问:
How to manage knex migrations in repository
What is the point of implementing migrations if the down script is missing while checking out to previous state of repository?

Example:

I have implemented migrations succesfully. Repo version is 0.0.1.

```<code>// repo version 0.0.1

migrations/
└── 001.js
</code>```

I have implemented a new feature that requires migrations in version 0.0.2:

```<code>// repo version 0.0.2

migrations/
├── 001.js
└── 002.js (new feature)
</code>```

I checkout repository to previous 0.0.1 version, due to a bug. But I cant run the down script of migration 002.js because at this point it didn exist yet:

```<code>// repo version 0.0.1

migrations/
└── 001.js
</code>```

So do I have to run the migration to the correct version manually before checking out to the previous state (npm run migrate:001)? This is a very easy and doable example. But it might get confusing over multiple branches.

Body:
What is the point of implementing migrations if the down script is missing while checking out to previous state of repository?

Example:

I have implemented migrations succesfully. Repo version is 0.0.1.

// repo version 0.0.1

migrations/
└── 001.js

I have implemented a new feature that requires migrations in version 0.0.2:

// repo version 0.0.2

migrations/
├── 001.js
└── 002.js (new feature)

I checkout repository to previous 0.0.1 version, due to a bug. But I cant run the down script of migration 002.js because at this point it didn exist yet:

// repo version 0.0.1

migrations/
└── 001.js

So do I have to run the migration to the correct version manually before checking out to the previous state (npm run migrate:001)? This is a very easy and doable example. But it might get confusing over multiple branches.


来源: stackexchange

问:
Using pywhatkit to send messages on Whatsapp
This is a well known bug with 'solutions' all over the internet:

When creating a pywhatkit auto-chat on Whatsapp -->

Tab opens

Message populates

The 'send' button is greyed out (I know this is a common bug)

I know this is a common bug and everyone is trying to get around this with something like the below (pyautogui, pynput, etc) but it's simply not working for me.

My dog has gone missing and I need to build a WA chatbot asap, can anyone help?

Ex.

```<code>        pyautogui.click()
        time.sleep(2)
        keyboard.press(Key.enter)
        keyboard.release(Key.enter)```

 time.sleep(5)
        pyautogui.click()
        time.sleep(2)
        keyboard.press(Key.enter)
        keyboard.release(Key.enter)

Expected the pynput to work.
```

ContentLicense: CC BY-SA 4.0

Body:
This is a well known bug with 'solutions' all over the internet:

When creating a pywhatkit auto-chat on Whatsapp -->

Tab opens

Message populates

The 'send' button is greyed out (I know this is a common bug)

I know this is a common bug and everyone is trying to get around this with something like the below (pyautogui, pynput, etc) but it's simply not working for me.

My dog has gone missing and I need to build a WA chatbot asap, can anyone help?

Ex.

        pyautogui.click()
        time.sleep(2)
        keyboard.press(Key.enter)
        keyboard.release(Key.enter)```

 time.sleep(5)
        pyautogui.click()
        time.sleep(2)
        keyboard.press(Key.enter)
        keyboard.release(Key.enter)

Expected the pynput to work.


问:
AJAX sending json data as text/xml
I have two sites using the same javascript code to interact with several web services. The code works perfectly in one site, but in the other, it is sending the data as text/xml. I have looked at the web config files in both sites and cannot spot anything that could cause the difference. The AjaxControlToolkit DLL files are the same. The AJAX call fails with an error 500 because the data is not in the proper form.

Code that makes the AJAX call:

```<code>function displaySessionNotifications() {
$.ajax({
type: "POST",
async: false,
url: "NotificationService.asmx/ListSessionNotifications",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({}),
success: function (data) {
$list = JSON.parse(data.d);
if (window.console.log) { window.console.log('Notification Service Msg Cnt: ' + $list.length) };
for (var i = 0; i < $list.length; i++) {
displayMessage($list[i].MessageText, $list[i].MessageType, $list[i].IsSticky, $list[i].jGrowlClass, $list[i].ContainerId);
};
if ($list.length > 0) {
clearSessionNotifications($list[0].SessionId);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("NotificationService/ListSessionNotifications failed: " + XMLHttpRequest.responseText);
}
});
}
</code>```

Watch Data from Firebug:

this
    Object { url="NotificationService.asmx/ListSessionNotifications", global=true, type="POST", more...}

```<code>XMLHttpRequest
    Object { readyState=4, status=0, statusText="error"}

errorThrown
    [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js :: <TOP_LEVEL> :: line 16" data: no] { name="NS_ERROR_FAILURE", message="Component returned fail...4005 (NS_ERROR_FAILURE)", result=2147500037, more...}

textStatus
    "error"
</code>```

Firebug console display of the code that works:

```<code>Server  ASP.NET Development Server/10.0.0.0
Date    Wed, 21 Sep 2011 17:44:39 GMT
X-AspNet-Version    4.0.30319
Cache-Control   private, max-age=0
Content-Type    application/json; charset=utf-8
Content-Length  10
Connection  Close
Request Headers
Host    127.0.0.1:54837
User-Agent  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0.2) Gecko/20100101 Firefox/6.0.2
Accept  application/json, text/javascript, */*; q=0.01
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection  keep-alive
Content-Type    application/json; charset=utf-8
x-requested-with    XMLHttpRequest
Referer http://127.0.0.1:54837/WebSite/TestNotifications.aspx
Content-Length  2
Cookie  JXID=80VR2F3uNRgK8YteuGgnAbsR; JXHID=false; Identifier=Id=20c8b636-7ec4-464f-b6dc-867d0924f475; enhanced=pass; Skin=Default; ASP.NET_SessionId=3nientky4k1hdy3gkfemne04; linkedin_oauth_BW-FUQKDybTn3R7TmZ-gHFmiFpzKY9ztqInF8jLVbHwNNkm_iSnIii26jEJts4wI_crc=null
</code>```

Same data for code that fails:

```<code>Response Headersview source
Server  ASP.NET Development Server/10.0.0.0
Date    Wed, 21 Sep 2011 18:34:01 GMT
X-AspNet-Version    4.0.30319
Cache-Control   private
Content-Type    text/html; charset=utf-8
Content-Length  4516
Connection  Close

Request Headersview source
    Host    127.0.0.1:60391
    User-Agent  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0.2) Gecko/20100101 Firefox/6.0.2
    Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    Accept-Language en-us,en;q=0.5
    Accept-Encoding gzip, deflate
    Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
    Connection  keep-alive
    Origin  http://localhost:60391
    Access-Control-Request-Me...    POST
    Access-Control-Request-He...    content-type,x-requested-with
    Pragma  no-cache
    Cache-Control   no-cache
</code>```

ContentLicense: CC BY-SA 3.0

Title: AJAX sending json data as text/xml

Body:
I have two sites using the same javascript code to interact with several web services. The code works perfectly in one site, but in the other, it is sending the data as text/xml. I have looked at the web config files in both sites and cannot spot anything that could cause the difference. The AjaxControlToolkit DLL files are the same. The AJAX call fails with an error 500 because the data is not in the proper form.

Code that makes the AJAX call:

function displaySessionNotifications() {
$.ajax({
type: "POST",
async: false,
url: "NotificationService.asmx/ListSessionNotifications",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({}),
success: function (data) {
$list = JSON.parse(data.d);
if (window.console.log) { window.console.log('Notification Service Msg Cnt: ' + $list.length) };
for (var i = 0; i < $list.length; i++) {
displayMessage($list[i].MessageText, $list[i].MessageType, $list[i].IsSticky, $list[i].jGrowlClass, $list[i].ContainerId);
};
if ($list.length > 0) {
clearSessionNotifications($list[0].SessionId);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("NotificationService/ListSessionNotifications failed: " + XMLHttpRequest.responseText);
}
});
}

Watch Data from Firebug:

this
    Object { url="NotificationService.asmx/ListSessionNotifications", global=true, type="POST", more...}

XMLHttpRequest
    Object { readyState=4, status=0, statusText="error"}

errorThrown
    [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js :: <TOP_LEVEL> :: line 16" data: no] { name="NS_ERROR_FAILURE", message="Component returned fail...4005 (NS_ERROR_FAILURE)", result=2147500037, more...}

textStatus
    "error"

Firebug console display of the code that works:

Server  ASP.NET Development Server/10.0.0.0
Date    Wed, 21 Sep 2011 17:44:39 GMT
X-AspNet-Version    4.0.30319
Cache-Control   private, max-age=0
Content-Type    application/json; charset=utf-8
Content-Length  10
Connection  Close
Request Headers
Host    127.0.0.1:54837
User-Agent  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0.2) Gecko/20100101 Firefox/6.0.2
Accept  application/json, text/javascript, */*; q=0.01
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection  keep-alive
Content-Type    application/json; charset=utf-8
x-requested-with    XMLHttpRequest
Referer http://127.0.0.1:54837/WebSite/TestNotifications.aspx
Content-Length  2
Cookie  JXID=80VR2F3uNRgK8YteuGgnAbsR; JXHID=false; Identifier=Id=20c8b636-7ec4-464f-b6dc-867d0924f475; enhanced=pass; Skin=Default; ASP.NET_SessionId=3nientky4k1hdy3gkfemne04; linkedin_oauth_BW-FUQKDybTn3R7TmZ-gHFmiFpzKY9ztqInF8jLVbHwNNkm_iSnIii26jEJts4wI_crc=null

Same data for code that fails:

Response Headersview source
Server  ASP.NET Development Server/10.0.0.0
Date    Wed, 21 Sep 2011 18:34:01 GMT
X-AspNet-Version    4.0.30319
Cache-Control   private
Content-Type    text/html; charset=utf-8
Content-Length  4516
Connection  Close

Request Headersview source
    Host    127.0.0.1:60391
    User-Agent  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0.2) Gecko/20100101 Firefox/6.0.2
    Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    Accept-Language en-us,en;q=0.5
    Accept-Encoding gzip, deflate
    Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
    Connection  keep-alive
    Origin  http://localhost:60391
    Access-Control-Request-Me...    POST
    Access-Control-Request-He...    content-type,x-requested-with
    Pragma  no-cache
    Cache-Control   no-cache


问:
Kotlin modify multiple lists of the same size
I need to transform multiple elements of immutable lists Object<List<T>>.  This is the way I'm doing it.  I show 3 lists, but in actuality I have about a dozen to transform.  The list size is the same fore all = 150.

```<code>val list1 = mutableListOf<Int>()
val list2 = mutableListOf<Int>()
val list3 = mutableListOf<Int>()
// x12 times

for (i in 0 until size){
    list1.add(i, object.list1[i].doSomething() )
    list2.add(i, object.list2[i].doSomethingElse() )
    list3.add(i, object.list3[i].doSomethingMore() )
    // x12 times
}
</code>```

A more idiomatic way would be to do something like this

```<code>val list1 =object.list1.map { it.doSomething() }
val list2 =object.list2.map { it.doSomethingElse() }
val list3 =object.list3.map { it.doSomethingMore() }
// x12 times
</code>```

It seems to me the first option is more efficient, but then again, I've read that Kotlin is in part designed to take advantage of the way chips are manufactured today with multiple cores and can handle the second option better.  I suspect for my iteration 12 x 150, it might not matter much either way.  At what point does it matter? For example, what if my iteration was 100 x 1000?  100000 x 1000000?

Body:
I need to transform multiple elements of immutable lists Object<List<T>>.  This is the way I'm doing it.  I show 3 lists, but in actuality I have about a dozen to transform.  The list size is the same fore all = 150.

val list1 = mutableListOf<Int>()
val list2 = mutableListOf<Int>()
val list3 = mutableListOf<Int>()
// x12 times

for (i in 0 until size){
    list1.add(i, object.list1[i].doSomething() )
    list2.add(i, object.list2[i].doSomethingElse() )
    list3.add(i, object.list3[i].doSomethingMore() )
    // x12 times
}

A more idiomatic way would be to do something like this

val list1 =object.list1.map { it.doSomething() }
val list2 =object.list2.map { it.doSomethingElse() }
val list3 =object.list3.map { it.doSomethingMore() }
// x12 times

It seems to me the first option is more efficient, but then again, I've read that Kotlin is in part designed to take advantage of the way chips are manufactured today with multiple cores and can handle the second option better.  I suspect for my iteration 12 x 150, it might not matter much either way.  At what point does it matter? For example, what if my iteration was 100 x 1000?  100000 x 1000000?


问:
Passing variables from Apple Shortcuts to AppleScript and returning the result
I'm trying to pass a string from Shortcuts to AppleScript, where AppleScript should truncate the string and return it back to Shortcuts, but I'm having difficulties. Any help would be appreciated Here's what I've got so far:

Shortcuts String to AppleScript, return Truncated results

I've tried using several methods to pass the text... I can pass original string through the applescript, and return the original text, but the truncated text is the problem.


问:
How to pass dictionary as an argument of dockerfile?
I want to download 2 build versions in my image, so for that I need 2 values in dockerfile and I am using loop over that but it didn't work

I have tried this

script.sh
declare -A count
count{1}=2
count{2}=3

docker build --build-arg version=$count

Dockerfile

ARG count

for i in "${count[@]}"; do \
sh create.sh ${count[$i]}

I am doing this, but it didn't pick the dictionary in docker build command, what should I do


问:
DFS Algorithm can't color acyclic graphs
```<code>#include "pch.h"
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
typedef struct node {
  int key;
  int color;
  int d;
  int f;
  struct node* parent;
  struct node* next;
} node;
typedef struct Graph {
  int nr;
  struct node** adj;
} Graph;

struct node* createNode(int v) {
    struct node* newNode = (node*)malloc(sizeof(struct node));
    newNode->key = v;
    newNode->next = NULL;
    return newNode;
}

struct Graph* createGraph(int n) {
    struct Graph* graph = (Graph*)malloc(sizeof(struct Graph));
    graph->nr = n;

    graph->adj = (node**)malloc((n+1) * sizeof(struct node*));

    int i;
    for (i = 0; i < n; i++)
        graph->adj[i] = NULL;

    return graph;

}

void addEdge(struct Graph* graph, int s, int d) {
    struct node* newNode = createNode(d);
    newNode->next = graph->adj[s];
    graph->adj[s] = newNode;

}

void printGraph(struct Graph* g) {
    for (int i = 0; i < g->nr; i++) {
        struct node* temp = g->adj[i];
        printf("\n%d -> ", i);
        while (temp) {
            printf("%d -> ", temp->key);
            temp = temp->next;
        }
        printf("\n");
    }
}

// topological sort + disc. time + final time pt noduri
void DFS_VISIT_test(Graph* G, node* u, int* time, node** s) {

    *time = *time + 1;
    u->d = *time;
    u->color = 1;

    node* v = G->adj[u->key];
    if (v) {
        while (v) {
            if (v->color == 0) {
                v->parent = u;
                DFS_VISIT_test(G, v, time,s);
            }
            v = v->next;
        }
    }
    //trebuia functie push dar am facut fara pt moment
    node* q = (node*)malloc(sizeof(node));
    q->next = (*s);
    q->key = u->key;
    (*s) = q;
    u->color = 2;
    *time = *time + 1;
    u->f = *time;

}

void DFStest(Graph* g) {
  node* s = (node*)malloc(sizeof(node));
  s->key = NULL;
  s->next = NULL;
  for (int i = 0; i < g->nr; i++) {
    g->adj[i]->color = 0;
    g->adj[i]->parent = NULL;
  }
  int time = 0;
  node* u;
  for (int i = 0; i < g->nr; i++) {
    u = g->adj[i];
    if (u->color == 0) {
      DFS_VISIT_test(g, u, &time,&s);
    }
  }
  //print stack
  while (s) {
    printf("%d", s->key);
    s = s->next;
  }
  printf("\n");
  //afisare discovery and final time
  for (int i = 0; i < g->nr; i++) printf("%d - %d %d\n", i, g->adj[i]-\>d, g->adj[i]->f);
}

int main(){
  Graph* g = createGraph(5);
  /*
   * pt topological sort, inca incerc
                             0
                           /   \
                          1     2
                          \      \
                           3     4

    */
    addEdge(g, 0, 2);
    addEdge(g, 0, 1);
    addEdge(g, 1, 3);
    addEdge(g, 2, 4);
    printGraph(g);
    DFStest(g);
    return 0;
}
</code>```

Through trial and error I discovered the problem but I am dumbfounded to the solution, I am sorry if it may be an obvious one but I tried it for 6 hours and I cannot wrap my head around it. Let's say I dynamically allocate the missing g->adj[i], then the if(v) while(v) will have a problem because the nodes don't point to anything, how do I solve this?

Body:
#include "pch.h"
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
typedef struct node {
  int key;
  int color;
  int d;
  int f;
  struct node* parent;
  struct node* next;
} node;
typedef struct Graph {
  int nr;
  struct node** adj;
} Graph;

struct node* createNode(int v) {
    struct node* newNode = (node*)malloc(sizeof(struct node));
    newNode->key = v;
    newNode->next = NULL;
    return newNode;
}

struct Graph* createGraph(int n) {
    struct Graph* graph = (Graph*)malloc(sizeof(struct Graph));
    graph->nr = n;

    graph->adj = (node**)malloc((n+1) * sizeof(struct node*));

    int i;
    for (i = 0; i < n; i++)
        graph->adj[i] = NULL;

    return graph;

}

void addEdge(struct Graph* graph, int s, int d) {
    struct node* newNode = createNode(d);
    newNode->next = graph->adj[s];
    graph->adj[s] = newNode;

}

void printGraph(struct Graph* g) {
    for (int i = 0; i < g->nr; i++) {
        struct node* temp = g->adj[i];
        printf("\n%d -> ", i);
        while (temp) {
            printf("%d -> ", temp->key);
            temp = temp->next;
        }
        printf("\n");
    }
}

// topological sort + disc. time + final time pt noduri
void DFS_VISIT_test(Graph* G, node* u, int* time, node** s) {

    *time = *time + 1;
    u->d = *time;
    u->color = 1;

    node* v = G->adj[u->key];
    if (v) {
        while (v) {
            if (v->color == 0) {
                v->parent = u;
                DFS_VISIT_test(G, v, time,s);
            }
            v = v->next;
        }
    }
    //trebuia functie push dar am facut fara pt moment
    node* q = (node*)malloc(sizeof(node));
    q->next = (*s);
    q->key = u->key;
    (*s) = q;
    u->color = 2;
    *time = *time + 1;
    u->f = *time;

}

void DFStest(Graph* g) {
  node* s = (node*)malloc(sizeof(node));
  s->key = NULL;
  s->next = NULL;
  for (int i = 0; i < g->nr; i++) {
    g->adj[i]->color = 0;
    g->adj[i]->parent = NULL;
  }
  int time = 0;
  node* u;
  for (int i = 0; i < g->nr; i++) {
    u = g->adj[i];
    if (u->color == 0) {
      DFS_VISIT_test(g, u, &time,&s);
    }
  }
  //print stack
  while (s) {
    printf("%d", s->key);
    s = s->next;
  }
  printf("\n");
  //afisare discovery and final time
  for (int i = 0; i < g->nr; i++) printf("%d - %d %d\n", i, g->adj[i]-\>d, g->adj[i]->f);
}

int main(){
  Graph* g = createGraph(5);
  /*
   * pt topological sort, inca incerc
                             0
                           /   \
                          1     2
                          \      \
                           3     4

    */
    addEdge(g, 0, 2);
    addEdge(g, 0, 1);
    addEdge(g, 1, 3);
    addEdge(g, 2, 4);
    printGraph(g);
    DFStest(g);
    return 0;
}

Through trial and error I discovered the problem but I am dumbfounded to the solution, I am sorry if it may be an obvious one but I tried it for 6 hours and I cannot wrap my head around it. Let's say I dynamically allocate the missing g->adj[i], then the if(v) while(v) will have a problem because the nodes don't point to anything, how do I solve this?


问:
Attempted import error: 'Amplify' is not exported from '@aws-amplify/core'
The error i get is as follows

Failed to compile.

./node_modules/@aws-amplify/api/lib-esm/API.js
Attempted import error: 'Amplify' is not exported from '@aws-amplify/core'.

i have tracked the issue to in my file to -

```<code>import { Amplify, ConsoleLogger as Logger } from '@aws-amplify/core';
var logger = new Logger('API')
</code>```

I have been following along with this tutorial https://www.youtube.com/watch?v=JgwI22y_eFA&lc=UgzvVN4OfDDVthrtwxF4AaABAg
and I get the error when i run npm run start at about 33.30 mins into it.

I have gone into my package.json file and changed the start from "react-scripts start" to "react-scripts --openssl-legacy-provider start" which is where i get a failure to compile but with the previous react-scripts start line i get the error-
Error: error:0308010C:digital envelope routines::unsupported
at new Hash (node:internal/crypto/hash:71:19)
at Object.createHash (node:crypto:133:10)
at module.exports (C:\Users\Swag\my-bookstore\cugs-bookstore\node_modules\webpack\lib\util\createHash.js:135:53)
at NormalModule._initBuildHash (C:\Users\Swag\my-bookstore\cugs-bookstore\node_modules\webpack\lib\NormalModule.js:417:16)
at handleParseError (C:\Users\Swag\my-bookstore\cugs-bookstore\node_modules\webpack\lib\NormalModule.js:471:10)
at C:\Users\Swag\my-bookstore\cugs-bookstore\node_modules\webpack\lib\NormalModule.js:503:5
at C:\Users\Swag\my-bookstore\cugs-bookstore\node_modules\webpack\lib\NormalModule.js:358:12
at C:\Users\Swag\my-bookstore\cugs-bookstore\node_modules\loader-runner\lib\LoaderRunner.js:373:3

Body:
The error i get is as follows

Failed to compile.

./node_modules/@aws-amplify/api/lib-esm/API.js
Attempted import error: 'Amplify' is not exported from '@aws-amplify/core'.

i have tracked the issue to in my file to -

import { Amplify, ConsoleLogger as Logger } from '@aws-amplify/core';
var logger = new Logger('API')

I have been following along with this tutorial https://www.youtube.com/watch?v=JgwI22y_eFA&lc=UgzvVN4OfDDVthrtwxF4AaABAg
and I get the error when i run npm run start at about 33.30 mins into it.

I have gone into my package.json file and changed the start from "react-scripts start" to "react-scripts --openssl-legacy-provider start" which is where i get a failure to compile but with the previous react-scripts start line i get the error-
Error: error:0308010C:digital envelope routines::unsupported
at new Hash (node:internal/crypto/hash:71:19)
at Object.createHash (node:crypto:133:10)
at module.exports (C:\Users\Swag\my-bookstore\cugs-bookstore\node_modules\webpack\lib\util\createHash.js:135:53)
at NormalModule._initBuildHash (C:\Users\Swag\my-bookstore\cugs-bookstore\node_modules\webpack\lib\NormalModule.js:417:16)
at handleParseError (C:\Users\Swag\my-bookstore\cugs-bookstore\node_modules\webpack\lib\NormalModule.js:471:10)
at C:\Users\Swag\my-bookstore\cugs-bookstore\node_modules\webpack\lib\NormalModule.js:503:5
at C:\Users\Swag\my-bookstore\cugs-bookstore\node_modules\webpack\lib\NormalModule.js:358:12
at C:\Users\Swag\my-bookstore\cugs-bookstore\node_modules\loader-runner\lib\LoaderRunner.js:373:3


问:
Visual Studio 2022. Problems with deployment
I finished my project in VS and the code is working perfectly (fetching data from an external API and storing it in a table in SSMS).
The problem is that it only works when I execute the project and then stops working unless I manually execute it again...I already build it and publish it in a .exe as well and opened it.... the same problem still.

I have written this refresh method:

```<code>   static async Task Main(string[] args)
        {
            // Set up a timer to refresh the data every 2 hours
            Timer timer = new Timer(TimeSpan.FromHours(2).TotalMilliseconds);
            timer.Elapsed += async (sender, e) => await RefreshData();
            timer.AutoReset = true;
            timer.Enabled = true;

            // Refresh the data for the first time
            await RefreshData();
        }

        static async Task RefreshData()
</code>```

can you please tell me what is wrong?
When I execute VS it brings the response correctly but then suddenly stops and if I want to refresh updates I need to execute it again...I would like this to be automatically refreshed every 2 hours and close VS without the need to open it again and execute it manually again...thanks a lot!!
PS: I don't get any error at all...is just not refreshing the database in ssms automatically.

Body:
I finished my project in VS and the code is working perfectly (fetching data from an external API and storing it in a table in SSMS).
The problem is that it only works when I execute the project and then stops working unless I manually execute it again...I already build it and publish it in a .exe as well and opened it.... the same problem still.

I have written this refresh method:

   static async Task Main(string[] args)
        {
            // Set up a timer to refresh the data every 2 hours
            Timer timer = new Timer(TimeSpan.FromHours(2).TotalMilliseconds);
            timer.Elapsed += async (sender, e) => await RefreshData();
            timer.AutoReset = true;
            timer.Enabled = true;

            // Refresh the data for the first time
            await RefreshData();
        }

        static async Task RefreshData()

can you please tell me what is wrong?
When I execute VS it brings the response correctly but then suddenly stops and if I want to refresh updates I need to execute it again...I would like this to be automatically refreshed every 2 hours and close VS without the need to open it again and execute it manually again...thanks a lot!!
PS: I don't get any error at all...is just not refreshing the database in ssms automatically.


问:
How to connect http request with async response from message broker
Problem:
In my api-gateway I call other microservices using a message broker and wait for response using method, annotated using Spring @MessageHandler. When response arrives how am I suppose to connect it with the waiting http request?

My solution is to hang request to CompletableFuture, generate a unique key and save the CompletableFuture with the key to the Spring Data Key-Value (or other in-memory) database and than call other services via Message Broker and send my request key along with the data. When async response arrives to the MessageHandler, check the in-memory database for my request key that is also part of the response and complete the stage.

If there are more nodes in cluster, I'll use a topic and check every key-value instance and complete stage only on the correct node, since I don't want to use any distributed cache for that.

Is it a good solution? Or how do you handle this particular problem?


问:
keras model only works with binary loss function for categorical data
I am training a text classification model to differentiate between 4 classes (3 different personality traits and "none"). I trained a simple keras model which worked fine. Recently I learned about transformers and wanted to build an even better model. I used this tutorial and tried to adapt it.

I use the german electra base model I found on huggingspace

```<code>transformer = reticulate::import('transformers')
ger_tokenizer <- transformer$ElectraTokenizer$from_pretrained('deepset/gelectra-base')
ger_model <- transformer$TFElectraModel$from_pretrained('deepset/gelectra-base')

input_size = 40L
epochs = 2
batch_size = 10
output_size = 4
</code>```

My data consists of 150k rated german sentences.

```<code>head(data)

      M     L     A     N text
  <dbl> <dbl> <dbl> <dbl> <chr>
    0     0     0     1 Sie fühlt sich nicht gut ...
    1     0     0     0 Aus Eifersucht führt sie die....
    0     0     0     1 Eine junge Forscherin hat gerade ihr Studium...
    1     1     0     0 Sie ist sehr gut und ihre Kollegen sind von...
</code>```

Around 3% had been assigned multiple classes (I removed them, because I was not sure how they would affect the training(?)). This is what my data looked like after shuffling, splitting train and test and tokenization

```<code>> train_[[1]][1:2, 1:9]
        1     2     3     4     5     6     7     8     9
 [1,] 102  1330 13999   943   285  2257  1413   697 13227
 [2,] 102   503  6254   307   924  1839   103     0     0

>  train_[[2]][1:2,]
      M L A N
 [1,] 0 0 0 1
 [2,] 0 0 1 0
</code>```

The data set is highly imbalanced (65% class 4, "none"), so I use class weights.

```<code>class_weight <- as.list(1/c(sum(data$M), sum(data$L), sum(data$A), sum(data$N)) %>% prop.table())
names(class_weight) <- c("0", "1", "2", "3")
</code>```

I freeze the weights of the pretrained model

```<code>keras::freeze_weights(ger_model)
</code>```

data and model architecture

```<code>tf_train = tensor_slices_dataset(list(train_[[1]], train_[[2]])) %>%
        dataset_batch(batch_size = batch_size, drop_remainder = TRUE) %>%
        dataset_shuffle(128) %>% dataset_repeat(epochs) %>%
        dataset_prefetch(tf$data$experimental$AUTOTUNE)

      tf_test = tensor_slices_dataset(list(test_[[1]], test_[[2]])) %>%
        dataset_batch(batch_size = batch_size)

input = layer_input(shape=c(input_size), dtype='int32')
hidden_mean = tf$reduce_mean(ger_model(input)[[1]], axis=1L) %>%
  layer_dense(64,activation = 'relu')

output = hidden_mean %>% layer_dense(units=output_size, activation='sigmoid')
model = keras_model(inputs=input, outputs = output)

model %>% compile(optimizer= tf$keras$optimizers$Adam(learning_rate=3e-5, epsilon=1e-08, clipnorm=1.0),
                  loss = tf$losses$CategoricalCrossentropy(from_logits=F),
                  metrics = tf$metrics$AUC())

history = model %>% keras::fit(tf_train, epochs=epochs,
                               validation_data=tf_test)
</code>```

Problem

Running it like this always results in the model predicting the 4th class. If I reduce the class weight for the 4th class even further, the model predicts another class 100% of the time.

"Solution"

I need to evenly distribute the data AND use BinaryCrossentropy (instead of Categorical) for the model to work.

```<code>id_even_dist <- c(sample(which(data$M==1), 12900),
                  sample(which(data$L==1), 12900),
                  sample(which(data$A==1), 12900),
                  sample(which(data$K==1), 12900))
data <- data[id_even_dist,]

model %>% compile(optimizer= tf$keras$optimizers$Adam(learning_rate=3e-5, epsilon=1e-08, clipnorm=1.0),
              loss = tf$losses$BinaryCrossentropy(from_logits=F),
              metrics = tf$metrics$AUC())
</code>```

I don't get why - Do you guys have any ideas?
I tried different activation functions, dropout/regularization, different number of layer (sizes), a lot of epochs. It didnt matter. Only if I used binary and even data, it worked. Interestingly, without the freezing of the gelectra layers it only returned around 95% to one class...

Bonus Question :)

Also, the model with BinaryCrossentropy and evenly distributed data results in 81% accuracy. Not that much more compared to the 76% of my "basic" keras model, considering it is 16hours of training vs 5 minutes and a lot more effort. Any Tips? I thought about removing filler words.

Body:
I am training a text classification model to differentiate between 4 classes (3 different personality traits and "none"). I trained a simple keras model which worked fine. Recently I learned about transformers and wanted to build an even better model. I used this tutorial and tried to adapt it.

I use the german electra base model I found on huggingspace

transformer = reticulate::import('transformers')
ger_tokenizer <- transformer$ElectraTokenizer$from_pretrained('deepset/gelectra-base')
ger_model <- transformer$TFElectraModel$from_pretrained('deepset/gelectra-base')

input_size = 40L
epochs = 2
batch_size = 10
output_size = 4

My data consists of 150k rated german sentences.

head(data)

      M     L     A     N text
  <dbl> <dbl> <dbl> <dbl> <chr>
    0     0     0     1 Sie fühlt sich nicht gut ...
    1     0     0     0 Aus Eifersucht führt sie die....
    0     0     0     1 Eine junge Forscherin hat gerade ihr Studium...
    1     1     0     0 Sie ist sehr gut und ihre Kollegen sind von...

Around 3% had been assigned multiple classes (I removed them, because I was not sure how they would affect the training(?)). This is what my data looked like after shuffling, splitting train and test and tokenization

> train_[[1]][1:2, 1:9]
        1     2     3     4     5     6     7     8     9
 [1,] 102  1330 13999   943   285  2257  1413   697 13227
 [2,] 102   503  6254   307   924  1839   103     0     0

>  train_[[2]][1:2,]
      M L A N
 [1,] 0 0 0 1
 [2,] 0 0 1 0

The data set is highly imbalanced (65% class 4, "none"), so I use class weights.

class_weight <- as.list(1/c(sum(data$M), sum(data$L), sum(data$A), sum(data$N)) %>% prop.table())
names(class_weight) <- c("0", "1", "2", "3")

I freeze the weights of the pretrained model

keras::freeze_weights(ger_model)

data and model architecture

tf_train = tensor_slices_dataset(list(train_[[1]], train_[[2]])) %>%
        dataset_batch(batch_size = batch_size, drop_remainder = TRUE) %>%
        dataset_shuffle(128) %>% dataset_repeat(epochs) %>%
        dataset_prefetch(tf$data$experimental$AUTOTUNE)

      tf_test = tensor_slices_dataset(list(test_[[1]], test_[[2]])) %>%
        dataset_batch(batch_size = batch_size)

input = layer_input(shape=c(input_size), dtype='int32')
hidden_mean = tf$reduce_mean(ger_model(input)[[1]], axis=1L) %>%
  layer_dense(64,activation = 'relu')

output = hidden_mean %>% layer_dense(units=output_size, activation='sigmoid')
model = keras_model(inputs=input, outputs = output)

model %>% compile(optimizer= tf$keras$optimizers$Adam(learning_rate=3e-5, epsilon=1e-08, clipnorm=1.0),
                  loss = tf$losses$CategoricalCrossentropy(from_logits=F),
                  metrics = tf$metrics$AUC())

history = model %>% keras::fit(tf_train, epochs=epochs,
                               validation_data=tf_test)

Problem

Running it like this always results in the model predicting the 4th class. If I reduce the class weight for the 4th class even further, the model predicts another class 100% of the time.

"Solution"

I need to evenly distribute the data AND use BinaryCrossentropy (instead of Categorical) for the model to work.

id_even_dist <- c(sample(which(data$M==1), 12900),
                  sample(which(data$L==1), 12900),
                  sample(which(data$A==1), 12900),
                  sample(which(data$K==1), 12900))
data <- data[id_even_dist,]

model %>% compile(optimizer= tf$keras$optimizers$Adam(learning_rate=3e-5, epsilon=1e-08, clipnorm=1.0),
              loss = tf$losses$BinaryCrossentropy(from_logits=F),
              metrics = tf$metrics$AUC())

I don't get why - Do you guys have any ideas?
I tried different activation functions, dropout/regularization, different number of layer (sizes), a lot of epochs. It didnt matter. Only if I used binary and even data, it worked. Interestingly, without the freezing of the gelectra layers it only returned around 95% to one class...

Bonus Question :)

Also, the model with BinaryCrossentropy and evenly distributed data results in 81% accuracy. Not that much more compared to the 76% of my "basic" keras model, considering it is 16hours of training vs 5 minutes and a lot more effort. Any Tips? I thought about removing filler words.


问:
how do i check is it safe for writing in c++
in this function where i am trying to write something on a disk, how can i check if the part of the disk is empty and it's safe to write on that part so i wouldn't lose data.

i tried finding answer to this and saw peek function but it seems that it's not working with that, I get an error with it

```<code>void write_sector(int num){
    char diskName[] = "/dev/sda";                                       //disk name
    std::ofstream disk(diskName, std::ios_base::binary);                //opening the disk for output
    std::string diskError = std::string() + diskName + ": ";

    if(!disk){
    throw(std::runtime_error(diskError + std::strerror(errno)));
    }

    disk.seekp(512 * num);                                              //changing position to specific sector

    if(!disk){
    throw(std::runtime_error(diskError + std::strerror(errno)));
    }

    disk << "MAGIC";                                                    //writing in sector

    if(!disk){
    throw(std::runtime_error(diskError + std::strerror(errno)));
    }

    disk.close();
}
</code>```

Body:
in this function where i am trying to write something on a disk, how can i check if the part of the disk is empty and it's safe to write on that part so i wouldn't lose data.

i tried finding answer to this and saw peek function but it seems that it's not working with that, I get an error with it

void write_sector(int num){
    char diskName[] = "/dev/sda";                                       //disk name
    std::ofstream disk(diskName, std::ios_base::binary);                //opening the disk for output
    std::string diskError = std::string() + diskName + ": ";

    if(!disk){
    throw(std::runtime_error(diskError + std::strerror(errno)));
    }

    disk.seekp(512 * num);                                              //changing position to specific sector

    if(!disk){
    throw(std::runtime_error(diskError + std::strerror(errno)));
    }

    disk << "MAGIC";                                                    //writing in sector

    if(!disk){
    throw(std::runtime_error(diskError + std::strerror(errno)));
    }

    disk.close();
}


问:
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'users.User'
I am working on a Django chat application using Django channels but I have run into a problem. I am getting the error AttributeError: Manager isn't available; 'auth.User' has been swapped for 'users.User' in my console and I cannot figure out how to solve this issue. In my project, I am checking whether users have an history in their chat, and if there is no history I create one.
Inside the users app where I am registering users, I have used the AbstractUser model and therefore I have AUTH_USER_MODEL='users.User' inside the setting.py.
Here is my Models.py for the chat application:

```<code>from django.contrib.auth import get_user_model
from django.conf import settings

User = get_user_model()

class TrackingModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

class Thread(TrackingModel):
    THREAD_TYPE = (
        ('personal', 'Personal'),
        ('group', 'Group')
    )

    name = models.CharField(max_length=50, null=True, blank=True)
    thread_type = models.CharField(max_length=15, choices=THREAD_TYPE, default='personal')
    users = models.ManyToManyField('users.User')

    objects = ThreadManager()

    def __str__(self) -> str:
        if self.thread_type == 'personal' and self.users.count() == 2:
            return f'{self.users.first()} and {self.users.last()}'
        return f'{self.name}'

class Message(TrackingModel):
    thread = models.ForeignKey(Thread, on_delete=models.CASCADE)
    sender = models.ForeignKey('users.User', on_delete=models.CASCADE)
    text = models.TextField(blank=False, null=False)

    def __str__(self) -> str:
        return f'From <Thread - {self.thread}>'
</code>```

And here is the Managers.py file:

```<code>User = get_user_model()

class ThreadManager(models.Manager):
    def get_or_create_personal_thread(self, user1, user2):
        threads = self.get_queryset().filter(thread_type='personal')
        threads = threads.filter(users__in=[user1, user2]).distinct()
        threads = threads.annotate(u_count=Count('users')).filter(u_count=2)
        if threads.exists():
            return threads.first()
        else:
            thread = self.create(thread_type='personal')
            thread.users.add(user1)
            thread.users.add(user2)
            return thread

    def by_user(self, user):
        return self.get_queryset().filter(users__in=[user])
</code>```

Any help will be highly appreciated.

I have tried replacing the line users = models.ManyToManyField('users.User') with users = models.ManyToManyField('auth.User') but it still gives the same error.

Body:
I am working on a Django chat application using Django channels but I have run into a problem. I am getting the error AttributeError: Manager isn't available; 'auth.User' has been swapped for 'users.User' in my console and I cannot figure out how to solve this issue. In my project, I am checking whether users have an history in their chat, and if there is no history I create one.
Inside the users app where I am registering users, I have used the AbstractUser model and therefore I have AUTH_USER_MODEL='users.User' inside the setting.py.
Here is my Models.py for the chat application:

from django.contrib.auth import get_user_model
from django.conf import settings

User = get_user_model()

class TrackingModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

class Thread(TrackingModel):
    THREAD_TYPE = (
        ('personal', 'Personal'),
        ('group', 'Group')
    )

    name = models.CharField(max_length=50, null=True, blank=True)
    thread_type = models.CharField(max_length=15, choices=THREAD_TYPE, default='personal')
    users = models.ManyToManyField('users.User')

    objects = ThreadManager()

    def __str__(self) -> str:
        if self.thread_type == 'personal' and self.users.count() == 2:
            return f'{self.users.first()} and {self.users.last()}'
        return f'{self.name}'

class Message(TrackingModel):
    thread = models.ForeignKey(Thread, on_delete=models.CASCADE)
    sender = models.ForeignKey('users.User', on_delete=models.CASCADE)
    text = models.TextField(blank=False, null=False)

    def __str__(self) -> str:
        return f'From <Thread - {self.thread}>'

And here is the Managers.py file:

User = get_user_model()

class ThreadManager(models.Manager):
    def get_or_create_personal_thread(self, user1, user2):
        threads = self.get_queryset().filter(thread_type='personal')
        threads = threads.filter(users__in=[user1, user2]).distinct()
        threads = threads.annotate(u_count=Count('users')).filter(u_count=2)
        if threads.exists():
            return threads.first()
        else:
            thread = self.create(thread_type='personal')
            thread.users.add(user1)
            thread.users.add(user2)
            return thread

    def by_user(self, user):
        return self.get_queryset().filter(users__in=[user])

Any help will be highly appreciated.

I have tried replacing the line users = models.ManyToManyField('users.User') with users = models.ManyToManyField('auth.User') but it still gives the same error.


问:
Why is it whenever I use std::ios:trunc, the stream is falsy
So I have the following code:

```<code>#include <iostream>
#include <fstream>
#include <string>

void writeSingle(std::fstream &myFileStream)
{
    myFileStream.open("my_file2", std::ios::trunc);
    if (!myFileStream)
    {
        std::cout << "File not created!\n";
    }
    else
    {
        std::cout << "File created successfully!\n";
        myFileStream << "Line 1\n";
        myFileStream << "Line 2\n";
        myFileStream << "Line 3\n";
        myFileStream.close();
    }
}

int main()
{
    std::fstream myFileStream;
    writeSingle(myFileStream);
    return 0;
}
</code>```

My question is, whenever I use std::ios::trunc, be it in a combination with app (std::ios::trunc | std::ios::app) and regardless to whether the file exists or not, the program
ends up in the !myFileStream block. With only std::ios::out and std::ios::app the program works as expected.

Why is it so? Can someone provide at least one working example with std::ios::trunc?
Thanks.

Body:
So I have the following code:

#include <iostream>
#include <fstream>
#include <string>

void writeSingle(std::fstream &myFileStream)
{
    myFileStream.open("my_file2", std::ios::trunc);
    if (!myFileStream)
    {
        std::cout << "File not created!\n";
    }
    else
    {
        std::cout << "File created successfully!\n";
        myFileStream << "Line 1\n";
        myFileStream << "Line 2\n";
        myFileStream << "Line 3\n";
        myFileStream.close();
    }
}

int main()
{
    std::fstream myFileStream;
    writeSingle(myFileStream);
    return 0;
}

My question is, whenever I use std::ios::trunc, be it in a combination with app (std::ios::trunc | std::ios::app) and regardless to whether the file exists or not, the program
ends up in the !myFileStream block. With only std::ios::out and std::ios::app the program works as expected.

Why is it so? Can someone provide at least one working example with std::ios::trunc?
Thanks.


问:
'Error Indexes must have a projection specified' while creating a DynamoDB table with Kotlin
While trying to create a table using the Kotlin client for DynamoDB, I'm getting this error:

```<code>Indexes must have a projection specified
aws.sdk.kotlin.services.dynamodb.model.DynamoDbException: Indexes must have a projection specified
at app//aws.sdk.kotlin.services.dynamodb.transform.CreateTableOperationDeserializerKt.throwCreateTableError(CreateTableOperationDeserializer.kt:64)
</code>```

However, my table definition specifies a projection:

```<code>Projection {
  projectionType = ProjectionType.All
}
</code>```

This is the full table definition:

```<code>        CreateTableRequest {
            tableName = Config.tableName
            attributeDefinitions = listOf(
                AttributeDefinition { attributeName = "PK"; attributeType = ScalarAttributeType.S },
                AttributeDefinition { attributeName = "SK"; attributeType = ScalarAttributeType.S },
                AttributeDefinition { attributeName = "GSI1PK"; attributeType = ScalarAttributeType.S },
                AttributeDefinition { attributeName = "GSI1SK"; attributeType = ScalarAttributeType.S },
            )
            keySchema = listOf(
                KeySchemaElement { attributeName = "PK"; keyType = KeyType.Hash },
                KeySchemaElement { attributeName = "SK"; keyType = KeyType.Range },
            )
            globalSecondaryIndexes = listOf(
                GlobalSecondaryIndex {
                    indexName = "GSI1"
                    keySchema = listOf(
                        KeySchemaElement { attributeName = "GSI1PK"; keyType = KeyType.Hash },
                        KeySchemaElement { attributeName = "GSI1SK"; keyType = KeyType.Range }
                    )
                    Projection { projectionType = ProjectionType.All }
                },
            )
        }
</code>```

So, what could be missing?

Body:
While trying to create a table using the Kotlin client for DynamoDB, I'm getting this error:

Indexes must have a projection specified
aws.sdk.kotlin.services.dynamodb.model.DynamoDbException: Indexes must have a projection specified
at app//aws.sdk.kotlin.services.dynamodb.transform.CreateTableOperationDeserializerKt.throwCreateTableError(CreateTableOperationDeserializer.kt:64)

However, my table definition specifies a projection:

Projection {
  projectionType = ProjectionType.All
}

This is the full table definition:

        CreateTableRequest {
            tableName = Config.tableName
            attributeDefinitions = listOf(
                AttributeDefinition { attributeName = "PK"; attributeType = ScalarAttributeType.S },
                AttributeDefinition { attributeName = "SK"; attributeType = ScalarAttributeType.S },
                AttributeDefinition { attributeName = "GSI1PK"; attributeType = ScalarAttributeType.S },
                AttributeDefinition { attributeName = "GSI1SK"; attributeType = ScalarAttributeType.S },
            )
            keySchema = listOf(
                KeySchemaElement { attributeName = "PK"; keyType = KeyType.Hash },
                KeySchemaElement { attributeName = "SK"; keyType = KeyType.Range },
            )
            globalSecondaryIndexes = listOf(
                GlobalSecondaryIndex {
                    indexName = "GSI1"
                    keySchema = listOf(
                        KeySchemaElement { attributeName = "GSI1PK"; keyType = KeyType.Hash },
                        KeySchemaElement { attributeName = "GSI1SK"; keyType = KeyType.Range }
                    )
                    Projection { projectionType = ProjectionType.All }
                },
            )
        }

So, what could be missing?


问:
RAM and epoch time is different across different machines and RAM keeps increasing when training a neural network
I was training a neural nets with exactly the same code and dataset in 2 different machines:

the first machine: NVIDIA GeForce RTX 3090 Ti 24GB with 125 GB of RAM

the second machine: NVIDIA RTX A6000 48 GB with 43 GB of RAM

the third machine: NVIDIA A100-SXM-80GB with 88 GB of RAM

On the first machine, 1 epoch took ~7.5 hours, 3 hours into the first epoch the it consumed 27 GB of RAM.

On the second machine it didn't finish the first epoch because it ran out of RAM (estimated 1 epoch would take 6 hrs), 3 hours into the first epoch the it consumed 35 GB of RAM.

On the third machine, 1 epoch took 2h 45m, 3 hours into the first epoch the it consumed 60 GB of RAM.

On all of the machines, the training stopped because the RAM kept increasing until it ran out of memory.

Can someone please explain to me about this phenomenon and what is the possible solution of this RAM consumption? I am using PyTorch and I checked I didn't the issue explained here about the loss (I use loss.item()).


问:
AAAttribution.attributionToken() produces Error posting to Attribution server
I want to use the AdServices framework in my app but I keep getting an error.

I've added AdServices as a framework

I've imported it

I try calling let token = try AAAttribution.attributionToken()

When running on device, this fails with the internalError code, saying Error posting to Attribution server.

Why? Nowhere online explains why this could be or how to fix it. I'm running in debug mode, could it be that?

On the simulator it's even worse and can't generate a token, but I'm not too bothered about that.


问:
Search/Browse function not working on mobile but works on desktop when inspecting mobile
I am making a website with a read only Api key and I realized my search/browse function works on desktop but not mobile. It works when i inspect mobile on my computer but when im actually on my phone it does not. Im confused as to why it would work when inspecting mobile on my desktop but not when i am actually on my phone. Anyone have a solution for that? The github and website link are below, thank you!
https://ryancacicedo.github.io/AnimeStudio/
https://github.com/RyanCacicedo/AnimeStudio

I have tried using 'OnClick' and 'Onmousedown' and it is the same result for both of them. I am not really sure what else to try since it works when i inspect mobile on desktop but not when i am actually on a mobile phone. I can't seem to find others who have had this problem either.


问:
My http request is sending back a blank map
How do I send a map as a response to an HTTP request? Currently I am sending an array of strings as part of the request. I want to send a nested map along with a bool as a response to a post request. The bool sends find but the map always comes back as empty. I did a bit of research to use the Object.entries method but no dice. Heres the client code:

```<code>const { response, request } = require('express');
const express = require('express');
const readline = require('readline/promises');
const app = express();
const port = 3000;
const axios = require('axios');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
    if (parsedInput > 0 && parsedInput <= 8) {
          let listOfNames = [];
          for (let i=0; i<parsedInput; i++) {
            let name = await rl.question(`Enter name #${i}\n`);
            listOfNames.push(name);
            console.log(`Added ${name} to list of players\n`);
          }
          const serverResponse = axios.post('http://localhost:3000/start', {
           params: { names: listOfNames },
          }).then(function (response) {
            const recievedMap = new Map(Object.entries(response.data.scoreboard));
            console.log(recievedMap);
          })
          .catch(function (error) {
            console.log(error);
          });
        }
</code>```

Server code:

```<code>const express = require('express');
var bodyParser = require('body-parser');
const app = express()
app.use(bodyParser.json());
const port = 3000
var listOfNames = [];
const scoreboard = new Map();
app.post('/start', async (req, res) => {
  listOfNames = req.body.params.names;
  for(let i = 0; i < listOfNames.length; i++){
    scoreboard.set(listOfNames[i],[]);
  }
  var responseObj = {
    gameRunning: true,
    scoreboard: JSON.stringify(scoreboard),
  };
  res.status(200).send(responseObj);
});
app.get('/', function(req, res, next) {
  res.send("Welcome to the homepage of bowling");
})
app.listen(port, () => {
  console.log('Listening to request on port 3000');
});
</code>```

Output:

```<code>Choose a number:
1)Start a bowling game
2)Exit simulation
1
Ok how many players will there be (MAX: 8 players)
1
Enter name #0
dadada
Added dadada to list of players

{}
</code>```

EDIT: Axios was sending data fine, however Im having issues accessing it when in my web server. Since I cant access any object, I return nothing. Am I refering to my request.body incorrectly?

Body:
How do I send a map as a response to an HTTP request? Currently I am sending an array of strings as part of the request. I want to send a nested map along with a bool as a response to a post request. The bool sends find but the map always comes back as empty. I did a bit of research to use the Object.entries method but no dice. Heres the client code:

const { response, request } = require('express');
const express = require('express');
const readline = require('readline/promises');
const app = express();
const port = 3000;
const axios = require('axios');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
    if (parsedInput > 0 && parsedInput <= 8) {
          let listOfNames = [];
          for (let i=0; i<parsedInput; i++) {
            let name = await rl.question(`Enter name #${i}\n`);
            listOfNames.push(name);
            console.log(`Added ${name} to list of players\n`);
          }
          const serverResponse = axios.post('http://localhost:3000/start', {
           params: { names: listOfNames },
          }).then(function (response) {
            const recievedMap = new Map(Object.entries(response.data.scoreboard));
            console.log(recievedMap);
          })
          .catch(function (error) {
            console.log(error);
          });
        }

Server code:

const express = require('express');
var bodyParser = require('body-parser');
const app = express()
app.use(bodyParser.json());
const port = 3000
var listOfNames = [];
const scoreboard = new Map();
app.post('/start', async (req, res) => {
  listOfNames = req.body.params.names;
  for(let i = 0; i < listOfNames.length; i++){
    scoreboard.set(listOfNames[i],[]);
  }
  var responseObj = {
    gameRunning: true,
    scoreboard: JSON.stringify(scoreboard),
  };
  res.status(200).send(responseObj);
});
app.get('/', function(req, res, next) {
  res.send("Welcome to the homepage of bowling");
})
app.listen(port, () => {
  console.log('Listening to request on port 3000');
});

Output:

Choose a number:
1)Start a bowling game
2)Exit simulation
1
Ok how many players will there be (MAX: 8 players)
1
Enter name #0
dadada
Added dadada to list of players

{}

EDIT: Axios was sending data fine, however Im having issues accessing it when in my web server. Since I cant access any object, I return nothing. Am I refering to my request.body incorrectly?


问:
React Use Query and Jest
I'm trying to test my nextjs app with Jest but according to this example , I have to tell Axios to  use node adapter while running in testing mode but for mome reason I'm getting this error.

jest.setup.js

```<code>import '@testing-library/jest-dom/extend-expect'
import axios from 'axios';
axios.defaults.adapter = require('axios/lib/adapters/http');
</code>```

index.test.js

```<code>const mockedUseRoomsQuery = useRoomsQuery;
jest.mock("../__mocks__/roomMockData.js");

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      retry: false,
    },
  },
});
const wrapper = ({ children }) => (
  <QueryClientProvider client={queryClient}>
    {children}
  </QueryClientProvider>
);

describe("Fetch all rooms", () => {
  it("fetches all rooms", async () => {
    nock("https://63b29d465901da0ab368e025.mockapi.io", {
      reqheaders: { "app-id": () => true },
    })
      .persist()
      .get("/api/v1/rooms")
      .reply(200, roomData);
    const { result, waitFor } = renderHook(() => useRoomsQuery(), { wrapper });
    await waitFor(() => result.current.isSuccess);
    console.log("data returned", result.current);
  }, 10000);
});

</code>```

What am I doing wrong?

Title: React Use Query and Jest

Body:
I'm trying to test my nextjs app with Jest but according to this example , I have to tell Axios to  use node adapter while running in testing mode but for mome reason I'm getting this error.

jest.setup.js

import '@testing-library/jest-dom/extend-expect'
import axios from 'axios';
axios.defaults.adapter = require('axios/lib/adapters/http');

index.test.js

const mockedUseRoomsQuery = useRoomsQuery;
jest.mock("../__mocks__/roomMockData.js");

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      retry: false,
    },
  },
});
const wrapper = ({ children }) => (
  <QueryClientProvider client={queryClient}>
    {children}
  </QueryClientProvider>
);

describe("Fetch all rooms", () => {
  it("fetches all rooms", async () => {
    nock("https://63b29d465901da0ab368e025.mockapi.io", {
      reqheaders: { "app-id": () => true },
    })
      .persist()
      .get("/api/v1/rooms")
      .reply(200, roomData);
    const { result, waitFor } = renderHook(() => useRoomsQuery(), { wrapper });
    await waitFor(() => result.current.isSuccess);
    console.log("data returned", result.current);
  }, 10000);
});

What am I doing wrong?


问:
How to upload files to dropbox from a submission form on my website?
I want to make a webpage with form in it that allow users to upload files to it and fill in some input fields. The uploaded files will be upload to my own dropbox account(not the user's dropbox account and not from the user's dropbox). Taking it to the next step it will be very helpful if i can change my dropbox folder based of the values in the input fields and also I can rename the file.

For example let say i have a form with a dropdown input field with option pubg or fortnite and a input field for uploading file. Dropbox folder and the file name change based on the option user select.

I am a front end developer so it will be helful if i dont have to deal with backend or php. And i am completely open to opinion if there is a better alternative to dropbox like a cheaper storage service or according to my need.


问:
Hide pentagon shaped form from ripple effect
I have the following layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.camera.view.PreviewView
        android:id="@+id/viewFinder"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/btn_image_select"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_margin="20dp"
        app:icon="@drawable/baseline_photo_24"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        style="@style/MaterialIconButtonCircledDarkTransparentStyle"
        />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/btn_image_capture"
        android:layout_width="75dp"
        android:layout_height="75dp"
        android:layout_margin="20dp"
        app:strokeWidth="2dp"
        app:strokeColor="@color/white"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        style="@style/MaterialIconButtonCircledLightTransparentStyle"
        />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

With the following style:

```<code><style name="MaterialIconButtonCircledDarkTransparentStyle">
    <item name="android:insetLeft">0dp</item>
    <item name="android:insetTop">0dp</item>
    <item name="android:insetRight">0dp</item>
    <item name="android:insetBottom">0dp</item>
    <item name="iconPadding">0dp</item>
    <item name="iconGravity">textStart</item>

    <item name="background">@color/BlackTransparent</item>
    <item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlayMaterialIconButtonCircular</item>
</style>

<style name="MaterialIconButtonCircledLightTransparentStyle" parent="MaterialIconButtonCircledDarkTransparentStyle">
    <item name="android:backgroundTint">@color/LightGrayTransparent</item>
</style>

<style name="ShapeAppearanceOverlayMaterialIconButtonCircular" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">50%</item>
</style>

<color name="LightGrayTransparent">#80C0C0C0</color>
<color name="BlackTransparent">#6A000000</color>
</code>```

Which looks like this:

As you can see there is a random pentagon shaped style which is visible when I have a transparent backgroundTint.
Any idea how I can hide the pentagon shaped form?
I tried setting the ripple color to null and other options, but none of them worked unfourtantly.

Body:
I have the following layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.camera.view.PreviewView
        android:id="@+id/viewFinder"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/btn_image_select"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_margin="20dp"
        app:icon="@drawable/baseline_photo_24"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        style="@style/MaterialIconButtonCircledDarkTransparentStyle"
        />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/btn_image_capture"
        android:layout_width="75dp"
        android:layout_height="75dp"
        android:layout_margin="20dp"
        app:strokeWidth="2dp"
        app:strokeColor="@color/white"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        style="@style/MaterialIconButtonCircledLightTransparentStyle"
        />

</androidx.constraintlayout.widget.ConstraintLayout>

With the following style:

<color name="LightGrayTransparent">#80C0C0C0</color>
<color name="BlackTransparent">#6A000000</color>

Which looks like this:

As you can see there is a random pentagon shaped style which is visible when I have a transparent backgroundTint.
Any idea how I can hide the pentagon shaped form?
I tried setting the ripple color to null and other options, but none of them worked unfourtantly.


问:
Setting page icon via the API - reusing the page first block image
I am trying to use first image found on the page and set it as a page cover and page icon. The reason is because in the page I can just paste the image and create a gallery like this

, and then I would like to set this image as page icon, so that it can be used in the rollup before the text, like this

I tried copying the file object from the block and just reusing the url for the page icon or banner, and it does set it to something, as in the client I can see a black box as an icon, but it is not set to the image.

Are there some additional rules for icons, if so what? Or how could this be achieved some other way?


问:
Why doesn't the color on my geom_line change?
I wonder why the color on my geom_line doesn't change? I have the following code and at the bottom of the post, you will find the image.

```<code>color <- c("Without interventions" = "navyblue", "With piecewise interventions" = "red", "With linear interventions" = "yellow")

ggplot() +
  geom_line(data = NULL, aes(x=c, y=d, color= "With linear interventions")) +
  geom_line(data = NULL, aes(x=x, y=y, color = "Without interventions")) +
  labs(x="time (days)", y="numbers of infectives") +
  geom_vline(xintercept = 10, linetype = "dotted") +
  geom_vline(xintercept = 30, linetype = "dotted") +
  geom_vline(xintercept = 60, linetype = "dotted") +
  geom_vline(xintercept = 70, linetype = "dotted") +
  theme(legend.position="bottom") +
  scale_color_discrete(name="")
</code>```

Body:
I wonder why the color on my geom_line doesn't change? I have the following code and at the bottom of the post, you will find the image.

color <- c("Without interventions" = "navyblue", "With piecewise interventions" = "red", "With linear interventions" = "yellow")

ggplot() +
  geom_line(data = NULL, aes(x=c, y=d, color= "With linear interventions")) +
  geom_line(data = NULL, aes(x=x, y=y, color = "Without interventions")) +
  labs(x="time (days)", y="numbers of infectives") +
  geom_vline(xintercept = 10, linetype = "dotted") +
  geom_vline(xintercept = 30, linetype = "dotted") +
  geom_vline(xintercept = 60, linetype = "dotted") +
  geom_vline(xintercept = 70, linetype = "dotted") +
  theme(legend.position="bottom") +
  scale_color_discrete(name="")


问:
Convert string to array in javsacript
i have a string containg an array. i can convert it using loop over string with different conditions but that will be slow. so is there any direct way to convert string which has array in it to an actuall array?
my javascript string looks like this

```<code>arr_str = '["value1", "value2", "value3"]'
</code>```

i want to convert it in array something like this

```<code>arr = ["value1", "value2", "value3"]
</code>```

Title: Convert string to array in javsacript

Body:
i have a string containg an array. i can convert it using loop over string with different conditions but that will be slow. so is there any direct way to convert string which has array in it to an actuall array?
my javascript string looks like this

arr_str = '["value1", "value2", "value3"]'

i want to convert it in array something like this

arr = ["value1", "value2", "value3"]


问:
I get results only for the last class, not all of them
I am doing a NLP work (just starting to learn) with policy descriptions (corpus) and policy areas (classes). I have calculated the word frequency, and made a list of words with the 100 most frequent terms. I have 27 classes. Some words are relevant for some classes but irrelevant for others, so I cant clean them from all the data set. I want to remove the words in the list from the classes where they are present in LESS than 50% od the rows, but when i print dfen_all it gives me only the results for the last class.
It seems that somehow it is not mergin the datasets for each class... Iàve tried a few modifications but nothing worked.

```<code>for term in most_common_words_list:
    for class_num in arr2:
        df_class = dfen[dfen['Policycat1'] == class_num] # get dataframe of class
        num_with_term = len(df_class[df_class['corpus3'].str.contains(term, case=False)])# count number of records with term
        num_total= len(df_class['corpus3'])
        percent = num_with_term/num_total
        if percent < 0.5:
            df_class['corpus3_clean'] = df_class['corpus3'].str.replace(term, '') # delete term from records

#join all dataframes into a single dataframe
dfen_all = pd.DataFrame()
for class_num in class_values:
    dfen_all = pd.concat([dfen_all, df_class[df_class['Policycat1'] == class_num]])

#save the dataframe to a csv
#df_all.to_csv('all_classes.csv', index=False)
dfen_all['totalwords_c3cl'] = dfen_all['corpus3_clean'].str.split().str.len()
dfen_all
</code>```

I am expecting to get all the results together in a daframe, not only the last label.

This is my first question, I apologize if I missed something. Thanks a lot!

Body:
I am doing a NLP work (just starting to learn) with policy descriptions (corpus) and policy areas (classes). I have calculated the word frequency, and made a list of words with the 100 most frequent terms. I have 27 classes. Some words are relevant for some classes but irrelevant for others, so I cant clean them from all the data set. I want to remove the words in the list from the classes where they are present in LESS than 50% od the rows, but when i print dfen_all it gives me only the results for the last class.
It seems that somehow it is not mergin the datasets for each class... Iàve tried a few modifications but nothing worked.

for term in most_common_words_list:
    for class_num in arr2:
        df_class = dfen[dfen['Policycat1'] == class_num] # get dataframe of class
        num_with_term = len(df_class[df_class['corpus3'].str.contains(term, case=False)])# count number of records with term
        num_total= len(df_class['corpus3'])
        percent = num_with_term/num_total
        if percent < 0.5:
            df_class['corpus3_clean'] = df_class['corpus3'].str.replace(term, '') # delete term from records

#join all dataframes into a single dataframe
dfen_all = pd.DataFrame()
for class_num in class_values:
    dfen_all = pd.concat([dfen_all, df_class[df_class['Policycat1'] == class_num]])

#save the dataframe to a csv
#df_all.to_csv('all_classes.csv', index=False)
dfen_all['totalwords_c3cl'] = dfen_all['corpus3_clean'].str.split().str.len()
dfen_all

I am expecting to get all the results together in a daframe, not only the last label.

This is my first question, I apologize if I missed something. Thanks a lot!


问:
How to disconnect clients from hotspot android
I'm writing app that should manage clients that connected to hotspot. I'm tried find some info about "how to disconnect users from hotspot android" but i found nothing. (api 29)
Can somebody help me, please?</p>


问:
using canvas api to create an image with a background
Im trying to create an image using canvas api. The problem is the image isnt loading no matter what I try, here is my code snippet, Im waiting for the image to load but the generated image doesnt have a background. Can anyone spot what I've done wrong? Thanks in advance:

```<code>
const backgroundImage = new Image();
    backgroundImage.src = '../Assets/pattern.png';

    return (backgroundImage.onload = () => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = width;
        canvas.height = height;

        if (!ctx) {
            return '';
        }

        ctx.drawImage(backgroundImage, 0, 0, width, height);

        ctx.fillRect(0, 0, width, height);
        ctx.font = 'bold italic 48px Montserrat';
        ctx.fillStyle = 'white';

        return canvas.toDataURL('image/png');
    });

</code>```

I've tried different import styles, I've tried using other image sources (unsplash) but no luck

Body:
Im trying to create an image using canvas api. The problem is the image isnt loading no matter what I try, here is my code snippet, Im waiting for the image to load but the generated image doesnt have a background. Can anyone spot what I've done wrong? Thanks in advance:

const backgroundImage = new Image();
    backgroundImage.src = '../Assets/pattern.png';

    return (backgroundImage.onload = () => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = width;
        canvas.height = height;

        if (!ctx) {
            return '';
        }

        ctx.drawImage(backgroundImage, 0, 0, width, height);

        ctx.fillRect(0, 0, width, height);
        ctx.font = 'bold italic 48px Montserrat';
        ctx.fillStyle = 'white';

        return canvas.toDataURL('image/png');
    });

I've tried different import styles, I've tried using other image sources (unsplash) but no luck


问:
Set an @EnvrionmentVariable from within an ObservableObject helper class
I am using CoreBluetooth in SwiftUI and want to set the CBPeripheral use it throughout the app. Using a wrapper class as an EnvironmentObject seems like the right way to go, however I am not sure how to set it from within the ViewModel.

```<code>class BluetoothViewModel: NSObject, ObservableObject {
    private var centralManager: CBCentralManager?
    @Published var peripherals: [CBPeripheral] = []

    override init() {
        super.init()
        self.centralManager = CBCentralManager(delegate: self, queue: .main)
        self.centralManager?.delegate = self
    }

    func connectToDevice(btPeripheral: CBPeripheral) -> Void {
        print("trying to connect to \(btPeripheral.name ?? "unknown")")
        centralManager?.connect(btPeripheral, options: nil)
    }

    func disconnectDevice(btPeripheral: CBPeripheral) -> Void {
        print("trying to disconnect to \(btPeripheral.name ?? "unknown")")
        centralManager?.cancelPeripheralConnection(btPeripheral)
        // WOULD LIKE TO SET THE @EnvrionmentObject TO nil HERE
    }
}
</code>```

...and after the connection:

```<code>extension BluetoothViewModel: CBCentralManagerDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            print("powered on")
            self.centralManager?.scanForPeripherals(withServices: nil)
        } else {
            //need to put an alert here to check bluetooth
            print("powered off")
        }
    }

    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {

        if !peripherals.contains(peripheral) {
            self.peripherals.append(peripheral)
        }
    }

    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {

        print("connected to \(peripheral.name ?? "unknown")")
        connectedPeripheral.peripheral = peripheral
        // WOULD LIKE TO SET THE @EnvrionmentObject here
    }

}
</code>```

This way in the view I show the Bluetooth device

```<code>    @EnvironmentObject var connectedPeripheral: ConnectedPeripheral
    @ObservedObject private var bluetoothViewModel = BluetoothViewModel()

    var body: some View {

        if (connectedPeripheral.peripheral == nil) {
            BluetoothDevicesView(). //this is where I list the devices and allow for selection
        } else {
            Text("We have one")
            Button("Disconnect") {
                print("pressed")
                // DISCONNECT DEVICE HERE
                bluetoothViewModel(connectedPeripheral.peripheral)
            }
            .buttonStyle(.borderedProminent)
        }
    }
</code>```

The wrapper class would be basic

import SwiftUI
import CoreBluetooth

```<code>@MainActor class ConnectedPeripheral: ObservableObject {

    @Published var peripheral: CBPeripheral? = nil

}
</code>```

I didn't think having the ViewModel as an EnvironmentVariable would be the right way to go and I need to use the CBPerpheral in other views as well. I also would probably just turn the ViewModel into some sort of helper class.

I was also thinking of potentially setting the @EnvironmentVariable by having a @Published object in the BluetoothViewModel, but would not know how to watch for it to change. I'm open to suggestions.

Body:
I am using CoreBluetooth in SwiftUI and want to set the CBPeripheral use it throughout the app. Using a wrapper class as an EnvironmentObject seems like the right way to go, however I am not sure how to set it from within the ViewModel.

class BluetoothViewModel: NSObject, ObservableObject {
    private var centralManager: CBCentralManager?
    @Published var peripherals: [CBPeripheral] = []

    override init() {
        super.init()
        self.centralManager = CBCentralManager(delegate: self, queue: .main)
        self.centralManager?.delegate = self
    }

    func connectToDevice(btPeripheral: CBPeripheral) -> Void {
        print("trying to connect to \(btPeripheral.name ?? "unknown")")
        centralManager?.connect(btPeripheral, options: nil)
    }

    func disconnectDevice(btPeripheral: CBPeripheral) -> Void {
        print("trying to disconnect to \(btPeripheral.name ?? "unknown")")
        centralManager?.cancelPeripheralConnection(btPeripheral)
        // WOULD LIKE TO SET THE @EnvrionmentObject TO nil HERE
    }
}

...and after the connection:

extension BluetoothViewModel: CBCentralManagerDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            print("powered on")
            self.centralManager?.scanForPeripherals(withServices: nil)
        } else {
            //need to put an alert here to check bluetooth
            print("powered off")
        }
    }

    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {

        if !peripherals.contains(peripheral) {
            self.peripherals.append(peripheral)
        }
    }

    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {

        print("connected to \(peripheral.name ?? "unknown")")
        connectedPeripheral.peripheral = peripheral
        // WOULD LIKE TO SET THE @EnvrionmentObject here
    }

}

This way in the view I show the Bluetooth device

    @EnvironmentObject var connectedPeripheral: ConnectedPeripheral
    @ObservedObject private var bluetoothViewModel = BluetoothViewModel()

    var body: some View {

        if (connectedPeripheral.peripheral == nil) {
            BluetoothDevicesView(). //this is where I list the devices and allow for selection
        } else {
            Text("We have one")
            Button("Disconnect") {
                print("pressed")
                // DISCONNECT DEVICE HERE
                bluetoothViewModel(connectedPeripheral.peripheral)
            }
            .buttonStyle(.borderedProminent)
        }
    }

The wrapper class would be basic

import SwiftUI
import CoreBluetooth

@MainActor class ConnectedPeripheral: ObservableObject {

    @Published var peripheral: CBPeripheral? = nil

}

I didn't think having the ViewModel as an EnvironmentVariable would be the right way to go and I need to use the CBPerpheral in other views as well. I also would probably just turn the ViewModel into some sort of helper class.

I was also thinking of potentially setting the @EnvironmentVariable by having a @Published object in the BluetoothViewModel, but would not know how to watch for it to change. I'm open to suggestions.


问:
Ubuntu: Execute shell script with fail2ban when user fails to log in ssh
In my ubuntu server I use fail2ban to block repeated failed ssh logins, when fail2ban detects this I want to execute a shell script, is this possible to do?

My ssh jail:

```<code>[ssh]
findtime = 10m
maxretry = 3
</code>```

My shell script is in this location:

```<code>/home/MyUser/scripts/send-mail
</code>```

Also, how can I get the banned IP? I want to send that information too if possible

Body:
In my ubuntu server I use fail2ban to block repeated failed ssh logins, when fail2ban detects this I want to execute a shell script, is this possible to do?

My ssh jail:

[ssh]
findtime = 10m
maxretry = 3

My shell script is in this location:

/home/MyUser/scripts/send-mail

Also, how can I get the banned IP? I want to send that information too if possible


问:
Ansible warning can't match supplied host pattern
I'm using ansible to create 2 aws ec2 instances and update them.

The playbook succeeds to create the instances and check if ssh is available but
can't find the hosts using my tag.

Ansible playbook:

---
- name: "Create 2 webservers"
  hosts: localhost
  tasks:
    - name: "Start instances with a public IP address"
      ec2_instance:
        name: "Ansible host"
        key_name: "vockey"
        instance_type: t2.micro
        security_group: sg-017a67d545bce2047
        image_id: "ami-0ed9277fb7eb570c9"
        region: "us-east-1"
        state: running
        exact_count: 2
        tags:
          Role: Webservers
      register: result
    - name: "Wait for SSH to come up"
      wait_for:
        host: "{{ item.public_ip_address }}"
        port: 22
        sleep: 10
      loop: "{{ result.instances }}"
- name: "Update the webServers"
  hosts: tag_Role_Webservers
  become: yes
  tasks:
    - name: "Upgrade all packages"
      yum:
        name: '*'
        state: latest
```
<p>The warning:</p>
```
[WARNING]: Could not match supplied host pattern, ignoring: tag_Role_Webservers

PLAY [Update the webServers] ******************************************************************************************************************************************************************
skipping: no hosts matched

PLAY RECAP ************************************************************************************************************************************************************************************
localhost                  : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
```

Body:
I'm using ansible to create 2 aws ec2 instances and update them.

The playbook succeeds to create the instances and check if ssh is available but
can't find the hosts using my tag.

Ansible playbook:

---
- name: "Create 2 webservers"
  hosts: localhost
  tasks:
    - name: "Start instances with a public IP address"
      ec2_instance:
        name: "Ansible host"
        key_name: "vockey"
        instance_type: t2.micro
        security_group: sg-017a67d545bce2047
        image_id: "ami-0ed9277fb7eb570c9"
        region: "us-east-1"
        state: running
        exact_count: 2
        tags:
          Role: Webservers
      register: result
    - name: "Wait for SSH to come up"
      wait_for:
        host: "{{ item.public_ip_address }}"
        port: 22
        sleep: 10
      loop: "{{ result.instances }}"
- name: "Update the webServers"
  hosts: tag_Role_Webservers
  become: yes
  tasks:
    - name: "Upgrade all packages"
      yum:
        name: '*'
        state: latest

The warning:

[WARNING]: Could not match supplied host pattern, ignoring: tag_Role_Webservers

PLAY [Update the webServers] ******************************************************************************************************************************************************************
skipping: no hosts matched

PLAY RECAP ************************************************************************************************************************************************************************************
localhost                  : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0


问:
How can I make the pattern execute one after the other rather than all at once?
I am making a sort of game where you repeat the pattern that's randomly generated. everything works and I made it show the last button of the pattern to the user but if I want to show the full pattern I cant seem to do it.

I have tried delays but it makes a delay and plays the button pattern all at once. then I tried to make it an increasing delay but it still waits, and then plays all at once.

I made the delays with setTimeout but not sure how to make the array of pattern play out one after another rather than all at once.

I was able to have a delay between buttons by using an array of delays and selecting the delay in the same position as the button but once there's 2 of the same button in the pattern it plays it only once. code here doesn't have any delays.

let pattern = [];
const buttons = ["b1", "b2", "b3", "b4", "b5", "b6"]

function nextSeq () {rndNum = Math.floor(Math.random()*6);
let chosenButton = buttons[rndNum];
pattern.push(chosenButton);
for (i=0; i<pattern.length; i++) {
switch (pattern[i]) {
case "b1": $("div.b1").css("background-color", "red"); rtrn();
break;
case "b2": $("div.b2").css("background-color", "red"); rtrn();
break;
case "b3": $("div.b3").css("background-color", "red"); rtrn();
break;
case "b4": $("div.b4").css("background-color", "red"); rtrn();
break;
case "b5": $("div.b5").css("background-color", "red"); rtrn();
break;
case "b6": $("div.b6").css("background-color", "red"); rtrn();
break;
default:
}

}
}
function rtrn () {setTimeout(() => {
$("div.btn").css("background-color", "white")
}, 500); }
    ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.btn {width: 100px; height: 100px; border: solid black; border-
radius: 5%; border-width: 5px;
margin: 10px; display: inline-block;}</code>```

 <button onClick="nextSeq()">run</button>

```

Body:
I am making a sort of game where you repeat the pattern that's randomly generated. everything works and I made it show the last button of the pattern to the user but if I want to show the full pattern I cant seem to do it.

I have tried delays but it makes a delay and plays the button pattern all at once. then I tried to make it an increasing delay but it still waits, and then plays all at once.

I made the delays with setTimeout but not sure how to make the array of pattern play out one after another rather than all at once.

I was able to have a delay between buttons by using an array of delays and selecting the delay in the same position as the button but once there's 2 of the same button in the pattern it plays it only once. code here doesn't have any delays.

let pattern = [];
const buttons = ["b1", "b2", "b3", "b4", "b5", "b6"]

function nextSeq () {rndNum = Math.floor(Math.random()*6);
let chosenButton = buttons[rndNum];
pattern.push(chosenButton);
for (i=0; i<pattern.length; i++) {
switch (pattern[i]) {
case "b1": $("div.b1").css("background-color", "red"); rtrn();
break;
case "b2": $("div.b2").css("background-color", "red"); rtrn();
break;
case "b3": $("div.b3").css("background-color", "red"); rtrn();
break;
case "b4": $("div.b4").css("background-color", "red"); rtrn();
break;
case "b5": $("div.b5").css("background-color", "red"); rtrn();
break;
case "b6": $("div.b6").css("background-color", "red"); rtrn();
break;
default:
}

}
}
function rtrn () {setTimeout(() => {
$("div.btn").css("background-color", "white")
}, 500); }

.btn {width: 100px; height: 100px; border: solid black; border-
radius: 5%; border-width: 5px;
margin: 10px; display: inline-block;}

 <button onClick="nextSeq()">run</button>


问:
Add rate limit to public api returning customer status (exists, not-exist) against email
I have api which will return user status i.e exists or not exists in the shop against email. Now the challenge here is to rate limit any specific user/bot which is sending multiples request. One solution is to use advanced cloudfare rate limit but its only support IP counting in core subscription which we have already but IP counting is not a good solution at all since it can be send from any corporate LAN having multiple users or proxy servers.

While if I go for normal server side solution we have node modules like express-rate-limit but I still think the user is coming to our server and then we are blocking them.

Not sure if we have any best solution on cdn level. Also how can I track a user request uniquely with IP address which attributes I can use.


问:
Idle connections AWS S3 on putObject
I need to copy files from the s3 bucket from one account to another. I am trying to do that via aws-java-sdk client and its functions getObject and putObject. There are a lot of files that should be uploaded. So during putObject run, I get this error:

```<code>Exception in thread "main" software.amazon.awssdk.services.s3.model.S3Exception: Your socket connection to the server was not read from or written to within the timeout period. Idle connections will be closed. (Service: S3, Status Code: 400)
</code>```

How can this issue be fixed?
Here's the code that produces this error:

```<code> val clientConfigurationBuilder = ClientOverrideConfiguration.builder()
   val clientConfiguration = clientConfigurationBuilder.build

   val builder = AWSS3Client
      .builder
      .credentialsProvider(createCredentialsProvider(accessKey, secretKey))
      .region(Region.of(region))
      .overrideConfiguration(clientConfiguration)
      .httpClientBuilder(ApacheHttpClient.builder())
    endpoint.map(URI.create).foreach(builder.endpointOverride)
    val awsS3Client = builder.build

    val getObjectRequest = GetObjectRequest
      .builder()
      .bucket(fromBucket)
      .key(fromKey)
      .build()
    val getObjectResponse = awsS3Client.getObject(getObjectRequest)

    val putObjectRequest = PutObjectRequest
      .builder()
      .bucket(toBucket)
      .key(toKey)
      .build()
    val reqBody = RequestBody.fromInputStream(getObjectResponse,
     getObjectResponse.response().contentLength())
    awsS3Client.putObject(putObjectRequest, reqBody)
</code>```

Title: Idle connections AWS S3 on putObject

Body:
I need to copy files from the s3 bucket from one account to another. I am trying to do that via aws-java-sdk client and its functions getObject and putObject. There are a lot of files that should be uploaded. So during putObject run, I get this error:

Exception in thread "main" software.amazon.awssdk.services.s3.model.S3Exception: Your socket connection to the server was not read from or written to within the timeout period. Idle connections will be closed. (Service: S3, Status Code: 400)

How can this issue be fixed?
Here's the code that produces this error:

 val clientConfigurationBuilder = ClientOverrideConfiguration.builder()
   val clientConfiguration = clientConfigurationBuilder.build

   val builder = AWSS3Client
      .builder
      .credentialsProvider(createCredentialsProvider(accessKey, secretKey))
      .region(Region.of(region))
      .overrideConfiguration(clientConfiguration)
      .httpClientBuilder(ApacheHttpClient.builder())
    endpoint.map(URI.create).foreach(builder.endpointOverride)
    val awsS3Client = builder.build

    val getObjectRequest = GetObjectRequest
      .builder()
      .bucket(fromBucket)
      .key(fromKey)
      .build()
    val getObjectResponse = awsS3Client.getObject(getObjectRequest)

    val putObjectRequest = PutObjectRequest
      .builder()
      .bucket(toBucket)
      .key(toKey)
      .build()
    val reqBody = RequestBody.fromInputStream(getObjectResponse,
     getObjectResponse.response().contentLength())
    awsS3Client.putObject(putObjectRequest, reqBody)


问:
Validating data from mysql query in express.js
I have a post api which i want to validate data before inserting it into data base .
I want to check if the customerCode from the body exists in database or not .
this is my code but it always returns " Cannot read properties of undefined (reading '0')"</p>
```<code>app.post('/CreateCustomer', (req, res) => {
    pool.getConnection((err, connection) => {
        if (err) throw err
        const params = req.body
        connection.query('SELECT CustomerCode FROM Customers WHERE CustomerCode = ?', params.CustomerCode, (err, rows) => {
            // connection.release() // return the connection to pool

            if (rows[0] == undefined) {
                connection.query('INSERT INTO Customers SET ?', params, (err, rows) => {
                    connection.release() // return the connection to pool
                    if (!err) {
                        res.send(`Customers with the record ID  has been added.`)
                    } else {
                        console.log(err)
                    }

                    console.log('The data from beer table are:11 \n', rows)

                })
            } else {
                res.send("Csutomer Code Already taken!")
            }
        })
    })
})
</code>```

Body:
I have a post api which i want to validate data before inserting it into data base .
I want to check if the customerCode from the body exists in database or not .
this is my code but it always returns " Cannot read properties of undefined (reading '0')"

app.post('/CreateCustomer', (req, res) => {
    pool.getConnection((err, connection) => {
        if (err) throw err
        const params = req.body
        connection.query('SELECT CustomerCode FROM Customers WHERE CustomerCode = ?', params.CustomerCode, (err, rows) => {
            // connection.release() // return the connection to pool

            if (rows[0] == undefined) {
                connection.query('INSERT INTO Customers SET ?', params, (err, rows) => {
                    connection.release() // return the connection to pool
                    if (!err) {
                        res.send(`Customers with the record ID  has been added.`)
                    } else {
                        console.log(err)
                    }

                    console.log('The data from beer table are:11 \n', rows)

                })
            } else {
                res.send("Csutomer Code Already taken!")
            }
        })
    })
})


问:
Trying to use PR_SET_MM_EXE_FILE with the linux prctl syscall
In order to use PR_SET_MM_EXE_FILE the man page it says that all executable memory areas need to be unmapped. How would one do this without unmapping the area in which the program itself is running and segfaulting?

I think I might be misunderstanding the man page. I tried reading through /proc/self/maps and munmapping all executable regions, but this unsurprisingly segfaulted. Is the man page referring to something else, or am I supposed to be using some other magic to get this to work?


问:
PyQt5 Python Scroll area can't scroll it's content
I can't make scroll area scrolling.
Added into it QLabel and grid with 100 lines.
You can see code and screenshot bellow.
Does someone know how to add grid into scrolling area?

```<code>import sys
from PyQt5 import QtWidgets
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(100, 100, 960, 820)
        self.setMinimumWidth(960)
        self.setMinimumHeight(820)
        self.user_interface()

    def user_interface(self):
        self.setFont(QFont('Times', 11))
        # 100 lines grid
        grid = QGridLayout()
        for i in range(0, 100):
            for j in range(0, 1):
                grid.addWidget(QLabel("Hello There"), i, j)
                grid.addWidget(QLabel("General Kenobi"), i, j + 1)
        # scroll layout with QLabel and 100 lines grid
        scroll_layout = QVBoxLayout()
        scroll_layout.addWidget(QLabel("Scroll me down baby"))
        scroll_layout.addLayout(grid)
        scroll_layout.addStretch()
        # Creation of scroll area and set scroll layout as its layout
        scroll_area = QScrollArea()
        scroll_area.setLayout(scroll_layout)
        scroll_area.setWidgetResizable(False)
        # main layout
        main_layout = QtWidgets.QVBoxLayout()
        main_layout.addWidget(QLabel("I stay on my place"))
        main_layout.addWidget(scroll_area)
        # application GUI setup
        central_widget = QtWidgets.QWidget(self)
        self.setCentralWidget(central_widget)
        central_widget.setLayout(main_layout)
        self.show()

def main():
    app = QApplication(sys.argv)
    window = Window()
    sys.exit(app.exec())

if __name__ == '__main__':
    main()

</code>```

Here is screenshot:

Thanks guys!

Body:
I can't make scroll area scrolling.
Added into it QLabel and grid with 100 lines.
You can see code and screenshot bellow.
Does someone know how to add grid into scrolling area?

import sys
from PyQt5 import QtWidgets
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(100, 100, 960, 820)
        self.setMinimumWidth(960)
        self.setMinimumHeight(820)
        self.user_interface()

    def user_interface(self):
        self.setFont(QFont('Times', 11))
        # 100 lines grid
        grid = QGridLayout()
        for i in range(0, 100):
            for j in range(0, 1):
                grid.addWidget(QLabel("Hello There"), i, j)
                grid.addWidget(QLabel("General Kenobi"), i, j + 1)
        # scroll layout with QLabel and 100 lines grid
        scroll_layout = QVBoxLayout()
        scroll_layout.addWidget(QLabel("Scroll me down baby"))
        scroll_layout.addLayout(grid)
        scroll_layout.addStretch()
        # Creation of scroll area and set scroll layout as its layout
        scroll_area = QScrollArea()
        scroll_area.setLayout(scroll_layout)
        scroll_area.setWidgetResizable(False)
        # main layout
        main_layout = QtWidgets.QVBoxLayout()
        main_layout.addWidget(QLabel("I stay on my place"))
        main_layout.addWidget(scroll_area)
        # application GUI setup
        central_widget = QtWidgets.QWidget(self)
        self.setCentralWidget(central_widget)
        central_widget.setLayout(main_layout)
        self.show()

def main():
    app = QApplication(sys.argv)
    window = Window()
    sys.exit(app.exec())

if __name__ == '__main__':
    main()

Here is screenshot:

Thanks guys!