问:
CORS error with UnityWebRequest from ASP.NET Web API 6.0 with CORS enabled
I'm working on a WebGL game with Unity in which I am attempting to call a custom built ASP.NET Web API that's built specifically to work with the game. I've added the code I thought was necessary to get CORS working for making the API requests from the browser, but I keep getting the same error: "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

I've tried several different variations of how to implement CORS with the API in the program.cs script. I tried:

```<code>builder.Services.AddCors(p => p.AddPolicy("corspolicy", build =>
{
    build.WithOrigins("*").AllowAnyMethod().AllowAnyHeader();
}));
</code>```

And

```<code>builder.Services.AddCors(o =>
{
    o.AddPolicy("corspolicy", build =>
        build.WithOrigins("*")
        .AllowAnyMethod()
        .AllowAnyHeader()
});
</code>```

Of course, I also included:

```<code>app.UseHttpsRedirection();

app.UseCors();

app.UseAuthorization();

app.MapControllers();

app.Run();
</code>```

According to the documentation and the tutorials I followed, it looks like I added the correct code in the correct places, but when I publish the API to Azure and try to call it from the WebGL game, I always get that same error that I listed above.

I also tried using the AddDefaultPolicy() with just UseCors(), but that had the same result.

I've tried plugging the URL into Postman and HTTPie along with the header: "Origin": "http://127.0.0.1:5500", to mimic the game running on my local machine, and when I include that, it does return an "Acces-Control-Allow-Origin" header in the response set to either "*" or "http://127.0.0.1:5500" (I've tried both), depending on what I used in WithOrigins().

In Unity I'm making the API call like this:

```<code>    public void MakeAPIRequest()
    {
        _webRequest = CreateRequest($"https://apiurl...");
        _APICallType = APICallType.login;
        _webRequestAsyncOperation = _webRequest.SendWebRequest();
        _webRequestAsyncOperation.completed += GetRequestAsyncOperation_completed;
    }

    private UnityWebRequest CreateRequest(string path, RequestType type = RequestType.GET, object data = null)
    {
        var request = new UnityWebRequest(path, type.ToString());

        if (data != null)
        {
            var bodyRaw = Encoding.UTF8.GetBytes(JsonUtility.ToJson(data));
            request.uploadHandler = new UploadHandlerRaw(bodyRaw);
        }

        request.downloadHandler = new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");

        return request;
    }
</code>```

I'm currently at a loss for how to get this working, so if anyone here has any advice about what to try or look into, I would really appreciate it.

Body:
I'm working on a WebGL game with Unity in which I am attempting to call a custom built ASP.NET Web API that's built specifically to work with the game. I've added the code I thought was necessary to get CORS working for making the API requests from the browser, but I keep getting the same error: "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

I've tried several different variations of how to implement CORS with the API in the program.cs script. I tried:

builder.Services.AddCors(p => p.AddPolicy("corspolicy", build =>
{
    build.WithOrigins("*").AllowAnyMethod().AllowAnyHeader();
}));

And

builder.Services.AddCors(o =>
{
    o.AddPolicy("corspolicy", build =>
        build.WithOrigins("*")
        .AllowAnyMethod()
        .AllowAnyHeader()
});

Of course, I also included:

app.UseHttpsRedirection();

app.UseCors();

app.UseAuthorization();

app.MapControllers();

app.Run();

According to the documentation and the tutorials I followed, it looks like I added the correct code in the correct places, but when I publish the API to Azure and try to call it from the WebGL game, I always get that same error that I listed above.

I also tried using the AddDefaultPolicy() with just UseCors(), but that had the same result.

I've tried plugging the URL into Postman and HTTPie along with the header: "Origin": "http://127.0.0.1:5500", to mimic the game running on my local machine, and when I include that, it does return an "Acces-Control-Allow-Origin" header in the response set to either "*" or "http://127.0.0.1:5500" (I've tried both), depending on what I used in WithOrigins().

In Unity I'm making the API call like this:

    public void MakeAPIRequest()
    {
        _webRequest = CreateRequest($"https://apiurl...");
        _APICallType = APICallType.login;
        _webRequestAsyncOperation = _webRequest.SendWebRequest();
        _webRequestAsyncOperation.completed += GetRequestAsyncOperation_completed;
    }

    private UnityWebRequest CreateRequest(string path, RequestType type = RequestType.GET, object data = null)
    {
        var request = new UnityWebRequest(path, type.ToString());

        if (data != null)
        {
            var bodyRaw = Encoding.UTF8.GetBytes(JsonUtility.ToJson(data));
            request.uploadHandler = new UploadHandlerRaw(bodyRaw);
        }

        request.downloadHandler = new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");

        return request;
    }

I'm currently at a loss for how to get this working, so if anyone here has any advice about what to try or look into, I would really appreciate it.


来源: stackexchange

问:
Initialize filters of SelectizeGroupUI with the first value
Does anyone know if it is possible to initialize the filters defined in the selectizeGroupUI with the first value in each of the filters?  Something like the "selected" option in the selectInput. Let's say I have the following code:

```<code>if (interactive()) {

  library(shiny)
  library(shinyWidgets)

  data("mpg", package = "ggplot2")

  ui <- fluidPage(
    fluidRow(
      column(
        width = 10, offset = 1,
        tags$h3("Filter data with selectize group"),
        panel(
          pickerInput(
            inputId = "car_select",
            choices = unique(mpg$manufacturer),
            options = list(
              `live-search` = TRUE,
              title = "None selected"
            )
          ),
          selectizeGroupUI(
            id = "my-filters",
            params = list(
              manufacturer = list(inputId = "manufacturer", title = "Manufacturer:"),
              model = list(inputId = "model", title = "Model:"),
              trans = list(inputId = "trans", title = "Trans:"),
              class = list(inputId = "class", title = "Class:")
            )
          ),
          status = "primary"
        ),
        DT::dataTableOutput(outputId = "table")
      )
    )
  )

  server <- function(input, output, session) {

    mpg_filter <- reactive({
      subset(mpg, manufacturer %in% input$car_select)
    })

    res_mod <- callModule(
      module = selectizeGroupServer,
      id = "my-filters",
      data = mpg_filter,
      vars = c("manufacturer", "model", "trans", "class")
    )

    output$table <- DT::renderDataTable({
      req(res_mod())
      res_mod()
    })
  }

  shinyApp(ui, server)
}

</code>```

If I select "audi" in the pickerInput, is it possible that instantly the filters of "Manufacturer", "Model", "Trans" and "Class" take the value of the first option they have?

I tried to assign a value to the filter with input[["my-filters-model"]] but it shows an error that  Can't modify read-only reactive value

ContentLicense: CC BY-SA 4.0

Body:
Does anyone know if it is possible to initialize the filters defined in the selectizeGroupUI with the first value in each of the filters?  Something like the "selected" option in the selectInput. Let's say I have the following code:

if (interactive()) {

  library(shiny)
  library(shinyWidgets)

  data("mpg", package = "ggplot2")

  ui <- fluidPage(
    fluidRow(
      column(
        width = 10, offset = 1,
        tags$h3("Filter data with selectize group"),
        panel(
          pickerInput(
            inputId = "car_select",
            choices = unique(mpg$manufacturer),
            options = list(
              `live-search` = TRUE,
              title = "None selected"
            )
          ),
          selectizeGroupUI(
            id = "my-filters",
            params = list(
              manufacturer = list(inputId = "manufacturer", title = "Manufacturer:"),
              model = list(inputId = "model", title = "Model:"),
              trans = list(inputId = "trans", title = "Trans:"),
              class = list(inputId = "class", title = "Class:")
            )
          ),
          status = "primary"
        ),
        DT::dataTableOutput(outputId = "table")
      )
    )
  )

  server <- function(input, output, session) {

    mpg_filter <- reactive({
      subset(mpg, manufacturer %in% input$car_select)
    })

    res_mod <- callModule(
      module = selectizeGroupServer,
      id = "my-filters",
      data = mpg_filter,
      vars = c("manufacturer", "model", "trans", "class")
    )

    output$table <- DT::renderDataTable({
      req(res_mod())
      res_mod()
    })
  }

  shinyApp(ui, server)
}

If I select "audi" in the pickerInput, is it possible that instantly the filters of "Manufacturer", "Model", "Trans" and "Class" take the value of the first option they have?

I tried to assign a value to the filter with input[["my-filters-model"]] but it shows an error that  Can't modify read-only reactive value


问:
How to submit input type = range in flask
While trying to submit input type = range i'm getting "Bad request error".

HTML:

```<code>{% extends "base.html" %} {% block content %} <head>
  <link rel="stylesheet" href="css/style.css" />
</head>
<div class="search-bar">
  <div class="rt-container">
    <form method="post" action="#">
      <div class="col-rt-12">
        <div class="Scriptcontent">
          <!-- Range Slider HTML -->
          <div slider id="slider-distance">
            <div>
              <div inverse-left style="width: 70%"></div>
              <div inverse-right style="width: 70%"></div>
              <div range style="left: 30%; right: 40%"></div>
              <span thumb style="left: 30%"></span>
              <span thumb style="left: 60%"></span>
              <div sign style="left: 30%">
                <span id="value">0</span>
              </div>
              <div sign style="left: 60%">
                <span id="value">100</span>
              </div>
            </div>
            <input name="max" type="range" tabindex="0" value="30" max="100" min="0" step="1" oninput="
                  this.value=Math.min(this.value,this.parentNode.childNodes[5].value-1);
                  var value=(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.value)-(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.min);
                  var children = this.parentNode.childNodes[1].childNodes;
                  children[1].style.width=value+'%';
                  children[5].style.left=value+'%';
                  children[7].style.left=value+'%';children[11].style.left=value+'%';
                  children[11].childNodes[1].innerHTML=this.value;" />
            <input name="min" type="range" tabindex="0" value="60" max="100" min="0" step="1" oninput="
                  this.value=Math.max(this.value,this.parentNode.childNodes[3].value-(-1));
                  var value=(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.value)-(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.min);
                  var children = this.parentNode.childNodes[1].childNodes;
                  children[3].style.width=(100-value)+'%';
                  children[5].style.right=(100-value)+'%';
                  children[9].style.left=value+'%';children[13].style.left=value+'%';
                  children[13].childNodes[1].innerHTML=this.value;" />
            <input id="search" type="submit" value="SEARCH" href="#"></input>
          </div>
    </form>
  </div>
</div>
</div>
<form action="/lobbies" method="POST">
  <input type="checkbox" name="IsVisible" value="0" default="0">Private?</input>
  <input type="text" name="LobbyValue" placeholder="Value" href="#" required></input>
  <input type="submit" value="CREATE" href="#"></input>
</form>
</div>
<div class="container"> {% for lobby in data%} <div class="lobby-item">
    <div class="lobby-coins">
      <img src="static/StashedCoins.png" alt="coin" width="32px" height="32px" /> {% print lobby['GameValue']%}
    </div>
    <div class="lobby-photo">
      <a href="/Player/{{lobby['PlayerOneID']}}">
        <img src=https://robohash.org/{{lobby['CreatorName']}} alt="coin" width="110px" height="110px" />
      </a>
    </div>
    <div class="lobby-join">
      <a href=/lobby/{{lobby['LobbyID']}} style="background-color:rgb{{color}}"">Join</a>
        </div>
    </div>
{%endfor%}

</div>
 {% endblock %}
</code>```

Flask:

```<code>@app.route("/lobbies", methods=["GET", "POST"])
def lobbies():
    if "username" in session:
        coins = requests.get(API_URL + "/GetUserBalance/" + str(session["id"])).json()[
            "balance"
        ]
        ProfilePicture = "https://robohash.org/" + str(session["username"])
        color = str(session["color"])
        PlayerID = session["PlayerID"]
        if request.method == "POST":
            LobbyValue = request.form['LobbyValue']
            if "IsVisible" in request.form:
                response = requests.post(API_URL + "/CreateNewLobby", params={"ApiUser": API_USER,"PlayerID": PlayerID, "IsVisible": 0, "LobbyValue": LobbyValue}).json()
            else:
                response = requests.post(API_URL + "/CreateNewLobby", params={"ApiUser": API_USER,"PlayerID": PlayerID, "LobbyValue": LobbyValue}).json()
            LobbyID = response['LobbyID']
            return redirect(url_for('lobby',LobbyID=LobbyID))

        data = requests.get(API_URL + "/GetLobbies", params={"PlayerID": PlayerID})
        return render_template(
            "lobbies.html",
            coins=coins,
            ProfilePicture=ProfilePicture,
            color=color,
            data=data.json(),
        )
    else:
        return redirect(url_for("login"))
</code>```

I dont understand what im doing wrong here.
I want to give user a slider with two handlers like this:

So they can filter the lobbies within the price range set in slider. I need in this example number 0 and 69 to be send to my flask app so i can then display lobbies within the price range.

Body:
While trying to submit input type = range i'm getting "Bad request error".

HTML:

{% extends "base.html" %} {% block content %}
  <link rel="stylesheet" href="css/style.css" />

    <form method="post" action="#">

                0

                100

            <input name="max" type="range" tabindex="0" value="30" max="100" min="0" step="1" oninput="
                  this.value=Math.min(this.value,this.parentNode.childNodes[5].value-1);
                  var value=(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.value)-(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.min);
                  var children = this.parentNode.childNodes[1].childNodes;
                  children[1].style.width=value+'%';
                  children[5].style.left=value+'%';
                  children[7].style.left=value+'%';children[11].style.left=value+'%';
                  children[11].childNodes[1].innerHTML=this.value;" />
            <input name="min" type="range" tabindex="0" value="60" max="100" min="0" step="1" oninput="
                  this.value=Math.max(this.value,this.parentNode.childNodes[3].value-(-1));
                  var value=(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.value)-(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.min);
                  var children = this.parentNode.childNodes[1].childNodes;
                  children[3].style.width=(100-value)+'%';
                  children[5].style.right=(100-value)+'%';
                  children[9].style.left=value+'%';children[13].style.left=value+'%';
                  children[13].childNodes[1].innerHTML=this.value;" />
            <input id="search" type="submit" value="SEARCH" href="#"></input>

    </form>

<form action="/lobbies" method="POST">
  <input type="checkbox" name="IsVisible" value="0" default="0">Private?</input>
  <input type="text" name="LobbyValue" placeholder="Value" href="#" required></input>
  <input type="submit" value="CREATE" href="#"></input>
</form>

 {% for lobby in data%}

       {% print lobby['GameValue']%}

      Join

{%endfor%}

 {% endblock %}

Flask:

@app.route("/lobbies", methods=["GET", "POST"])
def lobbies():
    if "username" in session:
        coins = requests.get(API_URL + "/GetUserBalance/" + str(session["id"])).json()[
            "balance"
        ]
        ProfilePicture = "https://robohash.org/" + str(session["username"])
        color = str(session["color"])
        PlayerID = session["PlayerID"]
        if request.method == "POST":
            LobbyValue = request.form['LobbyValue']
            if "IsVisible" in request.form:
                response = requests.post(API_URL + "/CreateNewLobby", params={"ApiUser": API_USER,"PlayerID": PlayerID, "IsVisible": 0, "LobbyValue": LobbyValue}).json()
            else:
                response = requests.post(API_URL + "/CreateNewLobby", params={"ApiUser": API_USER,"PlayerID": PlayerID, "LobbyValue": LobbyValue}).json()
            LobbyID = response['LobbyID']
            return redirect(url_for('lobby',LobbyID=LobbyID))

        data = requests.get(API_URL + "/GetLobbies", params={"PlayerID": PlayerID})
        return render_template(
            "lobbies.html",
            coins=coins,
            ProfilePicture=ProfilePicture,
            color=color,
            data=data.json(),
        )
    else:
        return redirect(url_for("login"))

I dont understand what im doing wrong here.
I want to give user a slider with two handlers like this:

So they can filter the lobbies within the price range set in slider. I need in this example number 0 and 69 to be send to my flask app so i can then display lobbies within the price range.


问:
Do i need mutex, when i just access map of net.Conn in different goroutines and write to them
Do i need mutex in this case ?

I have a simple type with map of net.Conn

type ConnectionsHandler struct {
    mutex                 sync.Mutex
    connections           map[string]net.Conn
    authorizedConnections []string
}
```
<p>And when i need to add or remove connection from different goroutines, i think i need to use mutex for thread safety</p>
<pre class="lang-go prettyprint-override"><code>func (c *ConnectionsHandler) addConnection(conn net.Conn, id string) {
    c.mutex.Lock()
    c.connections[id] = conn
    c.mutex.Unlock()
}

func (c *ConnectionsHandler) removeConnection(id string) {
    c.mutex.Lock()

    if conn, ok := c.connections[id]; ok {
        conn.Close()
        delete(c.connections, id)
    }

    c.mutex.Unlock()
}
</code>```

But i also need for iterate over all connections and write to them, or write to single one

func (c *ConnectionsHandler) sendMessage(msg GameMessage) {
    // write msg to specific single one
}

func (c *ConnectionsHandler) sendMessageToAll(msg GameMessage) {
    // iterate over all connections and write msg to them
}
```

And the question is, do i need mutex lock in sendMessageToAll() when i call Write() on each net.Conn stored in map ??

Body:
Do i need mutex in this case ?

I have a simple type with map of net.Conn

type ConnectionsHandler struct {
    mutex                 sync.Mutex
    connections           map[string]net.Conn
    authorizedConnections []string
}

And when i need to add or remove connection from different goroutines, i think i need to use mutex for thread safety

func (c *ConnectionsHandler) addConnection(conn net.Conn, id string) {
    c.mutex.Lock()
    c.connections[id] = conn
    c.mutex.Unlock()
}

func (c *ConnectionsHandler) removeConnection(id string) {
    c.mutex.Lock()

    if conn, ok := c.connections[id]; ok {
        conn.Close()
        delete(c.connections, id)
    }

    c.mutex.Unlock()
}

But i also need for iterate over all connections and write to them, or write to single one

func (c *ConnectionsHandler) sendMessage(msg GameMessage) {
    // write msg to specific single one
}

func (c *ConnectionsHandler) sendMessageToAll(msg GameMessage) {
    // iterate over all connections and write msg to them
}

And the question is, do i need mutex lock in sendMessageToAll() when i call Write() on each net.Conn stored in map ??


问:
How can I use oauth2 response to make requests to the api guarded by it?
I am trying to use Authorization Code scheme with oauth2.

How can I use the response from app backend to make new requests to the actual api (yahoo-fantasy) guarded by it? I have no idea how I can access the actual response on the code side, please note that this is a question about implementation, not the concept.

I have the following structure:

$ tree src

```<code>src
├── components
│   ├── app.rs
│   └── login.rs
├── components.rs
└── main.rs
</code>```

with the following files:

```<code>// ./src/components/app.rs

use yew::{function_component, html};

use crate::components::login::Login;

#[function_component(App)]
pub fn app() -> Html {
    html! {
        <>
            <Login/>
        </>
    }
}
</code>```

```<code>// ./src/components/login.rs
use yew::prelude::*;
use yew_oauth2::oauth2::*;
use yew_oauth2::prelude::*; // use `openid::*` when using OpenID connect

pub struct Login;

impl Component for Login {
    type Message = ();
    type Properties = ();

    fn create(ctx: &Context<Self>) -> Self {
        Self
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        let login = ctx.link().callback_once(|_: MouseEvent| {
            OAuth2Dispatcher::<Client>::new().start_login();
        });
        let logout = ctx.link().callback_once(|_: MouseEvent| {
            OAuth2Dispatcher::<Client>::new().logout();
        });

        let config = Config {
            client_id: "<my-yahoo-client-id>".to_string(),
            auth_url: "https://api.login.yahoo.com/oauth2/request_auth".into(),
            token_url: "<my-backend-end-point-for-oauth2>".to_string(),
        };

        html!(
          <OAuth2 config={config}>
            <Failure><FailureMessage/></Failure>
            <Authenticated>
              <button onclick={logout}>{ "Logout" }</button>
            </Authenticated>
            <NotAuthenticated>
              <button onclick={login.clone()}>{ "Login" }</button>
            </NotAuthenticated>
          </OAuth2>
        )
    }
}
</code>```

```<code>// ./src/components.rs
pub mod app;
pub mod login;
</code>```

```<code>// ./src/main.rs
mod components;

fn main() {
    yew::start_app::<components::app::App>();
}
</code>```

which I'm developing using:

trunk serve

When the login button is pushed, app backend responds with the following body:

```<code>{
  "access_token": "<access_token-value>",
  "expires_in": 3600,
  "refresh_token": "<refresh_token-value>",
  "token_type": "bearer"
}
</code>```

Further see the project dependencies:

```<code># ./Cargo.toml
[package]
edition = "2021"
name = "my_project"
version = "0.1.0"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
dotenv_codegen = "0.15.0"
gloo-net = "0.2.5"
log = "0.4.17"
reqwest = "0.11.13"
serde = "1.0.149"
wasm-bindgen-futures = "0.4.33"
wasm-logger = "0.2.0"
yew = "0.19.3"
yew-oauth2 = "0.4.0"
</code>```

Further note, I've read the all the answers on the question What is the OAuth 2.0 Bearer Token exactly?, and I could not make a progress and/or have any insight that it is related to my question directly.

Body:
I am trying to use Authorization Code scheme with oauth2.

How can I use the response from app backend to make new requests to the actual api (yahoo-fantasy) guarded by it? I have no idea how I can access the actual response on the code side, please note that this is a question about implementation, not the concept.

I have the following structure:

$ tree src

src
├── components
│   ├── app.rs
│   └── login.rs
├── components.rs
└── main.rs

with the following files:

// ./src/components/app.rs

use yew::{function_component, html};

use crate::components::login::Login;

#[function_component(App)]
pub fn app() -> Html {
    html! {
        <>
            <Login/>
        </>
    }
}

// ./src/components/login.rs
use yew::prelude::*;
use yew_oauth2::oauth2::*;
use yew_oauth2::prelude::*; // use `openid::*` when using OpenID connect

pub struct Login;

impl Component for Login {
    type Message = ();
    type Properties = ();

    fn create(ctx: &Context<Self>) -> Self {
        Self
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        let login = ctx.link().callback_once(|_: MouseEvent| {
            OAuth2Dispatcher::<Client>::new().start_login();
        });
        let logout = ctx.link().callback_once(|_: MouseEvent| {
            OAuth2Dispatcher::<Client>::new().logout();
        });

        let config = Config {
            client_id: "<my-yahoo-client-id>".to_string(),
            auth_url: "https://api.login.yahoo.com/oauth2/request_auth".into(),
            token_url: "<my-backend-end-point-for-oauth2>".to_string(),
        };

        html!(
          <OAuth2 config={config}>
            <Failure><FailureMessage/></Failure>
            <Authenticated>
              <button onclick={logout}>{ "Logout" }</button>
            </Authenticated>
            <NotAuthenticated>
              <button onclick={login.clone()}>{ "Login" }</button>
            </NotAuthenticated>
          </OAuth2>
        )
    }
}

// ./src/components.rs
pub mod app;
pub mod login;

// ./src/main.rs
mod components;

fn main() {
    yew::start_app::<components::app::App>();
}

which I'm developing using:

trunk serve

When the login button is pushed, app backend responds with the following body:

{
  "access_token": "<access_token-value>",
  "expires_in": 3600,
  "refresh_token": "<refresh_token-value>",
  "token_type": "bearer"
}

Further see the project dependencies:

# ./Cargo.toml
[package]
edition = "2021"
name = "my_project"
version = "0.1.0"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
dotenv_codegen = "0.15.0"
gloo-net = "0.2.5"
log = "0.4.17"
reqwest = "0.11.13"
serde = "1.0.149"
wasm-bindgen-futures = "0.4.33"
wasm-logger = "0.2.0"
yew = "0.19.3"
yew-oauth2 = "0.4.0"

Further note, I've read the all the answers on the question What is the OAuth 2.0 Bearer Token exactly?, and I could not make a progress and/or have any insight that it is related to my question directly.


问:
Why does FragmentTransaction on FragmentContainerView in RecyclerView listitem only affect first element of RecyclerView?
Inflating a layout XML file with a FragmentContainerView in the onCreateViewHolder() method of a RecyclerView adapter and trying to put different Fragments into the FragmentContainerViews of each list item only affects the FragmentContainerView in the first list item.

When creating a listitem_layout.xml with a FragmentContainerView inside a ConstraintLayout like this:

```<code><androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#D47F00">

  <androidx.fragment.app.FragmentContainerView
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

And then trying to inflate this layout in the onCreateViewHolder() method of a RecyclerView adapter like this:

```<code>@NonNull
@Override
public CustomHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View itemView = inflater.inflate(R.layout.listitem_layout, parent, false);
    return new CustomHolder(itemView, (AppCompatActivity) inflater.getContext());
}
</code>```

I then put different Fragments, depending on if the user has clicked a list item or not, into the list item in the CustomHolder:

```<code>class CustomHolder extends RecyclerView.ViewHolder {
    public static boolean skip = true;
    private AppCompatActivity appCompatActivity;
    private FragmentContainerView fragmentContainerView;
    private Fragment attributeDetailFragment;
    private Trainer trainer;
    private TextView trainerAge;

    CustomHolder(@NonNull View itemView, AppCompatActivity appCompatActivity) {
        super(itemView);
        this.trainerAge = itemView.findViewById(R.id.trainer_age);
        this.fragmentContainerView = itemView.findViewById(R.id.fragment_container);
        this.appCompatActivity = appCompatActivity;
    }

    void setTrainer(Trainer trainer) {
        this.trainer = trainer;
        this.trainerAge.setText(" " + trainer.getAge());
        this.trainerAge.setOnClickListener(this::onTrainerAgeClick);
        itemView.setTag(this);
    }

    private void onTrainerAgeClick(View view) {
        attributeDetailFragment = new AgeFragment();
        showFragment();
    }

    private void showFragment() {
        Bundle args = new Bundle();
        args.putParcelable("trainer", trainer);
        attributeDetailFragment.setArguments(args);
        FragmentManager fragmentManager = appCompatActivity.getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(fragmentContainerView.getId(), attributeDetailFragment);
        fragmentTransaction.commit();
    }
}
</code>```

However upon running the app, when clicking on different listitems, the correct content will be set into a fragment, but the Fragment will always land in the FragmentContainerView of the first listitem. This is what the previous version of this question meant by the id stays the same, the FragmentContainerView targeted stays the same but the TextView targeted changes depending on the ViewHolder object.

From the comments on this, I suspect it may be the fragmentContainerView.getId() in showFragment(), but I have no idea with what I should replace it, since replace() needs an int id.

Body:
Inflating a layout XML file with a FragmentContainerView in the onCreateViewHolder() method of a RecyclerView adapter and trying to put different Fragments into the FragmentContainerViews of each list item only affects the FragmentContainerView in the first list item.

When creating a listitem_layout.xml with a FragmentContainerView inside a ConstraintLayout like this:

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#D47F00">

  <androidx.fragment.app.FragmentContainerView
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

And then trying to inflate this layout in the onCreateViewHolder() method of a RecyclerView adapter like this:

@NonNull
@Override
public CustomHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View itemView = inflater.inflate(R.layout.listitem_layout, parent, false);
    return new CustomHolder(itemView, (AppCompatActivity) inflater.getContext());
}

I then put different Fragments, depending on if the user has clicked a list item or not, into the list item in the CustomHolder:

class CustomHolder extends RecyclerView.ViewHolder {
    public static boolean skip = true;
    private AppCompatActivity appCompatActivity;
    private FragmentContainerView fragmentContainerView;
    private Fragment attributeDetailFragment;
    private Trainer trainer;
    private TextView trainerAge;

    CustomHolder(@NonNull View itemView, AppCompatActivity appCompatActivity) {
        super(itemView);
        this.trainerAge = itemView.findViewById(R.id.trainer_age);
        this.fragmentContainerView = itemView.findViewById(R.id.fragment_container);
        this.appCompatActivity = appCompatActivity;
    }

    void setTrainer(Trainer trainer) {
        this.trainer = trainer;
        this.trainerAge.setText(" " + trainer.getAge());
        this.trainerAge.setOnClickListener(this::onTrainerAgeClick);
        itemView.setTag(this);
    }

    private void onTrainerAgeClick(View view) {
        attributeDetailFragment = new AgeFragment();
        showFragment();
    }

    private void showFragment() {
        Bundle args = new Bundle();
        args.putParcelable("trainer", trainer);
        attributeDetailFragment.setArguments(args);
        FragmentManager fragmentManager = appCompatActivity.getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(fragmentContainerView.getId(), attributeDetailFragment);
        fragmentTransaction.commit();
    }
}

However upon running the app, when clicking on different listitems, the correct content will be set into a fragment, but the Fragment will always land in the FragmentContainerView of the first listitem. This is what the previous version of this question meant by the id stays the same, the FragmentContainerView targeted stays the same but the TextView targeted changes depending on the ViewHolder object.

From the comments on this, I suspect it may be the fragmentContainerView.getId() in showFragment(), but I have no idea with what I should replace it, since replace() needs an int id.


问:
JetpackCompose, request focus on any of my child
I have a LazyList of items, each item has layers of nested children wrapped in other components. For each item, there could be 2 or 3 focusables nested. From the list level, how to I request focus on any focusable child of nth item?</p>
```<code>
val autoFocusIndex = n

LazyList{

   itemsIndex(data){ index, d->

      ListItem{...}

      if(index == n){
         // focus on any child focus area of nth item
      }

   }
}

@Composable
fun ListItem(...) { ListItemLayer1{...} }

@Composable
fun ListItemLayer1(...) { ListItemLayer2{...} }

@Composable
fun ListItemLayerX(...) {
    // 2 or 3 focusables,
    Box(Modifier.focusable()) {...}
    Box(Modifier.focusable()) {...}

    if(...) Box(Modifier.focusable()) {...}
}
</code>```

Body:
I have a LazyList of items, each item has layers of nested children wrapped in other components. For each item, there could be 2 or 3 focusables nested. From the list level, how to I request focus on any focusable child of nth item?

val autoFocusIndex = n

LazyList{

   itemsIndex(data){ index, d->

      ListItem{...}

      if(index == n){
         // focus on any child focus area of nth item
      }

   }
}

@Composable
fun ListItem(...) { ListItemLayer1{...} }

@Composable
fun ListItemLayer1(...) { ListItemLayer2{...} }

@Composable
fun ListItemLayerX(...) {
    // 2 or 3 focusables,
    Box(Modifier.focusable()) {...}
    Box(Modifier.focusable()) {...}

    if(...) Box(Modifier.focusable()) {...}
}


问:
I filter for a slice of a dataframe, how can I now set of one of the column values?
When I execute the following:

```<code>market_info_df.loc[(market_info_df['issue_status'] == '10') & (market_info_df['market_phase'] == '0') & (market_info_df['trading_state'] == '  ')].iloc[0]
</code>```

I get back a slice of a dataframe. Here is what the slice looks like:

```<code>activity                                          0
msg_original_type                                 0
sequence_no                                       0
system_event
timestamp                2021-12-13 15:17:28.593198
trading_status                                    1
market_state                                   None
</code>```

I simply want to set the market_state value of the dataframe  to OPENING_AUCTION.

I tried doing:

```<code>first_row = market_info_df.loc[(market_info_df['issue_status'] == '10') & (market_info_df['market_phase'] == '0') & (market_info_df['trading_state'] == '  ')].iloc[0]

first_row['market_state'] = 'OPENING_AUCTION'
</code>```

But when I now print(market_info_df), the market_state for the slice is not set! Basically my code is setting the value of market_state for first_row (i.e. the slice of the dataframe) but not the value of the dataframe itself.

How can I map it in market_info_df rather than in first_row?

Body:
When I execute the following:

market_info_df.loc[(market_info_df['issue_status'] == '10') & (market_info_df['market_phase'] == '0') & (market_info_df['trading_state'] == '  ')].iloc[0]

I get back a slice of a dataframe. Here is what the slice looks like:

activity                                          0
msg_original_type                                 0
sequence_no                                       0
system_event
timestamp                2021-12-13 15:17:28.593198
trading_status                                    1
market_state                                   None

I simply want to set the market_state value of the dataframe  to OPENING_AUCTION.

I tried doing:

first_row = market_info_df.loc[(market_info_df['issue_status'] == '10') & (market_info_df['market_phase'] == '0') & (market_info_df['trading_state'] == '  ')].iloc[0]

first_row['market_state'] = 'OPENING_AUCTION'

But when I now print(market_info_df), the market_state for the slice is not set! Basically my code is setting the value of market_state for first_row (i.e. the slice of the dataframe) but not the value of the dataframe itself.

How can I map it in market_info_df rather than in first_row?


问:
How can I install a kernel version with a specific name?
I'd like to manually compile multiple versions of the same Linux kernel which would differ only for few minor things (e.g. debug symbols) and install them on my host. I would need to have the modules installed in different paths so I could compare the different versions of the .ko files.

If possible in the end I would like to have one image called vmlinux-6.0.7-debug and one called vmlinux-6.0.7 and the modules to be installed in /lib/modules/debug and /lib/modules/nodebug

I tried to manually rename the bzImage and to export the INSTALL_DIR but I had no luck.

Anyone can show me the set of commands?

Thanks


问:
SQL Server Agent randomly stops working however says its running in Services though the agent is dead (Forced restart fixes it)
I've not seen this scenario in all my web searches.
We have several SQL Server Agent jobs that get kicked off by users through various applications.
Quite randomly, these executions will fail. When log in and manually kick the jobs off i'm immediately presented with 'SQL Agent not started' errors.
When I check the agent it says it's running. If I force a restart the problem is fixed.

The random nature of the issue causes testing issues.
The agent is already set up to 'restart if stopped unexpectedly' and 'restart with delay'.

A recent disaster recovery was performed and SQL Server Agent started successfully and declared itself 'running'. However once again it required a manual restart to actually work.

Is this a known issue or bug?

How can I mitigate against this when the agent says its running and all parameters are set correctly and meet the 'internet's' suggestions?


问:
I want to create a squares with 5 by 5 squares with a space but I am not sure how to?This is what I tried
```<code>y = topLeft.getY()
for i in range(5):
    x = topLeft.getX()
    for c in range(5):
        cellButton = CellButton(window,x,y,size,cellID=(i,c))
        self._buttons.append(cellButton)
        x= x + (size+padding)
    y = y + (size + padding)
</code>```

#padding being space between each squares

I was expecting a 25 cell which is 5 by 5 with a space between them

Body:
y = topLeft.getY()
for i in range(5):
    x = topLeft.getX()
    for c in range(5):
        cellButton = CellButton(window,x,y,size,cellID=(i,c))
        self._buttons.append(cellButton)
        x= x + (size+padding)
    y = y + (size + padding)

#padding being space between each squares

I was expecting a 25 cell which is 5 by 5 with a space between them


问:
How to capture the referralId of a URL using the chrome.webnavigation api?
The chrome history api has some limitations the following being that the referralID will be "0" if you "control + click" that url from the current page.

I'm building a browsing history visualization tool and the referralID labeling has "zero" is not helping.

Instead of using the chrome.history, can you use the chrome.webnavigation api to get the referralID to every website?

Image of the browsing history code from the console

Image of the code sample used

It seems that at this point the web navigation api is going to be how to solve this question, but I'm not sure how to capture the referralID using that method.  With the web navigation API it'll only be useful in capturing history moving forward, not retroactively.


问:
text datatype convert automatically to number in postgresql
I use Postgres as my database so in my app I use oauth2 the client role after user grant permission to my app so i retrieve the access token from auth server I'm trying to store it in database with column datatype text its inserted as a numbers.

I try varchar it same problem so i try different database MySQL it works fine


问:
Reducing time for minimum edit distance in python?
I am trying to create a list with the edit distances between each word in a set of documents, ranging from 10k-42k words. If my idea of edit distance is correct, I would end up with a distance for each word compared to every single other word. So if I had a corpus of 10k words each word would have 9,999 distances associated with it. Is there any way to optimize this or possibly a completely different approach as the run time is unreasonably long.
I am using JW Distance and I have the following code:</p>
```<code>ru_distances = []
# ru_final is a list of tokenized words
for i, j in enumerate(ru_final[:-1]):
    a = j
    b = ru_final[i + 1]
    dist = distance.get_jaro_distance(a, b, winkler=True, scaling=0.1)
    ru_distances.append((a, b, dist))
</code>```

Body:
I am trying to create a list with the edit distances between each word in a set of documents, ranging from 10k-42k words. If my idea of edit distance is correct, I would end up with a distance for each word compared to every single other word. So if I had a corpus of 10k words each word would have 9,999 distances associated with it. Is there any way to optimize this or possibly a completely different approach as the run time is unreasonably long.
I am using JW Distance and I have the following code:

ru_distances = []
# ru_final is a list of tokenized words
for i, j in enumerate(ru_final[:-1]):
    a = j
    b = ru_final[i + 1]
    dist = distance.get_jaro_distance(a, b, winkler=True, scaling=0.1)
    ru_distances.append((a, b, dist))


问:
Why doesn't @altname with a variable work? - TCC
This is a TCC code.

I wanted my .BAT file to return a shortened name for a specified file (with @ALTNAME), but I don't want it to return the whole path of the file. My solution doesn't seem to be working. Can someone tell me what am I doing wrong?

I used the function @FILENAME and added it to a variable. Then, I used @ALTNAME with the variable. Is this not allowed?

Edit: It works when I use %1 instead of FNAME, but it returns the whole path to the file as well, which is not what I'm looking for.

```<code>set FNAME=%@filename[%1]
set ANAME=%@altname[FNAME]

echo Name of the file:
echo %FNAME
echo.

echo Shortened name of the file:
echo %ANAME
echo.
</code>```

Body:
This is a TCC code.

I wanted my .BAT file to return a shortened name for a specified file (with @ALTNAME), but I don't want it to return the whole path of the file. My solution doesn't seem to be working. Can someone tell me what am I doing wrong?

I used the function @FILENAME and added it to a variable. Then, I used @ALTNAME with the variable. Is this not allowed?

Edit: It works when I use %1 instead of FNAME, but it returns the whole path to the file as well, which is not what I'm looking for.

set FNAME=%@filename[%1]
set ANAME=%@altname[FNAME]

echo Name of the file:
echo %FNAME
echo.

echo Shortened name of the file:
echo %ANAME
echo.


问:
Handwriting synthesis with rnn, can't understand the .npy files for style, can someone sees some sense?
I'm experimenting with some models for handwriting synthesis, I found some github repos on this, most of them are implementing the paper by Alex Graves ("Generating Sequences With Recurrent Neural Networks", 2014), and found this repository by sjvasquez, it's from 5+ years ago, but I found it more effective at generating more legible outputs, also has more controls for the characters in the output lines.

My question is about the the "styles" folder, that have some .npy files, when I open them there is no much I can understand. Can someone tell me what are these files, and what is their use? Not sure but guessing these are written words representations.

I don't know if they are used as some kind of transfer learning or fine-tunning for the model... I don't think so, because the styles files are not in any other file ("drawing.py" which contains the main class that generates the text with the "write" method, nor the "rnn.py" file which is the model itself).

These files are one of the differences I can spot between this and other repos, trying to understand if this is the reason for better results or is there anything that anyone can identify?

Sorry, I can't post the npy files here there is not much to interpret, half of them are matrix of 3x800+, you can see them with numpy:

```<code>import numpy as np
np.load("/style-0-strokes.npy")
</code>```

plotting also does not show anything I can identify

I tried other code repos for this task, many just scribble lines for some words, to the point they doodle

Body:
I'm experimenting with some models for handwriting synthesis, I found some github repos on this, most of them are implementing the paper by Alex Graves ("Generating Sequences With Recurrent Neural Networks", 2014), and found this repository by sjvasquez, it's from 5+ years ago, but I found it more effective at generating more legible outputs, also has more controls for the characters in the output lines.

My question is about the the "styles" folder, that have some .npy files, when I open them there is no much I can understand. Can someone tell me what are these files, and what is their use? Not sure but guessing these are written words representations.

I don't know if they are used as some kind of transfer learning or fine-tunning for the model... I don't think so, because the styles files are not in any other file ("drawing.py" which contains the main class that generates the text with the "write" method, nor the "rnn.py" file which is the model itself).

These files are one of the differences I can spot between this and other repos, trying to understand if this is the reason for better results or is there anything that anyone can identify?

Sorry, I can't post the npy files here there is not much to interpret, half of them are matrix of 3x800+, you can see them with numpy:

import numpy as np
np.load("/style-0-strokes.npy")

plotting also does not show anything I can identify

I tried other code repos for this task, many just scribble lines for some words, to the point they doodle


问:
Swagger doesn't found the yaml file (404)
I am using swagger to show my open API YAML file, it suddenly gives me "response status is 404 /openapi.yaml" when I run the spring boot application.

Note : I can open the /api-docs/ in swagger and it shows the apis, also when I hit the swagger config URL (http://localhost:8080/api-docs/swagger-config), it gives me the below response, which include the openapi.yaml file

```<code>{"configUrl":"/api-docs/swagger-config","oauth2RedirectUrl":"http://localhost:8080/swagger-ui/oauth2-redirect.html","url":"/openapi.yaml","validatorUrl":""}
</code>```

The problem happened only in my machine, other colleagues' machines work fine with the same codebase.

Deps:

```<code>org.springdoc:springdoc-openapi-ui:1.6.11
org.springdoc:springdoc-openapi-javadoc:1.6.11
org.springdoc:springdoc-openapi-data-rest:1.6.11
org.springdoc:springdoc-openapi-security:1.6.11
io.swagger:swagger-annotations:1.6.6
org.openapitools:jackson-databind-nullable:0.2.2
io.swagger.parser.v3:swagger-parser:2.0.32
org.openapi.generator version "5.4.0" // open API generator plugin
</code>```

Body:
I am using swagger to show my open API YAML file, it suddenly gives me "response status is 404 /openapi.yaml" when I run the spring boot application.

Note : I can open the /api-docs/ in swagger and it shows the apis, also when I hit the swagger config URL (http://localhost:8080/api-docs/swagger-config), it gives me the below response, which include the openapi.yaml file

{"configUrl":"/api-docs/swagger-config","oauth2RedirectUrl":"http://localhost:8080/swagger-ui/oauth2-redirect.html","url":"/openapi.yaml","validatorUrl":""}

The problem happened only in my machine, other colleagues' machines work fine with the same codebase.

Deps:

org.springdoc:springdoc-openapi-ui:1.6.11
org.springdoc:springdoc-openapi-javadoc:1.6.11
org.springdoc:springdoc-openapi-data-rest:1.6.11
org.springdoc:springdoc-openapi-security:1.6.11
io.swagger:swagger-annotations:1.6.6
org.openapitools:jackson-databind-nullable:0.2.2
io.swagger.parser.v3:swagger-parser:2.0.32
org.openapi.generator version "5.4.0" // open API generator plugin


问:
How to get modal overtop of navbar?
For the life of me I can't seem to get this modal (appears on click for "Apply Online") over top of the navbar,

(I'm staging it here)

I'm trying to use jQuery to hide the navbar upon click and then reappear on exit of the modal.

This is the code I used but I can't seem to get to work.

JS:

```<code>$( document.body ).click(function () {
  if ( $( ".exad-modal-item" ).hasClass("active") ) {
    $(".main-header-area").addClass("navbarishidden");
  } else {
    $( ".main-header-area" ).removeClass("navbarishidden");
  }
});
</code>```

The modal already gets the class .active added upon click so I based this code on that.

CSS:

```<code>.navbarishidden {
    display: none !important;
}

</code>```

Any help would be appreciated, I was also wondering if where I placed the JS had anything to do with it? I keep trying different things.

Title: How to get modal overtop of navbar?

Body:
For the life of me I can't seem to get this modal (appears on click for "Apply Online") over top of the navbar,

(I'm staging it here)

I'm trying to use jQuery to hide the navbar upon click and then reappear on exit of the modal.

This is the code I used but I can't seem to get to work.

JS:

$( document.body ).click(function () {
  if ( $( ".exad-modal-item" ).hasClass("active") ) {
    $(".main-header-area").addClass("navbarishidden");
  } else {
    $( ".main-header-area" ).removeClass("navbarishidden");
  }
});

The modal already gets the class .active added upon click so I based this code on that.

CSS:

.navbarishidden {
    display: none !important;
}

Any help would be appreciated, I was also wondering if where I placed the JS had anything to do with it? I keep trying different things.


问:
MSTest hides data from html log output
so I am using the MSTest for framework for visual studio 2022 to run a few tests for QA. I want the data in a html format to easily keep track of the tests. It would show the failed test results just fine, but I want it to show which tests were ran as well, which are not displayed.

I found that the data I want is there in the html file, but for some reason MSTest would hide that data using css. How can I get MSTest to show this data? This is what it and what I actually want: https://imgur.com/a/LCW3zyR

Title: MSTest hides data from html log output


问:
AWS SQS SimpleMessageListenerContainer failing while polling queue
I have one SqsListener in my spring boot app as below:

```<code>@SqsListener(value = "QUEUE-FQN", deletionPolicy = SqsMessageDeletionPolicy.NEVER)
    private void receiveNotifications(String payload, MessageHeaders headers, Acknowledgment acknowledgment)
            throws IOException, ParseException, InterruptedException {
        try {
        // process message here
    }
}
</code>```

And the following two beans defined:

```<code>    @Bean
    public AmazonSQSAsync amazonSQSAsync(AWSCredentialsProvider awsCredentialsProvider) {
        return AmazonSQSAsyncClientBuilder
                .standard()
                .withCredentials(awsCredentialsProvider)
                .withRegion(Regions.US_EAST_1.getName())
                .build();
    }
</code>```
```<code>@Bean
    public SimpleMessageListenerContainerFactory simpleMessageListenerContainerFactory(AmazonSQSAsync amazonSqs) {
        SimpleMessageListenerContainerFactory factory = new SimpleMessageListenerContainerFactory();
        factory.setAmazonSqs(amazonSqs);
        factory.setMaxNumberOfMessages(10);
        factory.setAutoStartup(false);
        return factory;
    }
</code>```

After the  simpleMessageListenerContainer.start(QUEUE_NAME), I see below exceptions constantly and the listener is never able to poll for new messages (never makes any progress).

Anything that I am doing wrong here? How to get past this error:

```<code>WARN 1297 --- [enerContainer-2] i.a.c.m.l.SimpleMessageListenerContainer : An Exception occurred while polling queue 'https://sqs:us-east-1:amazonaws:com/ACCOUNTID/QUEUE_NAME'. The failing operation will be retried in 10000 milliseconds
org.springframework.core.task.TaskRejectedException: Executor [java.util.concurrent.ThreadPoolExecutor@3cee2db[Running, pool size = 11, active threads = 11, queued tasks = 0, completed tasks = 1188]] did not accept task: io.awspring.cloud.messaging.listener.SimpleMessageListenerContainer$SignalExecutingRunnable@681b4433
    at org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor.execute(ThreadPoolTaskExecutor.java:363)
    at io.awspring.cloud.messaging.listener.SimpleMessageListenerContainer$AsynchronousMessageListener.run(SimpleMessageListenerContainer.java:343)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: java.util.concurrent.RejectedExecutionException: Task io.awspring.cloud.messaging.listener.SimpleMessageListenerContainer$SignalExecutingRunnable@681b4433 rejected from java.util.concurrent.ThreadPoolExecutor@3cee2db[Running, pool size = 11, active threads = 11, queued tasks = 0, completed tasks = 1188]
    at java.base/java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2055)
    at java.base/java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:825)
    at java.base/java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1355)
    at org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor.execute(ThreadPoolTaskExecutor.java:360)
    ... 6 more
</code>```

Body:
I have one SqsListener in my spring boot app as below:

@SqsListener(value = "QUEUE-FQN", deletionPolicy = SqsMessageDeletionPolicy.NEVER)
    private void receiveNotifications(String payload, MessageHeaders headers, Acknowledgment acknowledgment)
            throws IOException, ParseException, InterruptedException {
        try {
        // process message here
    }
}

And the following two beans defined:

    @Bean
    public AmazonSQSAsync amazonSQSAsync(AWSCredentialsProvider awsCredentialsProvider) {
        return AmazonSQSAsyncClientBuilder
                .standard()
                .withCredentials(awsCredentialsProvider)
                .withRegion(Regions.US_EAST_1.getName())
                .build();
    }

@Bean
    public SimpleMessageListenerContainerFactory simpleMessageListenerContainerFactory(AmazonSQSAsync amazonSqs) {
        SimpleMessageListenerContainerFactory factory = new SimpleMessageListenerContainerFactory();
        factory.setAmazonSqs(amazonSqs);
        factory.setMaxNumberOfMessages(10);
        factory.setAutoStartup(false);
        return factory;
    }

After the  simpleMessageListenerContainer.start(QUEUE_NAME), I see below exceptions constantly and the listener is never able to poll for new messages (never makes any progress).

Anything that I am doing wrong here? How to get past this error:

WARN 1297 --- [enerContainer-2] i.a.c.m.l.SimpleMessageListenerContainer : An Exception occurred while polling queue 'https://sqs:us-east-1:amazonaws:com/ACCOUNTID/QUEUE_NAME'. The failing operation will be retried in 10000 milliseconds
org.springframework.core.task.TaskRejectedException: Executor [java.util.concurrent.ThreadPoolExecutor@3cee2db[Running, pool size = 11, active threads = 11, queued tasks = 0, completed tasks = 1188]] did not accept task: io.awspring.cloud.messaging.listener.SimpleMessageListenerContainer$SignalExecutingRunnable@681b4433
    at org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor.execute(ThreadPoolTaskExecutor.java:363)
    at io.awspring.cloud.messaging.listener.SimpleMessageListenerContainer$AsynchronousMessageListener.run(SimpleMessageListenerContainer.java:343)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: java.util.concurrent.RejectedExecutionException: Task io.awspring.cloud.messaging.listener.SimpleMessageListenerContainer$SignalExecutingRunnable@681b4433 rejected from java.util.concurrent.ThreadPoolExecutor@3cee2db[Running, pool size = 11, active threads = 11, queued tasks = 0, completed tasks = 1188]
    at java.base/java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2055)
    at java.base/java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:825)
    at java.base/java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1355)
    at org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor.execute(ThreadPoolTaskExecutor.java:360)
    ... 6 more


问:
Python write and then read csv. Cant open brand new file
python creates an excel type csv file, but it is not opening and printing the single line of information that is saved on row 1.

I'm new to coding and my syntax seems fine, I believe it has to do with how I may be calling it.

I tried changing the code multiple times to call the file differently, but nothing is working. The shell just closes after the file is created

```<code>import os
import csv
import time

directory = input("Enter directory to save file: ")

# directory will automatically default to current directory if user presses enter key

if directory == "":

    directory = os.path.dirname(os.path.realpath(__file__))

filename = input("Enter filename: ")
name = input("Enter name: ")
address = input("Enter address: ")
phone = input("Enter phone number: ")

# create file object to write to specified file in directory
with open("{}/{}.csv".format(directory, filename), "w") as file:
    file.write(",".join([name, address, phone]) + "\n")
# create file object to read from specified file in directory

"""
original lines that still do the same thing
with open("{}/{}.csv".format(directory, filename), "r") as file:

    print("{}/{}.csv contents".format(directory, filename))

    for line in file:
        print(line)
"""
time.sleep(5)
with open("{}/{}.csv".format(directory, filename), "r") as file:
    cvsreader = csv.reader(file)
    print("{}/{}.csv contents".format(directory, filename))

for row in file:

    print(row)
input("Press Enter")

</code>```

Body:
python creates an excel type csv file, but it is not opening and printing the single line of information that is saved on row 1.

I'm new to coding and my syntax seems fine, I believe it has to do with how I may be calling it.

I tried changing the code multiple times to call the file differently, but nothing is working. The shell just closes after the file is created

import os
import csv
import time

directory = input("Enter directory to save file: ")

# directory will automatically default to current directory if user presses enter key

if directory == "":

    directory = os.path.dirname(os.path.realpath(__file__))

filename = input("Enter filename: ")
name = input("Enter name: ")
address = input("Enter address: ")
phone = input("Enter phone number: ")

# create file object to write to specified file in directory
with open("{}/{}.csv".format(directory, filename), "w") as file:
    file.write(",".join([name, address, phone]) + "\n")
# create file object to read from specified file in directory

"""
original lines that still do the same thing
with open("{}/{}.csv".format(directory, filename), "r") as file:

    print("{}/{}.csv contents".format(directory, filename))

    for line in file:
        print(line)
"""
time.sleep(5)
with open("{}/{}.csv".format(directory, filename), "r") as file:
    cvsreader = csv.reader(file)
    print("{}/{}.csv contents".format(directory, filename))

for row in file:

    print(row)
input("Press Enter")


问:
Expo-Notification not showing notification when in foreground
I have setup the Expo-Notifications, and I'm using local notifications as reminders, all works well until I need a notification to show while I'm inside the app. The notification always shows while the app is in background but I can't get it to work in the foreground.

App.tsx:

```<code>import * as Notifications from "expo-notifications";

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: false,
  }),
});

const App = () => {

  const notificationListener = useRef();
  const responseListener = useRef();
  const [notification, setNotification] = useState(false);

    useEffect(() => {
      const getPerm = async() => {
        const { status: existingStatus } = await Notifications.getPermissionsAsync();
        let finalStatus = existingStatus
        if(existingStatus !== 'granted'){
          const { lastStatus }:any = await Notifications.requestPermissionsAsync();
          finalStatus = lastStatus
        }
        if (finalStatus !== "granted") {
          console.log("Failed to get push token for push notification!");
          return;
        }
      }
      getPerm()

      notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
        setNotification(notification);
        console.log("NOTIF: ", notification)
      });

      responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
        console.log("RES: ",response);
      });

      return () => {
        Notifications.removeNotificationSubscription(notificationListener.current);
        Notifications.removeNotificationSubscription(responseListener.current);
      };
    }, []) ....
</code>```

How I schedule the notification in a different file:

```<code>const triggerNotifications = async () => {
    await Notifications.scheduleNotificationAsync({
    content: {
        title: "You’ve got mail! ",
        body: "Here is the notification body",
        data: { data: "goes here" }
    },
    trigger: { seconds: 5 },
    });
}
</code>```

Body:
I have setup the Expo-Notifications, and I'm using local notifications as reminders, all works well until I need a notification to show while I'm inside the app. The notification always shows while the app is in background but I can't get it to work in the foreground.

App.tsx:

import * as Notifications from "expo-notifications";

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: false,
  }),
});

const App = () => {

  const notificationListener = useRef();
  const responseListener = useRef();
  const [notification, setNotification] = useState(false);

    useEffect(() => {
      const getPerm = async() => {
        const { status: existingStatus } = await Notifications.getPermissionsAsync();
        let finalStatus = existingStatus
        if(existingStatus !== 'granted'){
          const { lastStatus }:any = await Notifications.requestPermissionsAsync();
          finalStatus = lastStatus
        }
        if (finalStatus !== "granted") {
          console.log("Failed to get push token for push notification!");
          return;
        }
      }
      getPerm()

      notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
        setNotification(notification);
        console.log("NOTIF: ", notification)
      });

      responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
        console.log("RES: ",response);
      });

      return () => {
        Notifications.removeNotificationSubscription(notificationListener.current);
        Notifications.removeNotificationSubscription(responseListener.current);
      };
    }, []) ....

How I schedule the notification in a different file:

const triggerNotifications = async () => {
    await Notifications.scheduleNotificationAsync({
    content: {
        title: "You’ve got mail! ",
        body: "Here is the notification body",
        data: { data: "goes here" }
    },
    trigger: { seconds: 5 },
    });
}


问:
How to find the eprocess structure in the RAM dump?
I'm new to this business and I have a difficult task. I need to write a program with which it would be possible to get the data of a certain process. This process is in a file .dmp, which is a full RAM dump. As far as I know, every process in Windows OS has an EPROCESS structure. So, having received this structure, I will be able to find the data of this process. Are there any libraries or functions that can facilitate this task? For example, in C++ or Python?</p>


问:
Create a Docker image with DockerFile to run two windows services
So I'm trying to build a Docker Image based on windows that will run two windows services.

This builds an image as expected but when I run the image I don't see the two windows services present and I don't see the services file with my edit in it.

I've searched and searched and have not found much help with Docker and Windows mostly everything is linux based help.  I will need to expose tcp/ip ports as well for the 2 services.

Here is what I have in my DockerFile so far

```<code>FROM mcr.microsoft.com/windows/servercore:ltsc2019

COPY bin C:\Company\App\bin
COPY Installers C:\Company\Installers

WORKDIR "C:\Company\Installers"
SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]

RUN Start-Process 'C:\Company\Installers\msodbcsql.msi' '/qn' -PassThru | Wait-Process;

RUN echo "apprecv           22804/tcp                           #Company AppRecv service" >> c:\windows\system32\drivers\etc\services

WORKDIR "C:\Company\App\bin"

RUN Start-Process 'SC.exe' -Wait -ArgumentList 'CREATE "App Poll" binpath="C:\Company\App\bin\apppoll.exe" start=disabled';
RUN Start-Process 'SC.exe' -Wait -ArgumentList 'DESCRIPTION "App Poll" "Pulls Data"';
RUN Start-Process 'SC.exe' -Wait -ArgumentList 'CREATE "App Receive" binpath="C:\Company\App\bin\apprecv.exe" start=disabled';
RUN Start-Process 'SC.exe' -Wait -ArgumentList 'DESCRIPTION "App Receive" "Receives Data"';
</code>```

I first run this to build the image

```<code>docker build -t app .
</code>```

Then when I run

```<code>docker run -it app:latest powershell.exe
</code>```

I first check the services file and don't see it changed and then when I call Get-Services I don't see the windows services installed.

What am I missing here?  Eventually, I plan to run this in Azure.

Body:
So I'm trying to build a Docker Image based on windows that will run two windows services.

This builds an image as expected but when I run the image I don't see the two windows services present and I don't see the services file with my edit in it.

I've searched and searched and have not found much help with Docker and Windows mostly everything is linux based help.  I will need to expose tcp/ip ports as well for the 2 services.

Here is what I have in my DockerFile so far

FROM mcr.microsoft.com/windows/servercore:ltsc2019

COPY bin C:\Company\App\bin
COPY Installers C:\Company\Installers

WORKDIR "C:\Company\Installers"
SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]

RUN Start-Process 'C:\Company\Installers\msodbcsql.msi' '/qn' -PassThru | Wait-Process;

RUN echo "apprecv           22804/tcp                           #Company AppRecv service" >> c:\windows\system32\drivers\etc\services

WORKDIR "C:\Company\App\bin"

RUN Start-Process 'SC.exe' -Wait -ArgumentList 'CREATE "App Poll" binpath="C:\Company\App\bin\apppoll.exe" start=disabled';
RUN Start-Process 'SC.exe' -Wait -ArgumentList 'DESCRIPTION "App Poll" "Pulls Data"';
RUN Start-Process 'SC.exe' -Wait -ArgumentList 'CREATE "App Receive" binpath="C:\Company\App\bin\apprecv.exe" start=disabled';
RUN Start-Process 'SC.exe' -Wait -ArgumentList 'DESCRIPTION "App Receive" "Receives Data"';

I first run this to build the image

docker build -t app .

Then when I run

docker run -it app:latest powershell.exe

I first check the services file and don't see it changed and then when I call Get-Services I don't see the windows services installed.

What am I missing here?  Eventually, I plan to run this in Azure.


问:
Unknown AID UICC initialization iPhone SE2
When inserting an UICC in an iPhone SE2 and recording the APDU messages between the modem and the UICC I see a sequence opening a logical channel and trying to select an application. I could not find any reference to this application. What is it?

```<code>01 a4 04 0c 10 a0 00 00 00 09 02 03 ff ff ff ff 89 01 00 00 ff
</code>```

The RID a0 00 00 00 09 is registered for the ETSI.

Body:
When inserting an UICC in an iPhone SE2 and recording the APDU messages between the modem and the UICC I see a sequence opening a logical channel and trying to select an application. I could not find any reference to this application. What is it?

01 a4 04 0c 10 a0 00 00 00 09 02 03 ff ff ff ff 89 01 00 00 ff

The RID a0 00 00 00 09 is registered for the ETSI.


问:
CodeBuild with parallel builds
I'm using CodeBuild with this syntax in buildspec:

```<code>version: 0.2
phases:
  pre_build:
    commands:
      - pwd
  build:
    commands:
    - echo "hi" && sleep 50
    - echo "hi" && sleep 20
    batch:
      fast-fail: false
      build-list:
        - identifier: build1
        - identifier: build2
</code>```

It should be running in parallel but run sequentially.

What have I missed?

Try an example above

Title: CodeBuild with parallel builds

Body:
I'm using CodeBuild with this syntax in buildspec:

version: 0.2
phases:
  pre_build:
    commands:
      - pwd
  build:
    commands:
    - echo "hi" && sleep 50
    - echo "hi" && sleep 20
    batch:
      fast-fail: false
      build-list:
        - identifier: build1
        - identifier: build2

It should be running in parallel but run sequentially.

What have I missed?

Try an example above


问:
Is there a way to put API gateway in front of AWS Secrets manager
I am wanting to create an API that goes in front of AWS Secrets manager and use the api to get secret values. In terms of security of accessing the API, I'm not worried about security of the API Gateway since I can set up authorization keys/certificates and the API will only be access by the lambda.

When I attempted to add the secrets manager and test the API, I was met with <UnknownOperationException/>

Here is the current setup of my API Gateway

Is there any documentation on doing something like this, if it's even possible? All and any help is appreciated.

EDIT: More explanation

I want to know if there is an API Gateway only solution for this
mainly because of package size, execution time, and RAM Usage if I were to have a lambda as a middleman. If I use a lambda function to get the secrets from Secrets manager, the max amount of ram used is the max amount of whatever I set as the lambda function (i.e. Lambda function has 128MB ram or 10GB ram, the lambda function will use up all 1of it to get the secrets).


问:
Amazon s3 Services for J2me in blackberry
I am developing a social network app for blackberry. In it i need to upload audio and image files and retrieve it at later time. So for that i need to use Amazon services. I downloaded the j2me toolkit for Amazon s3 from below link.

I have keys from amazon services. I can create buckets through it and i can store,retrieve and delete String objects. But there is no option in jar to store images or any other files.

So anyone please help me out to store image and audio  files.   Thanks in advance.

ContentLicense: CC BY-SA 3.0


问:
Request blocked by CORS on web, but not on Android
I am trying to make a request to Replicate. When executing the below code on Android, everything works flawlessly.

import 'package:http/http.dart' as http;

    var headers = {
      'Authorization': 'Token $replicate_APIKEY',
      'Content-Type': 'application/json',
    };
    var data =
        '{"version": "30414ee7c4fffc37e260fcab7842b5be470b9b840f2b608f5baa9bbef9a259ed", "input": {"model":"medium","audio": "$downloadUrl"}}';
    var url = Uri.parse('https://api.replicate.com/v1/predictions');

    http.Response res = await http.post(url, headers: headers, body: data);
    print(res.statusCode);
```
<p>When I try to run it in a web environment, I get an <code>Error: XMLHttpRequest error</code> and in my console I can see</p>
<p><img src="https://i.stack.imgur.com/lY6fo.png" alt="Dev Tools screenshot" /></p>
<p>with the correct payload and the following headers.</p>
```Request URL: https://api.replicate.com/v1/predictions
Referrer Policy: strict-origin-when-cross-origin
Provisional headers are shown
Authorization: Token -REDACTED-
Content-Type: application/json; charset=utf-8
Referer: http://localhost:59140/
sec-ch-ua: "Google Chrome";v="107", "Chromium";v="107", "Not=A?Brand";v="24"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36
```
<p>The same requests, or to my knowladge an equivalent one works with curl as well:</p>
<pre class="lang-bash prettyprint-override"><code>curl
--location --request POST 'https://api.replicate.com/v1/predictions' \
--header 'Authorization: Token -REDACTED-' \
--header 'Content-Type: application/json' \
--data-raw '{"version": "30414ee7c4fffc37e260fcab7842b5be470b9b840f2b608f5baa9bbef9a259ed", "input": {"audio": "-REDACTED-"}}'

</code>```

Please someone educate me on the matter, I have no idea what is going on :)

Body:
I am trying to make a request to Replicate. When executing the below code on Android, everything works flawlessly.

import 'package:http/http.dart' as http;

    var headers = {
      'Authorization': 'Token $replicate_APIKEY',
      'Content-Type': 'application/json',
    };
    var data =
        '{"version": "30414ee7c4fffc37e260fcab7842b5be470b9b840f2b608f5baa9bbef9a259ed", "input": {"model":"medium","audio": "$downloadUrl"}}';
    var url = Uri.parse('https://api.replicate.com/v1/predictions');

    http.Response res = await http.post(url, headers: headers, body: data);
    print(res.statusCode);

When I try to run it in a web environment, I get an Error: XMLHttpRequest error and in my console I can see

with the correct payload and the following headers.

Request URL: https://api.replicate.com/v1/predictions
Referrer Policy: strict-origin-when-cross-origin
Provisional headers are shown
Authorization: Token -REDACTED-
Content-Type: application/json; charset=utf-8
Referer: http://localhost:59140/
sec-ch-ua: "Google Chrome";v="107", "Chromium";v="107", "Not=A?Brand";v="24"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36

The same requests, or to my knowladge an equivalent one works with curl as well:

curl
--location --request POST 'https://api.replicate.com/v1/predictions' \
--header 'Authorization: Token -REDACTED-' \
--header 'Content-Type: application/json' \
--data-raw '{"version": "30414ee7c4fffc37e260fcab7842b5be470b9b840f2b608f5baa9bbef9a259ed", "input": {"audio": "-REDACTED-"}}'

Please someone educate me on the matter, I have no idea what is going on :)


问:
Invalid procedure call or argument in Javascript on IE8
I have a little problem on IE8. Everything works fine on Chrome and FF.

I have a function like this:

```<code>var Dog = function(){};
</code>```

and I'm able to do this, of course:

```<code>new Dog();
</code>```

I open a popup window and I try to do this:

```<code>new window.opener.Dog();
</code>```

and now, only in IE, I get:

```<code>Invalid procedure call or argument
</code>```

Does anyone knows if it is possible to create an instance of a function defined on the parent window?

Thanks.

Body:
I have a little problem on IE8. Everything works fine on Chrome and FF.

I have a function like this:

var Dog = function(){};

and I'm able to do this, of course:

new Dog();

I open a popup window and I try to do this:

new window.opener.Dog();

and now, only in IE, I get:

Invalid procedure call or argument

Does anyone knows if it is possible to create an instance of a function defined on the parent window?

Thanks.


问:
How to merge dictionaries within a list based on values?
I am working on a task of preprocessing messy (fake) data. I've managed to go through most of my data and clean it up until this point shown below:

```<code>[{'birthdate': '1966-07-17', 'name': 'WORDS, MARK M'},
 {'birthdate': '1966-07-17','name': 'WORDS, MARK MY','placeOfBirth': 'WYOMING','ssn': '999999999'},
 {'birthdate': '1966-07-17', 'name': 'WORDS, MARK MY', 'ssn': '999999999'},
 {'birthdate': '1970-01-01', 'placeOfBirth': 'MISSOURI', 'ssn': '999999999'},
 {'birthdate': '1970-01-01','name': 'BOLLIE PRIDE, CHESTER','placeOfBirth': 'INDIANA','ssn': '999999999'},
 {'birthdate': '1966-07-17', 'name': 'WORDS, MARK M', 'ssn': '999999999'}]
</code>```

I want to merge dictionaries pertaining to the same person, which can be difficult to figure out based on the data. Four of these dictionaries are pertaining to MARK WORDS.

One issue is that two dictionaries has the middle initial of the name (M) and the other dictionaries have the full middle name (MY).

The second issue is that they don't all have all of the keys.

In future iterations of this task, I also don't know which keys might be guaranteed in all of the dictionaries (In this case birthdate is in all 4 dictionaries regarding MARK WORDS). I also want to note that other dictionaries in the list might not pertain to the same individual (e.g. CHESTER BOLLIE PRIDE). I'm just not sure how to go about this in anyway, so any tips or thoughts would be great.

Body:
I am working on a task of preprocessing messy (fake) data. I've managed to go through most of my data and clean it up until this point shown below:

[{'birthdate': '1966-07-17', 'name': 'WORDS, MARK M'},
 {'birthdate': '1966-07-17','name': 'WORDS, MARK MY','placeOfBirth': 'WYOMING','ssn': '999999999'},
 {'birthdate': '1966-07-17', 'name': 'WORDS, MARK MY', 'ssn': '999999999'},
 {'birthdate': '1970-01-01', 'placeOfBirth': 'MISSOURI', 'ssn': '999999999'},
 {'birthdate': '1970-01-01','name': 'BOLLIE PRIDE, CHESTER','placeOfBirth': 'INDIANA','ssn': '999999999'},
 {'birthdate': '1966-07-17', 'name': 'WORDS, MARK M', 'ssn': '999999999'}]

I want to merge dictionaries pertaining to the same person, which can be difficult to figure out based on the data. Four of these dictionaries are pertaining to MARK WORDS.

One issue is that two dictionaries has the middle initial of the name (M) and the other dictionaries have the full middle name (MY).

The second issue is that they don't all have all of the keys.

In future iterations of this task, I also don't know which keys might be guaranteed in all of the dictionaries (In this case birthdate is in all 4 dictionaries regarding MARK WORDS). I also want to note that other dictionaries in the list might not pertain to the same individual (e.g. CHESTER BOLLIE PRIDE). I'm just not sure how to go about this in anyway, so any tips or thoughts would be great.


问:
Flutter emoji font working om iOS emulator, but not on real device
I downloaded and put the NotoColorEmoji-Regular.ttf in the assets and configured it in the pubspec.yml

```<code>    - family: NotoColorEmoji
      fonts:
        - asset: assets/fonts/Noto_Color_Emoji/NotoColorEmoji-Regular.ttf

</code>```

I am using it like this:

```<code>Text(emoji,
  style: const TextStyle(
    fontWeight: FontWeight.w400,
    fontSize: 22,
    height: 1,
    fontFamily: 'NotoColorEmoji',
    color: const Color(0xFF191919),
  ),
)
</code>```

This works on

Android emulator

Android device

iOS emulator (iOS 15.5, iphone 13)

It does not work on

a real device iOS 12.5.5, iphone 6. Everything else of the app works fine on the device, but the font is not working (i.e. nothing shows up but an emoji is expected).

Unfortunately I have no other real iphone device for testing => Can anyone confirm or disprove the behavior on other real devices?

I tried

uninstall the app from the device

flutter clean

re-install the app (flutter run)

run the app from xcode

I found

https://github.com/googlefonts/noto-emoji/issues/72 which indicates that macOS does not support the ttf format, but Apple would compile the ttf using a SBIX format, which does not support CBDT/CBLC as used by the NotoColorEmoji font. But I could not figure out if that would be an issue with iOS? And also I wonder because on the emulator it runs fine.

EDIT

As a workaround we currently use the system font on ios:

```<code>TextStyle textEmoji(BuildContext context) {
  return TextStyle(
    fontFamily: Platform.isIOS
      ? null // see https://stackoverflow.com/questions/74710185/flutter-emoji-font-working-om-ios-emulator-but-not-on-real-device
      : 'NotoColorEmoji',
    // ...
  );
}
</code>```

Body:
I downloaded and put the NotoColorEmoji-Regular.ttf in the assets and configured it in the pubspec.yml

    - family: NotoColorEmoji
      fonts:
        - asset: assets/fonts/Noto_Color_Emoji/NotoColorEmoji-Regular.ttf

I am using it like this:

Text(emoji,
  style: const TextStyle(
    fontWeight: FontWeight.w400,
    fontSize: 22,
    height: 1,
    fontFamily: 'NotoColorEmoji',
    color: const Color(0xFF191919),
  ),
)

This works on

Android emulator

Android device

iOS emulator (iOS 15.5, iphone 13)

It does not work on

a real device iOS 12.5.5, iphone 6. Everything else of the app works fine on the device, but the font is not working (i.e. nothing shows up but an emoji is expected).

Unfortunately I have no other real iphone device for testing => Can anyone confirm or disprove the behavior on other real devices?

I tried

uninstall the app from the device

flutter clean

re-install the app (flutter run)

run the app from xcode

I found

https://github.com/googlefonts/noto-emoji/issues/72 which indicates that macOS does not support the ttf format, but Apple would compile the ttf using a SBIX format, which does not support CBDT/CBLC as used by the NotoColorEmoji font. But I could not figure out if that would be an issue with iOS? And also I wonder because on the emulator it runs fine.

EDIT

As a workaround we currently use the system font on ios:

TextStyle textEmoji(BuildContext context) {
  return TextStyle(
    fontFamily: Platform.isIOS
      ? null // see https://stackoverflow.com/questions/74710185/flutter-emoji-font-working-om-ios-emulator-but-not-on-real-device
      : 'NotoColorEmoji',
    // ...
  );
}


问:
Undefined 'map' for nilClass using two models inside a form - Ruby on Rails
I have a models name Menu

```<code>class Menu < ApplicationRecord
  validates_presence_of :name

  has_many :menus_ingredients
  accepts_nested_attributes_for :menus_ingredients
end
</code>```

And I want to connect it to Ingredients

```<code>class Ingredient < ApplicationRecord
  include ActionView::Helpers::NumberHelper

  validates_presence_of :name
  validates_presence_of :price_per_num_of_unit
  validates_presence_of :num_of_unit
  validates_presence_of :unit
end

</code>```

Therefore, I need a tables, that connect them both. Calls, MenusIngredient

```<code>class MenusIngredient < ApplicationRecord
  validates_presence_of :menu_id
  validates_presence_of :ingredient_id
  validates_presence_of :qty

  belongs_to :menu, optional: true
  belongs_to :ingredient
end

</code>```

Next, I need to be able to add new Menu with MenusIngredient in the same form. I use this form.

```<code><h1> New Menu </h1>
<%= form_with model: @menu do |form| %>
  <div>
    <%= form.label :name %>
    <%= form.text_field :name %>
  </div>

  <% for i in 0..9 %>
  <div>
    <%= form.fields_for :menus_ingredients do |mi| %>
      <%= mi.label :menus_ingredients %>
      <%= mi.collection_select :ingredient_id, @ingredients, :id, :name, :prompt => "Select ingredients" %>
      <%= mi.text_field :qty, placeholder: "unit in gram" %>
    <% end %>
  </div>
  <% end %>

  <div>
    <%= form.submit %>
  </div>
<% end %>

</code>```

but then, I got error like this.

undefined map for nilClass

What should I do? Thank you

Here is what my Controller looks like

```<code>class MenusController < ApplicationController
  def index
    @menus = Menu.all
  end

  def show
    @menu = Menu.find(params[:id])
  end

  def new
    @menu = Menu.new
    @menu.menus_ingredients.build
    @ingredients = Ingredient.all
  end

  def create
    @menu = Menu.new permit_params

    if @menu.save
      redirect_to @menu
    else
      render :new, status: :unprocessable_entity
    end
  end

  private

  def permit_params
    params.require(:menu).permit!
  end
end

</code>```

Body:
I have a models name Menu

class Menu < ApplicationRecord
  validates_presence_of :name

  has_many :menus_ingredients
  accepts_nested_attributes_for :menus_ingredients
end

And I want to connect it to Ingredients

class Ingredient < ApplicationRecord
  include ActionView::Helpers::NumberHelper

  validates_presence_of :name
  validates_presence_of :price_per_num_of_unit
  validates_presence_of :num_of_unit
  validates_presence_of :unit
end

Therefore, I need a tables, that connect them both. Calls, MenusIngredient

class MenusIngredient < ApplicationRecord
  validates_presence_of :menu_id
  validates_presence_of :ingredient_id
  validates_presence_of :qty

  belongs_to :menu, optional: true
  belongs_to :ingredient
end

Next, I need to be able to add new Menu with MenusIngredient in the same form. I use this form.

 New Menu

<%= form_with model: @menu do |form| %>

    <%= form.label :name %>
    <%= form.text_field :name %>

  <% for i in 0..9 %>

    <%= form.fields_for :menus_ingredients do |mi| %>
      <%= mi.label :menus_ingredients %>
      <%= mi.collection_select :ingredient_id, @ingredients, :id, :name, :prompt => "Select ingredients" %>
      <%= mi.text_field :qty, placeholder: "unit in gram" %>
    <% end %>

  <% end %>

    <%= form.submit %>

<% end %>

but then, I got error like this.

undefined map for nilClass

What should I do? Thank you

Here is what my Controller looks like

class MenusController < ApplicationController
  def index
    @menus = Menu.all
  end

  def show
    @menu = Menu.find(params[:id])
  end

  def new
    @menu = Menu.new
    @menu.menus_ingredients.build
    @ingredients = Ingredient.all
  end

  def create
    @menu = Menu.new permit_params

    if @menu.save
      redirect_to @menu
    else
      render :new, status: :unprocessable_entity
    end
  end

  private

  def permit_params
    params.require(:menu).permit!
  end
end


问:
By how much assignment is slower/faster than indexation?
When does redeclaring a new variable faster than accessing an item in a list repeatedly in python?

for example with this list -

import time

fruits = ["orange", "banana", "strawberry", "apple"]

```
<p>when running this code</p>
<pre class="lang-py prettyprint-override"><code>timesToRun = 1000000
timesToAccess = 100

start_time = time.time()
for x in range(timesToRun):
    for y in range(timesToAccess):
        tempFruit = fruits[2] # Accessing the list directly
print("--- %s seconds ---" % (time.time() - start_time))

start_time = time.time()
for x in range(timesToRun):
    myFruit = fruits[2] # Declaring a new variable
    for y in range(timesToAccess):
        tempFruit = myFruit # Accessing the variable
print("--- %s seconds ---" % (time.time() - start_time))
</code>```

And I got the following print -

```<code>--- 5.268802165985107 seconds ---
--- 4.507154226303101 seconds ---
</code>```

so clearly redeclaring the item is faster than accessing it 100 times,

but when I am only accessing the item once

timesToRun = 10000000
timesToAccess = 1
```
<p>the print is</p>
```--- 1.948554277420044 seconds ---
--- 2.1312568187713623 seconds ---
```

so now it is faster to just access it directly.

So my question is what is the threshold, when is it better to redeclare the item than access it directly? and with a dictionary or NumPy arrays is it any different answer?

EDIT:
I guess my question can also be by how much does declaring a new variable is slower then just accessing a list.

Body:
When does redeclaring a new variable faster than accessing an item in a list repeatedly in python?

for example with this list -

import time

fruits = ["orange", "banana", "strawberry", "apple"]

when running this code

timesToRun = 1000000
timesToAccess = 100

start_time = time.time()
for x in range(timesToRun):
    for y in range(timesToAccess):
        tempFruit = fruits[2] # Accessing the list directly
print("--- %s seconds ---" % (time.time() - start_time))

start_time = time.time()
for x in range(timesToRun):
    myFruit = fruits[2] # Declaring a new variable
    for y in range(timesToAccess):
        tempFruit = myFruit # Accessing the variable
print("--- %s seconds ---" % (time.time() - start_time))

And I got the following print -

--- 5.268802165985107 seconds ---
--- 4.507154226303101 seconds ---

so clearly redeclaring the item is faster than accessing it 100 times,

but when I am only accessing the item once

timesToRun = 10000000
timesToAccess = 1

the print is

--- 1.948554277420044 seconds ---
--- 2.1312568187713623 seconds ---

so now it is faster to just access it directly.

So my question is what is the threshold, when is it better to redeclare the item than access it directly? and with a dictionary or NumPy arrays is it any different answer?

EDIT:
I guess my question can also be by how much does declaring a new variable is slower then just accessing a list.


问:
Where is the simulator option in Xcode?
I have no simulator option as shown in the image below. I just installed Xcode

Title: Where is the simulator option in Xcode?


问:
Trying to understand the vtable content
I have this example code:

https://godbolt.org/z/reM8PY8r9

struct Base {
    Base() {}
    virtual void foo() = 0;
};

struct Derived: public Base {
    Derived(): Base() { }

    void foo() {
        return;
    }
};

Base* todolist[2] = { new Derived()};

void realtime() {
    for (int i=0; i<2; i++)
        todolist[i]->foo();
}
```
<p>Which produces this AVR assembly:</p>
```__tmp_reg__ = 0
Derived::foo():
  ret
realtime():
  lds r26,todolist
  lds r27,todolist+1
  ld r30,X+
  ld r31,X
  sbiw r26,1
  ld __tmp_reg__,Z+
  ld r31,Z
  mov r30,__tmp_reg__
  ldi r24,hi8(gs(Derived::foo()))
  cpi r30,lo8(gs(Derived::foo()))
  cpc r31,r24
  brne .L9
.L4:
  lds r26,todolist+2
  lds r27,todolist+2+1
  ld r30,X+
  ld r31,X
  sbiw r26,1
  ld __tmp_reg__,Z+
  ld r31,Z
  mov r30,__tmp_reg__
  ldi r24,hi8(gs(Derived::foo()))
  cpi r30,lo8(gs(Derived::foo()))
  cpc r31,r24
  brne .L10
  ret
.L9:
  movw r24,r26
  icall
  rjmp .L4
.L10:
  movw r24,r26
  ijmp
_GLOBAL__sub_I_todolist:
  ldi r24,lo8(2)
  ldi r25,0
  rcall operator new(unsigned int)
  movw r30,r24
  ldi r24,lo8(vtable for Derived+4)
  ldi r25,hi8(vtable for Derived+4)
  std Z+1,r25
  st Z,r24
  sts todolist+1,r31
  sts todolist,r30
  ret
vtable for Derived:
  .word 0
  .word 0
  .word gs(Derived::foo())
todolist:
  .zero 4
```
<p>What I'm trying to understand is the vtable:</p>
```vtable for Derived:
  .word 0
  .word 0
  .word gs(Derived::foo())
```
<p>Why it's not just the foo pointer for example like this?</p>
```vtable for Derived:
  .word gs(Derived::foo())
```

That's what I would assume it to be from literature, but I'm not sure if literature is glancing over some specific detail. Each class has own vtable with pointer to their own methods or their base classes depending how they inherit/implement/override them. Then the vptr is in each instance of the classes point to their corresponding vtable. I would expect the vtable have just the pointer to that one and only method the classes, What are the zeros before it, what is exact structure of the vtable?

Title: Trying to understand the vtable content

Body:
I have this example code:

https://godbolt.org/z/reM8PY8r9

struct Base {
    Base() {}
    virtual void foo() = 0;
};

struct Derived: public Base {
    Derived(): Base() { }

    void foo() {
        return;
    }
};

Base* todolist[2] = { new Derived()};

void realtime() {
    for (int i=0; i<2; i++)
        todolist[i]->foo();
}

Which produces this AVR assembly:

__tmp_reg__ = 0
Derived::foo():
  ret
realtime():
  lds r26,todolist
  lds r27,todolist+1
  ld r30,X+
  ld r31,X
  sbiw r26,1
  ld __tmp_reg__,Z+
  ld r31,Z
  mov r30,__tmp_reg__
  ldi r24,hi8(gs(Derived::foo()))
  cpi r30,lo8(gs(Derived::foo()))
  cpc r31,r24
  brne .L9
.L4:
  lds r26,todolist+2
  lds r27,todolist+2+1
  ld r30,X+
  ld r31,X
  sbiw r26,1
  ld __tmp_reg__,Z+
  ld r31,Z
  mov r30,__tmp_reg__
  ldi r24,hi8(gs(Derived::foo()))
  cpi r30,lo8(gs(Derived::foo()))
  cpc r31,r24
  brne .L10
  ret
.L9:
  movw r24,r26
  icall
  rjmp .L4
.L10:
  movw r24,r26
  ijmp
_GLOBAL__sub_I_todolist:
  ldi r24,lo8(2)
  ldi r25,0
  rcall operator new(unsigned int)
  movw r30,r24
  ldi r24,lo8(vtable for Derived+4)
  ldi r25,hi8(vtable for Derived+4)
  std Z+1,r25
  st Z,r24
  sts todolist+1,r31
  sts todolist,r30
  ret
vtable for Derived:
  .word 0
  .word 0
  .word gs(Derived::foo())
todolist:
  .zero 4

What I'm trying to understand is the vtable:

vtable for Derived:
  .word 0
  .word 0
  .word gs(Derived::foo())

Why it's not just the foo pointer for example like this?

vtable for Derived:
  .word gs(Derived::foo())

That's what I would assume it to be from literature, but I'm not sure if literature is glancing over some specific detail. Each class has own vtable with pointer to their own methods or their base classes depending how they inherit/implement/override them. Then the vptr is in each instance of the classes point to their corresponding vtable. I would expect the vtable have just the pointer to that one and only method the classes, What are the zeros before it, what is exact structure of the vtable?


问:
How do i stack a ad widget on top?
currently i have image display but when i added the an ad on it , it pushes my image up.
i have tried to stack it but i keep getting red wavy line.

thanks in adavnce

```<code>Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: _isBottomBannerAdLoaded
          ? Container(
              height: _bottomBannerAd.size.height.toDouble(),
              width: _bottomBannerAd.size.width.toDouble(),
              child: AdWidget(ad: _bottomBannerAd),
            )
          : null,
      backgroundColor: Color.fromARGB(255, 247, 246, 246),
      body: Center(
        child: Container(
          height: 600,
          width: 600,
          color: Colors.black,
          child: GestureDetector(
            child: Center(
              child: Center(child: Image.asset(imagePath)),
            ),
</code>```

Title: How do i stack a ad widget on top?

Body:
currently i have image display but when i added the an ad on it , it pushes my image up.
i have tried to stack it but i keep getting red wavy line.

thanks in adavnce

Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: _isBottomBannerAdLoaded
          ? Container(
              height: _bottomBannerAd.size.height.toDouble(),
              width: _bottomBannerAd.size.width.toDouble(),
              child: AdWidget(ad: _bottomBannerAd),
            )
          : null,
      backgroundColor: Color.fromARGB(255, 247, 246, 246),
      body: Center(
        child: Container(
          height: 600,
          width: 600,
          color: Colors.black,
          child: GestureDetector(
            child: Center(
              child: Center(child: Image.asset(imagePath)),
            ),