问:
Why do I get a missing return statement error although there is a return statement in each of my if and if else blocks?
What I am trying to do here out of flower1 and flower2, one is even and one is odd then return true.
If both are even, return false.
If both are odd, return false.
When my code is:

```<code>public class OppositesAttract {

  public static boolean isLove(final int flower1, final int flower2) {

    if(flower1%2==0 && flower2%2==0){
      return false;
    }else
    if(flower1%2!=0 && flower2%2!=0){
      return false;
    } else
    if(flower1%2==0 || flower2%2==0){
      return true;
    }

  }

}
</code>```

I get a "missing return statement" error.
So I added:

```<code>public class OppositesAttract {

  public static boolean isLove(final int flower1, final int flower2) {

    if(flower1%2==0 && flower2%2==0){
      return false;
    }else
    if(flower1%2!=0 && flower2%2!=0){
      return false;
    } else
    if(flower1%2==0 || flower2%2==0){
      return true;
    }else{
      return true;
    }

  }

}
</code>```

Now, the code works but I do not understand why I have to add the additional return statement.

答:
The compiler doesn't know the first 3 terms cover all situations.

```<code>if(flower1%2==0 && flower2%2==0){
  return false;
} else if(flower1%2!=0 && flower2%2!=0){
  return false;
} else if(flower1%2==0 || flower2%2==0){
  return true;
}
</code>```

to you this reads as: all options are covered. but the compiler just sees:

```<code>if (somethingThatMayBeTrue) {

} else if (somethingElseThatMayBeTrue) {

} else if (aThirdThingThatMayBeTrue) {

} .... and what if none of them are?
</code>```

You may know that the last else if should always be true (since you know they are not both uneven) but the compiler doesn't generally try to understand your code.

in your case, the last clause (aThirdThingThatMayBeTrue, flower1%2==0 || flower2%2==0) is actually (somethingThatIsAlwaysTrueIfPreviousTermsAreFalse).

so you can treat it as such:

```<code>if(flower1%2==0 && flower2%2==0){
  return false;
} else if(flower1%2!=0 && flower2%2!=0){
  return false;
} else {
  return true;
}
</code>```

Body:
What I am trying to do here out of flower1 and flower2, one is even and one is odd then return true.
If both are even, return false.
If both are odd, return false.
When my code is:

public class OppositesAttract {

  public static boolean isLove(final int flower1, final int flower2) {

    if(flower1%2==0 && flower2%2==0){
      return false;
    }else
    if(flower1%2!=0 && flower2%2!=0){
      return false;
    } else
    if(flower1%2==0 || flower2%2==0){
      return true;
    }

  }

}

I get a "missing return statement" error.
So I added:

public class OppositesAttract {

  public static boolean isLove(final int flower1, final int flower2) {

    if(flower1%2==0 && flower2%2==0){
      return false;
    }else
    if(flower1%2!=0 && flower2%2!=0){
      return false;
    } else
    if(flower1%2==0 || flower2%2==0){
      return true;
    }else{
      return true;
    }

  }

}

Now, the code works but I do not understand why I have to add the additional return statement.

Body:
The compiler doesn't know the first 3 terms cover all situations.

if(flower1%2==0 && flower2%2==0){
  return false;
} else if(flower1%2!=0 && flower2%2!=0){
  return false;
} else if(flower1%2==0 || flower2%2==0){
  return true;
}

to you this reads as: all options are covered. but the compiler just sees:

if (somethingThatMayBeTrue) {

} else if (somethingElseThatMayBeTrue) {

} else if (aThirdThingThatMayBeTrue) {

} .... and what if none of them are?

You may know that the last else if should always be true (since you know they are not both uneven) but the compiler doesn't generally try to understand your code.

in your case, the last clause (aThirdThingThatMayBeTrue, flower1%2==0 || flower2%2==0) is actually (somethingThatIsAlwaysTrueIfPreviousTermsAreFalse).

so you can treat it as such:

if(flower1%2==0 && flower2%2==0){
  return false;
} else if(flower1%2!=0 && flower2%2!=0){
  return false;
} else {
  return true;
}


来源: stackexchange

问:
How can I get multiple input for optional phone number dynamically (DOM)?
Here is my code. I want to add more phone number as optional phone. How can I do it dinamically?

```<code>          <div class="col-12 row border my-2 py-2">
                <div class="col-6 form-group">
                    <label class="control-label " for="official_phone"><h5 class="h6">Phone (Official) *</h5></label>
                    <input class="form-control" type="text" name="official_phone" placeholder="Input Phone Number.." required/>
                </div>
                <div class="col-6 form-group">
                    <label class="control-label " for="optional_phone"><h5 class="h6">Phone (Others) </h5></label>
                    <input class="form-control" type="text" name="optional_phone" placeholder="Input Phone Number.."/>
                </div>

            </div>
</code>```

答:
Just make a button that triggers the input div into the parent form.

let count = 1;
function addphone(){
    const parent = document.getElementById("phone-list");
    let el = document.createElement("div");
    el.setAttribute("class","col-6 form-group");
    el.innerHTML = `
Phone (Optional) *
<input class="form-control" type="text" name="optional_phone_${count}" placeholder="Input Phone Number.." required/>`;
    parent.appendChild(el);
  count++;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <head></head>
<body>
  <div class="col-12 row border my-2 py-2">
    <div id="phone-list">
      <div class="col-6 form-group">
        <label class="control-label " for="official_phone"><h5 class="h6">Phone (Official) *</h5></label>
        <input class="form-control" type="text" name="official_phone" placeholder="Input Phone Number.." required/>
      </div>
      <div class="col-6 form-group">
        <label class="control-label " for="optional_phone"><h5 class="h6">Phone (Others)</h5></label>
        <input class="form-control" type="text" name="optional_phone" placeholder="Input Phone Number.."/>
      </div>
    </div>
    <button type="button" onclick="addphone()">Add Phone</button>
  </div>
</body>
</html></code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is my code. I want to add more phone number as optional phone. How can I do it dinamically?

Phone (Official) *

                    <input class="form-control" type="text" name="official_phone" placeholder="Input Phone Number.." required/>

Phone (Others)

                    <input class="form-control" type="text" name="optional_phone" placeholder="Input Phone Number.."/>

Body:
Just make a button that triggers the input div into the parent form.

let count = 1;
function addphone(){
    const parent = document.getElementById("phone-list");
    let el = document.createElement("div");
    el.setAttribute("class","col-6 form-group");
    el.innerHTML = `<label class="control-label " for="optional_phone_${count}"><h5 class="h6">Phone (Optional) *</h5></label><input class="form-control" type="text" name="optional_phone_${count}" placeholder="Input Phone Number.." required/>`;
    parent.appendChild(el);
  count++;
}

<html>
  <head></head>
<body>
  <div class="col-12 row border my-2 py-2">
    <div id="phone-list">
      <div class="col-6 form-group">
        <label class="control-label " for="official_phone"><h5 class="h6">Phone (Official) *</h5></label>
        <input class="form-control" type="text" name="official_phone" placeholder="Input Phone Number.." required/>
      </div>
      <div class="col-6 form-group">
        <label class="control-label " for="optional_phone"><h5 class="h6">Phone (Others)</h5></label>
        <input class="form-control" type="text" name="optional_phone" placeholder="Input Phone Number.."/>
      </div>
    </div>
    <button type="button" onclick="addphone()">Add Phone</button>
  </div>
</body>
</html>


问:
AD Authentication (System Assigned Managed Identity) with Azure SQL Managed Instance not working?
I am trying to connect to the Azure SQL Database from App Service Spring boot application with System managed identity. I am trying to connect to the database using ActiveDirectoryMSI and MSIClientId. In my database I have the connection string for SQL Authentication, AD Password Authentication, AD Integrated Authentication. App service MI is added as a user to the database with roles as dbreader and dbwriter. While deploying the application I am getting the error as

com.microsoft.sqlserver.jdbc.SQLServerException: Cannot set AccessToken property if "Authentication" has been specified in the connection string.

I am trying to get the token for my database here.

Can someone help how can I resolve this?

答:
accessToken can only be set using the Properties parameter of the
getConnection() method in the DriverManager class. It can't be used in
the connection string.

Based on the error it is telling you that you specified "AccessToken" property in part of your Connection String, but the documentation specifically tells you to not do that.

https://learn.microsoft.com/en-us/sql/connect/jdbc/connecting-using-azure-active-directory-authentication?view=sql-server-ver15

accessToken:

Use this connection property to connect to a SQL Database with access
token. accessToken can only be set using the Properties parameter of
the getConnection() method in the DriverManager class. It can't be
used in the connection URL.

Example:

```<code>public class AADTokenBased {

    public static void main(String[] args) throws Exception {

        // Retrieve the access token from the AD.
        String spn = "https://database.windows.net/";
        String stsurl = "https://login.microsoftonline.com/..."; // Replace with your STS URL.
        String clientId = "1846943b-ad04-4808-aa13-4702d908b5c1"; // Replace with your client ID.
        String clientSecret = "..."; // Replace with your client secret.

        String scope = spn +  "/.default";
        Set<String> scopes = new HashSet<>();
        scopes.add(scope);

        ExecutorService executorService = Executors.newSingleThreadExecutor();
        IClientCredential credential = ClientCredentialFactory.createFromSecret(clientSecret);
        ConfidentialClientApplication clientApplication = ConfidentialClientApplication
            .builder(clientId, credential).executorService(executorService).authority(stsurl).build();
        CompletableFuture<IAuthenticationResult> future = clientApplication
            .acquireToken(ClientCredentialParameters.builder(scopes).build());

        IAuthenticationResult authenticationResult = future.get();
        String accessToken = authenticationResult.accessToken();

        System.out.println("Access Token: " + accessToken);

        // Connect with the access token.
        SQLServerDataSource ds = new SQLServerDataSource();

        ds.setServerName("aad-managed-demo.database.windows.net"); // Replace with your server name.
        ds.setDatabaseName("demo"); // Replace with your database name.
        ds.setAccessToken(accessToken);

        try (Connection connection = ds.getConnection();
                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT SUSER_SNAME()")) {
            if (rs.next()) {
                System.out.println("You have successfully logged on as: " + rs.getString(1));
            }
        }
    }
}
</code>```

Body:
accessToken can only be set using the Properties parameter of the
getConnection() method in the DriverManager class. It can't be used in
the connection string.

Based on the error it is telling you that you specified "AccessToken" property in part of your Connection String, but the documentation specifically tells you to not do that.

https://learn.microsoft.com/en-us/sql/connect/jdbc/connecting-using-azure-active-directory-authentication?view=sql-server-ver15

accessToken:

Use this connection property to connect to a SQL Database with access
token. accessToken can only be set using the Properties parameter of
the getConnection() method in the DriverManager class. It can't be
used in the connection URL.

Example:

public class AADTokenBased {

    public static void main(String[] args) throws Exception {

        // Retrieve the access token from the AD.
        String spn = "https://database.windows.net/";
        String stsurl = "https://login.microsoftonline.com/..."; // Replace with your STS URL.
        String clientId = "1846943b-ad04-4808-aa13-4702d908b5c1"; // Replace with your client ID.
        String clientSecret = "..."; // Replace with your client secret.

        String scope = spn +  "/.default";
        Set<String> scopes = new HashSet<>();
        scopes.add(scope);

        ExecutorService executorService = Executors.newSingleThreadExecutor();
        IClientCredential credential = ClientCredentialFactory.createFromSecret(clientSecret);
        ConfidentialClientApplication clientApplication = ConfidentialClientApplication
            .builder(clientId, credential).executorService(executorService).authority(stsurl).build();
        CompletableFuture<IAuthenticationResult> future = clientApplication
            .acquireToken(ClientCredentialParameters.builder(scopes).build());

        IAuthenticationResult authenticationResult = future.get();
        String accessToken = authenticationResult.accessToken();

        System.out.println("Access Token: " + accessToken);

        // Connect with the access token.
        SQLServerDataSource ds = new SQLServerDataSource();

        ds.setServerName("aad-managed-demo.database.windows.net"); // Replace with your server name.
        ds.setDatabaseName("demo"); // Replace with your database name.
        ds.setAccessToken(accessToken);

        try (Connection connection = ds.getConnection();
                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT SUSER_SNAME()")) {
            if (rs.next()) {
                System.out.println("You have successfully logged on as: " + rs.getString(1));
            }
        }
    }
}


问:
dynamically populate data in dropdown using javascript api using axois
it is a dropdown with top and other in the world

the cities and data will be dynamically populated in dropdown using javascript API using Axios

With external Apis.

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">

<select class="form-select" aria-label="Default select example">
    <option selected>Open this select menu</option>
    <option value="1">---Top Cities---</option>
    <option value="2">Mumbai</option>
    <option value="3">Delhi</option>
    <option value="1">Bengaluru</option>
    <option value="2">Chennai</option>
    <option value="3">Kolkata</option>
    <option value="2">---Other Cities---</option>
    <option value="3">Bhavnagar</option>
    <option value="3">Udaipur</option>
    <option value="3">Pune</option>
</select>```
</div>
</div>
</p>
```[
  { "id": "1", "name": "Mumbai", "state": "Maharashtra" },
  { "id": "2", "name": "Delhi", "state": "Delhi" },
  { "id": "3", "name": "Bengaluru", "state": "Karnataka" },
  { "id": "4", "name": "Ahmedabad", "state": "Gujarat" },
  { "id": "5", "name": "Hyderabad", "state": "Telangana" },
  { "id": "6", "name": "Chennai", "state": "Tamil Nadu" },
  { "id": "7", "name": "Kolkata", "state": "West Bengal" }
]
```

答:
```<code>let options = [
  { "id": "1", "name": "Mumbai", "state": "Maharashtra" },
  { "id": "2", "name": "Delhi", "state": "Delhi" },
  { "id": "3", "name": "Bengaluru", "state": "Karnataka" },
  { "id": "4", "name": "Ahmedabad", "state": "Gujarat" },
  { "id": "5", "name": "Hyderabad", "state": "Telangana" },
  { "id": "6", "name": "Chennai", "state": "Tamil Nadu" },
  { "id": "7", "name": "Kolkata", "state": "West Bengal" }
]

const select = document.querySelector(".form-select");
options.map(val=>{
let opt = document.createElement("option");
  opt.innerText = val.name
 select.appendChild(opt);
})
</code>```

Just add this in your javascript file .

Body:
it is a dropdown with top and other in the world

the cities and data will be dynamically populated in dropdown using javascript API using Axios

With external Apis.

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">

<select class="form-select" aria-label="Default select example">
    <option selected>Open this select menu</option>
    <option value="1">---Top Cities---</option>
    <option value="2">Mumbai</option>
    <option value="3">Delhi</option>
    <option value="1">Bengaluru</option>
    <option value="2">Chennai</option>
    <option value="3">Kolkata</option>
    <option value="2">---Other Cities---</option>
    <option value="3">Bhavnagar</option>
    <option value="3">Udaipur</option>
    <option value="3">Pune</option>
</select>

[
  { "id": "1", "name": "Mumbai", "state": "Maharashtra" },
  { "id": "2", "name": "Delhi", "state": "Delhi" },
  { "id": "3", "name": "Bengaluru", "state": "Karnataka" },
  { "id": "4", "name": "Ahmedabad", "state": "Gujarat" },
  { "id": "5", "name": "Hyderabad", "state": "Telangana" },
  { "id": "6", "name": "Chennai", "state": "Tamil Nadu" },
  { "id": "7", "name": "Kolkata", "state": "West Bengal" }
]

Body:
let options = [
  { "id": "1", "name": "Mumbai", "state": "Maharashtra" },
  { "id": "2", "name": "Delhi", "state": "Delhi" },
  { "id": "3", "name": "Bengaluru", "state": "Karnataka" },
  { "id": "4", "name": "Ahmedabad", "state": "Gujarat" },
  { "id": "5", "name": "Hyderabad", "state": "Telangana" },
  { "id": "6", "name": "Chennai", "state": "Tamil Nadu" },
  { "id": "7", "name": "Kolkata", "state": "West Bengal" }
]

const select = document.querySelector(".form-select");
options.map(val=>{
let opt = document.createElement("option");
  opt.innerText = val.name
 select.appendChild(opt);
})

Just add this in your javascript file .


问:
What is the proper way to do a foreach loop with an Array/Map in dart?
I'm trying to convert a piece of PHP code to dart and getting stuck.
What I have is a PHP array text that gets run through a function called toUTF8 as follows:

```<code>if(is_array($text))
{
  foreach($text as $k => $v)
    {
    text[$k] = self::toUTF8($v);
    }
  return $text;
}
</code>```

Conceptually, what I've done in dart is turn text into a Map

```<code>if(text is Map)
{
  foreach(text as k => v)
    {
    text[k] = toUTF8(v);
    }
  return text;
}
</code>```

But I cannot wrap my mind around, how I would walk the map and run each element into the toUTF8 function.

Essentially, the question is how to do a foreach on a map?

For bonus points, would treating it as a List is a better approach?  What this code is ultimately doing is handling malformed UTF8 characters

答:
I'd probably keep it as an array. I don't see any good reason for using a map.

What are the contents of the text array? Is it strings or UTF-8 bytes? Is it individual string characters, or longer strings?
Since you call something called toUTF8, I'm assuming it's strings, and you want to convert them to UTF-8.
I'm not sure how the code "handles" malformed UTF-8 sequences, since it appears to convert to UTF-8.

You are doing that on a chunk-by-chunk basis, but that's not necessarily correct, if the text array represents a single large text chopped into pieces. Dart strings are sequences of UTF-16 code units, and a surrogate pair  can be split between separate chunks, but must be converted together.

I'd do something like:

var bytes = Stream.fromIterable(text).transform(utf8.encoder);
// do something with `bytes`.
```
<p>or, if you want manual control:</p>
<pre class="lang-dart prettyprint-override"><code>import "dart:convert";
import "dart:typed_data";
// ...
  var buffer = BytesBuilder();
  var converter = utf8.encoder.startChunkedEncoding(
      ByteConversionSink.withCallback(buffer.add));
  text.forEach(converter.add);
  converter.close();
  var bytes = buffer.takeBytes(); // UTF-8 converted `text`.
</code>```

Body:
I'm trying to convert a piece of PHP code to dart and getting stuck.
What I have is a PHP array text that gets run through a function called toUTF8 as follows:

if(is_array($text))
{
  foreach($text as $k => $v)
    {
    text[$k] = self::toUTF8($v);
    }
  return $text;
}

Conceptually, what I've done in dart is turn text into a Map

if(text is Map)
{
  foreach(text as k => v)
    {
    text[k] = toUTF8(v);
    }
  return text;
}

But I cannot wrap my mind around, how I would walk the map and run each element into the toUTF8 function.

Essentially, the question is how to do a foreach on a map?

For bonus points, would treating it as a List is a better approach?  What this code is ultimately doing is handling malformed UTF8 characters

Body:
I'd probably keep it as an array. I don't see any good reason for using a map.

What are the contents of the text array? Is it strings or UTF-8 bytes? Is it individual string characters, or longer strings?
Since you call something called toUTF8, I'm assuming it's strings, and you want to convert them to UTF-8.
I'm not sure how the code "handles" malformed UTF-8 sequences, since it appears to convert to UTF-8.

You are doing that on a chunk-by-chunk basis, but that's not necessarily correct, if the text array represents a single large text chopped into pieces. Dart strings are sequences of UTF-16 code units, and a surrogate pair  can be split between separate chunks, but must be converted together.

I'd do something like:

var bytes = Stream.fromIterable(text).transform(utf8.encoder);
// do something with `bytes`.

or, if you want manual control:

import "dart:convert";
import "dart:typed_data";
// ...
  var buffer = BytesBuilder();
  var converter = utf8.encoder.startChunkedEncoding(
      ByteConversionSink.withCallback(buffer.add));
  text.forEach(converter.add);
  converter.close();
  var bytes = buffer.takeBytes(); // UTF-8 converted `text`.


问:
Finding the maximum product of a path in binary tree
I need some help to come up with an algorithm to calculate maximum product of the values along any path from leaf to root of a binary tree. So far I have:

```<code>int max_path_prod_rec(Tree* t, int max_so_far, int path_prod) {
    if (is_leaf(t))
        return t->value;

    int left = max_path_prod_rec(t->left, max_so_far, path_prod);
    int right = max_path_prod_rec(t->right, max_so_far, path_prod);

    if (left > right)
        return left * t->value;
    else
        return right * t->value;
}

int max_path_prod(Tree* t) {
    require("path product only defined for non-empty trees", t != NULL);
    return max_path_prod_rec(t, INT_MIN, 1);
}
</code>```

The problem is this function doesn't work when there are 2 negative numbers in a row, like 10 * (-3) * (-6). How can I improve upon this?

Edit: examples:

```<code>    //   10
    //  2   5
    // 1 -3 4 -6
    t = node(node(leaf(1), 2, leaf(-3)), 10, node(leaf(4), 5, leaf(-6)));
    printf("%i\n", max_path_prod(t));
</code>```

Will return 10 * 5 * 4 == 200. But

```<code>    //   10
    //  2   -5
    // 1 -3 4 -6
    t = node(node(leaf(1), 2, leaf(-3)), 10, node(leaf(4), -5, leaf(-6)));
    printf("%i\n", max_path_prod(t));
</code>```

Returns 10 * 2 * 1 == 20 instead of 10 * (-5) * (-6) == 300

答:
In my opinion, you should write a simpler routine (there's no need to pass down anything to the subtrees, as we are building the product from the leaves to the root)

```<code>int max_path_prod_rec(Tree* t)
{
    if (t == NULL) return 1;
    int left  = max_path_prod_rec(t->left);
    int right = max_path_prod_rec(t->right);
    return (left > right ? left : right) * t->value;
}
</code>```

In your code:

```<code>int max_path_prod_rec(Tree* t, int max_so_far, int path_prod) {
    if (is_leaf(t)) /* you should have posted this function */
        return t->value;
</code>```

Until here you are correct (assuming you will never pass a NULL reference to the t parameter)...

```<code>
    int left  = max_path_prod_rec(t->left,  max_so_far, path_prod);
    int right = max_path_prod_rec(t->right, max_so_far, path_prod);
</code>```

but here you are assuming that the node, if it's not a leaf node, will have both children attached, and that can be not the case!  You should do those, checking if the children do exist only.

```<code>
    if (left > right)
        return left  * t->value;
    else
        return right * t->value;
}
</code>```

In case you have done:

```<code>int max_path_prod_rec(Tree* t, int max_so_far, int path_prod) {
    if (t == NULL)
        return 1; /* you add always an extra factor of 1, don't hurt */

    int left  = max_path_prod_rec(t->left,  max_so_far, path_prod);
    int right = max_path_prod_rec(t->right, max_so_far, path_prod);

    if (left > right)
        return left * t->value;
    else
        return right * t->value;
}
</code>```

then your code would be protected, and your code would result (for a leaf node) with both children being 1, and the returned value being t->value * 1 * 1 ==> t->value

If you want to compare absolute values, just do:

```<code>int max_path_prod_rec(Tree* t)
{
    if (t == NULL) return 1;
    int left  = t->value * max_path_prod_rec(t->left);
    int right = t->value * max_path_prod_rec(t->right);
    return abs(left) > abs(right)
              ? left
              : right;
}
</code>```

Body:
I need some help to come up with an algorithm to calculate maximum product of the values along any path from leaf to root of a binary tree. So far I have:

int max_path_prod_rec(Tree* t, int max_so_far, int path_prod) {
    if (is_leaf(t))
        return t->value;

    int left = max_path_prod_rec(t->left, max_so_far, path_prod);
    int right = max_path_prod_rec(t->right, max_so_far, path_prod);

    if (left > right)
        return left * t->value;
    else
        return right * t->value;
}

int max_path_prod(Tree* t) {
    require("path product only defined for non-empty trees", t != NULL);
    return max_path_prod_rec(t, INT_MIN, 1);
}

The problem is this function doesn't work when there are 2 negative numbers in a row, like 10 * (-3) * (-6). How can I improve upon this?

Edit: examples:

    //   10
    //  2   5
    // 1 -3 4 -6
    t = node(node(leaf(1), 2, leaf(-3)), 10, node(leaf(4), 5, leaf(-6)));
    printf("%i\n", max_path_prod(t));

Will return 10 * 5 * 4 == 200. But

    //   10
    //  2   -5
    // 1 -3 4 -6
    t = node(node(leaf(1), 2, leaf(-3)), 10, node(leaf(4), -5, leaf(-6)));
    printf("%i\n", max_path_prod(t));

Returns 10 * 2 * 1 == 20 instead of 10 * (-5) * (-6) == 300

Body:
In my opinion, you should write a simpler routine (there's no need to pass down anything to the subtrees, as we are building the product from the leaves to the root)

int max_path_prod_rec(Tree* t)
{
    if (t == NULL) return 1;
    int left  = max_path_prod_rec(t->left);
    int right = max_path_prod_rec(t->right);
    return (left > right ? left : right) * t->value;
}

In your code:

int max_path_prod_rec(Tree* t, int max_so_far, int path_prod) {
    if (is_leaf(t)) /* you should have posted this function */
        return t->value;

Until here you are correct (assuming you will never pass a NULL reference to the t parameter)...

    int left  = max_path_prod_rec(t->left,  max_so_far, path_prod);
    int right = max_path_prod_rec(t->right, max_so_far, path_prod);

but here you are assuming that the node, if it's not a leaf node, will have both children attached, and that can be not the case!  You should do those, checking if the children do exist only.

    if (left > right)
        return left  * t->value;
    else
        return right * t->value;
}

In case you have done:

int max_path_prod_rec(Tree* t, int max_so_far, int path_prod) {
    if (t == NULL)
        return 1; /* you add always an extra factor of 1, don't hurt */

    int left  = max_path_prod_rec(t->left,  max_so_far, path_prod);
    int right = max_path_prod_rec(t->right, max_so_far, path_prod);

    if (left > right)
        return left * t->value;
    else
        return right * t->value;
}

then your code would be protected, and your code would result (for a leaf node) with both children being 1, and the returned value being t->value * 1 * 1 ==> t->value

If you want to compare absolute values, just do:

int max_path_prod_rec(Tree* t)
{
    if (t == NULL) return 1;
    int left  = t->value * max_path_prod_rec(t->left);
    int right = t->value * max_path_prod_rec(t->right);
    return abs(left) > abs(right)
              ? left
              : right;
}


问:
How to customize object equality for JavaScript Set
New ES 6 (Harmony) introduces new Set object. Identity algorithm used by Set is similar to === operator and so not much suitable for comparing objects:

var set = new Set();
set.add({a:1});
set.add({a:1});
console.log([...set.values()]); // Array [ Object, Object ]
```

How to customize equality for Set objects in order to do deep object comparison? Is there anything like Java equals(Object)?

答:
A good stringification method for the special but frequent case of a TypedArray as Set/Map key is using

```<code>const key = String.fromCharCode(...new Uint16Array(myArray.buffer));
</code>```

It generates the shortest possible unique string that can be easily converted back. However this is not always a valid UTF-16 string for display concerning Low and High Surrogates. Set and Map seem to ignore surrogate validity.
As measured in Firefox and Chrome, the spread operator performs slowly. If your myArray has fixed size, it executes faster when you write:

```<code>const a = new Uint16Array(myArray.buffer);  // here: myArray = Uint32Array(2) = 8 bytes
const key = String.fromCharCode(a[0],a[1],a[2],a[3]);  // 8 bytes too
</code>```

Probably the most valuable advantage of this method of key-building: It works for Float32Array and Float64Array without any rounding side-effect. Note that +0 and -0 are then different. Infinities are same. Silent NaNs are same. Signaling NaNs are different depending on their signal (never seen in vanilla JavaScript).

ContentLicense: CC BY-SA 3.0

Body:
New ES 6 (Harmony) introduces new Set object. Identity algorithm used by Set is similar to === operator and so not much suitable for comparing objects:

var set = new Set();
set.add({a:1});
set.add({a:1});
console.log([...set.values()]); // Array [ Object, Object ]

How to customize equality for Set objects in order to do deep object comparison? Is there anything like Java equals(Object)?

Body:
A good stringification method for the special but frequent case of a TypedArray as Set/Map key is using

const key = String.fromCharCode(...new Uint16Array(myArray.buffer));

It generates the shortest possible unique string that can be easily converted back. However this is not always a valid UTF-16 string for display concerning Low and High Surrogates. Set and Map seem to ignore surrogate validity.
As measured in Firefox and Chrome, the spread operator performs slowly. If your myArray has fixed size, it executes faster when you write:

const a = new Uint16Array(myArray.buffer);  // here: myArray = Uint32Array(2) = 8 bytes
const key = String.fromCharCode(a[0],a[1],a[2],a[3]);  // 8 bytes too

Probably the most valuable advantage of this method of key-building: It works for Float32Array and Float64Array without any rounding side-effect. Note that +0 and -0 are then different. Infinities are same. Silent NaNs are same. Signaling NaNs are different depending on their signal (never seen in vanilla JavaScript).


问:
How this code is failing to give me an accurate answer?
this is my code which is working fine but it is not correct. I am unable to figure out the problem</p>
```<code>class MathUtils:

    @staticmethod
    def average(a, b):
        return a + b / 2

print(MathUtils.average(2, 1))

</code>```

答:
you made a tiny mistake - what your code actually does is taking b, dividing it by 2 and then add the result to a. so you get 2 + 0.5 = 2.5

you need to put parentheses around a + b:

class MathUtils:

```<code>@staticmethod
def average(a, b):
    return (a + b) / 2
</code>```

print(MathUtils.average(2, 1))

Body:
this is my code which is working fine but it is not correct. I am unable to figure out the problem

class MathUtils:

    @staticmethod
    def average(a, b):
        return a + b / 2

print(MathUtils.average(2, 1))

Body:
you made a tiny mistake - what your code actually does is taking b, dividing it by 2 and then add the result to a. so you get 2 + 0.5 = 2.5

you need to put parentheses around a + b:

class MathUtils:

@staticmethod
def average(a, b):
    return (a + b) / 2

print(MathUtils.average(2, 1))


答:
Create "OPTION" element

Set its value using setAttribute

Update that to the select element

const topCities = [
  { "id": "1", "name": "Mumbai", "state": "Maharashtra" },
  { "id": "2", "name": "Delhi", "state": "Delhi" },
  { "id": "3", "name": "Bengaluru", "state": "Karnataka" },
  { "id": "4", "name": "Ahmedabad", "state": "Gujarat" },
  { "id": "5", "name": "Hyderabad", "state": "Telangana" },
  { "id": "6", "name": "Chennai", "state": "Tamil Nadu" },
  { "id": "7", "name": "Kolkata", "state": "West Bengal" }
]
const otherCities = [
  { "id": "1", "name": "Bhavnagar", "state": "Bhavnagar" },
  { "id": "2", "name": "Udaipur", "state": "Udaipur" },
  { "id": "3", "name": "Pune", "state": "Pune" },
];

const select = document.querySelector('select');

function addOption(label, value) {
  const option = document.createElement("OPTION");
  option.setAttribute('value', value);
  const text = document.createTextNode(label);
  option.appendChild(text);
  select.appendChild(option);
}

addOption("---Top Cities---", "1");

topCities.forEach((city) => {
  addOption(city.name, city.id);
});

addOption("---Other Cities---", "2");

otherCities.forEach((city) => {
  addOption(city.name, city.id);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<select class="form-select" aria-label="Default select example">
  <option selected>Open this select menu</option>
</select></code>```

Title: dynamically populate data in dropdown using javascript api using axois

Body:
Create "OPTION" element

Set its value using setAttribute

Update that to the select element

const topCities = [
  { "id": "1", "name": "Mumbai", "state": "Maharashtra" },
  { "id": "2", "name": "Delhi", "state": "Delhi" },
  { "id": "3", "name": "Bengaluru", "state": "Karnataka" },
  { "id": "4", "name": "Ahmedabad", "state": "Gujarat" },
  { "id": "5", "name": "Hyderabad", "state": "Telangana" },
  { "id": "6", "name": "Chennai", "state": "Tamil Nadu" },
  { "id": "7", "name": "Kolkata", "state": "West Bengal" }
]
const otherCities = [
  { "id": "1", "name": "Bhavnagar", "state": "Bhavnagar" },
  { "id": "2", "name": "Udaipur", "state": "Udaipur" },
  { "id": "3", "name": "Pune", "state": "Pune" },
];

const select = document.querySelector('select');

function addOption(label, value) {
  const option = document.createElement("OPTION");
  option.setAttribute('value', value);
  const text = document.createTextNode(label);
  option.appendChild(text);
  select.appendChild(option);
}

addOption("---Top Cities---", "1");

topCities.forEach((city) => {
  addOption(city.name, city.id);
});

addOption("---Other Cities---", "2");

otherCities.forEach((city) => {
  addOption(city.name, city.id);
});

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<select class="form-select" aria-label="Default select example">
  <option selected>Open this select menu</option>
</select>


问:
React Component with JSON Image path
I have a react component that is pulling in some data from a local json file. That data has some links to images. However the images aren't loading even though the paths are correct. I was using require before but in a different code setup. Now that I've transitioned it to this the images won't load. i'm using webpack 4 so i'm guessing i need to require the images again? How do i do that in the below statement ?

the part that is failing is the 'image={release.imageURL}' which is being passed to the 'src' of the component

```<code>import React from "react";
import ReactDOM from "react-dom";
import Release from "./release.js"
import data from "../data/releases.json"

const allReleases = data.map(release => {
  return (
    <div className="column-2">
    <Release
    key={release.id}
    url={release.releaseURL}
    image={release.imageURL}
    cta={release.cta}
    title={release.title}
    artists={release.artists}
    />
    </div>
  )
})

const Releases = () => {

  return (
    <div>
    <div className="row">
      <h3>All Releases</h3>
        {allReleases}
    </div>
    </div>
  )
}
</code>```

export default Releases;

答:
Bro, I was working on this problem and eventually figure it out:

1- All you have to do is changing the path of the image from your JSON file. That means the path should be related to your react component (allReleases).

2- Next thing, instead of using

*

```<code><Release
    key={release.id}
    url={release.releaseURL}
    image={release.imageURL}  // ==> WRONG
    cta={release.cta}
    title={release.title}
    artists={release.artists}
/>
</code>```

Just go with:

*

```<code><Release
    key={release.id}
    url={release.releaseURL}
    image={`${release.imageURL}`} // ===> CORRECT
    cta={release.cta}
    title={release.title}
    artists={release.artists}
/>
</code>```

Title: React Component with JSON Image path

Body:
I have a react component that is pulling in some data from a local json file. That data has some links to images. However the images aren't loading even though the paths are correct. I was using require before but in a different code setup. Now that I've transitioned it to this the images won't load. i'm using webpack 4 so i'm guessing i need to require the images again? How do i do that in the below statement ?

the part that is failing is the 'image={release.imageURL}' which is being passed to the 'src' of the component

import React from "react";
import ReactDOM from "react-dom";
import Release from "./release.js"
import data from "../data/releases.json"

const allReleases = data.map(release => {
  return (

    <Release
    key={release.id}
    url={release.releaseURL}
    image={release.imageURL}
    cta={release.cta}
    title={release.title}
    artists={release.artists}
    />

  )
})

const Releases = () => {

  return (

All Releases

        {allReleases}

  )
}

export default Releases;

Body:
Bro, I was working on this problem and eventually figure it out:

1- All you have to do is changing the path of the image from your JSON file. That means the path should be related to your react component (allReleases).

2- Next thing, instead of using

*

<Release
    key={release.id}
    url={release.releaseURL}
    image={release.imageURL}  // ==> WRONG
    cta={release.cta}
    title={release.title}
    artists={release.artists}
/>

Just go with:

*

<Release
    key={release.id}
    url={release.releaseURL}
    image={`${release.imageURL}`} // ===> CORRECT
    cta={release.cta}
    title={release.title}
    artists={release.artists}
/>


问:
How to Pass Id correctly to Rest API Endpoint from React
I'm trying to fetch data through endpoint from Django Rest Framework
endpoint is :

```<code>/api/v1/categories/nested/{id}/
</code>```

Problem is when I'm requesting with id, Django server show this error :

```<code>ValueError: Field 'id' expected a number but got 'undefined'.
[07/Feb/2022 15:53:01] "GET /api/v1/categories/nested/undefined/ HTTP/1.1" 500 162581
</code>```

As this suggest I'm unable to Pass id correctly,
So need littl help to fix that
I'm using actions > reducer > store > component approach using react redux
action.js

```<code>export const listCategoryDetails = (id) => async (dispatch) => {
    try {
      dispatch({ type: CATEGORY_DETAIL_REQUEST });

      const { data } = await axios.get(`/api/v1/categories/nested/${id}`); // Purpose to show nested brands[]

      dispatch({
        type: CATEGORY_DETAIL_SUCCESS,
        payload: data,
      });
    } catch (error) {
      dispatch({
        type: CATEGORY_DETAIL_FAIL,
        payload:
          error.response && error.response.data.detail
            ? error.response.data.detail
            : error.message,
      });
    }
  };
</code>```

reducer.js

```<code>export const categoryDetailsReducer = (
    state = { category: {  } },
    action
  ) => {
    switch (action.type) {
      case CATEGORY_DETAIL_REQUEST:
        return { loading: true, ...state };

      case CATEGORY_DETAIL_SUCCESS:
        return { loading: false, category: action.payload };

      case CATEGORY_DETAIL_FAIL:
        return { loading: false, error: action.payload };

      default:
        return state;
    }
  };
</code>```

store.js

```<code>const reducer = combineReducers({
  categoryDetail: categoryDetailsReducer,
});
</code>```

component

```<code>function CategoryDetail({ match, history }) {
    // const { id } = useParams();
    // console.log(id);
    const dispatch = useDispatch();
    const categoryList = useSelector((state) => state.categoryList);
    const { loading, error, categories , page, pages} = categoryList;

    useEffect(() => {

        dispatch(listCategoryDetails());
    }, [dispatch, match]);

  return <div>

                {categories.map(category => (
                <Col key={category.id} sm={12} md={8} lg={4} xl={3} >

                    <h1><strong>{category.title}</strong></h1>))}

</div>;
}

export default CategoryDetail;
</code>```

答:
Before

```<code>// const { id } = useParams();
// console.log(id);
const dispatch = useDispatch();
const categoryList = useSelector((state) => state.categoryList);
const { loading, error, categories , page, pages} = categoryList;

useEffect(() => {

    dispatch(listCategoryDetails());
}, [dispatch, match]);
</code>```

After

```<code>const { id } = useParams();
console.log(id);
const dispatch = useDispatch();
const categoryList = useSelector((state) => state.categoryList);
const { loading, error, categories , page, pages} = categoryList;

useEffect(() => {

    dispatch(listCategoryDetails(id));
}, [dispatch, match]);
</code>```

Inside UseEffect You Are Not Passing id Variable So its Saying Id Is Undefined

Body:
I'm trying to fetch data through endpoint from Django Rest Framework
endpoint is :

/api/v1/categories/nested/{id}/

Problem is when I'm requesting with id, Django server show this error :

ValueError: Field 'id' expected a number but got 'undefined'.
[07/Feb/2022 15:53:01] "GET /api/v1/categories/nested/undefined/ HTTP/1.1" 500 162581

As this suggest I'm unable to Pass id correctly,
So need littl help to fix that
I'm using actions > reducer > store > component approach using react redux
action.js

export const listCategoryDetails = (id) => async (dispatch) => {
    try {
      dispatch({ type: CATEGORY_DETAIL_REQUEST });

      const { data } = await axios.get(`/api/v1/categories/nested/${id}`); // Purpose to show nested brands[]

      dispatch({
        type: CATEGORY_DETAIL_SUCCESS,
        payload: data,
      });
    } catch (error) {
      dispatch({
        type: CATEGORY_DETAIL_FAIL,
        payload:
          error.response && error.response.data.detail
            ? error.response.data.detail
            : error.message,
      });
    }
  };

reducer.js

export const categoryDetailsReducer = (
    state = { category: {  } },
    action
  ) => {
    switch (action.type) {
      case CATEGORY_DETAIL_REQUEST:
        return { loading: true, ...state };

      case CATEGORY_DETAIL_SUCCESS:
        return { loading: false, category: action.payload };

      case CATEGORY_DETAIL_FAIL:
        return { loading: false, error: action.payload };

      default:
        return state;
    }
  };

store.js

const reducer = combineReducers({
  categoryDetail: categoryDetailsReducer,
});

component

function CategoryDetail({ match, history }) {
    // const { id } = useParams();
    // console.log(id);
    const dispatch = useDispatch();
    const categoryList = useSelector((state) => state.categoryList);
    const { loading, error, categories , page, pages} = categoryList;

    useEffect(() => {

        dispatch(listCategoryDetails());
    }, [dispatch, match]);

  return

                {categories.map(category => (
                <Col key={category.id} sm={12} md={8} lg={4} xl={3} >

{category.title}
))}

;
}

export default CategoryDetail;

Body:
Before

// const { id } = useParams();
// console.log(id);
const dispatch = useDispatch();
const categoryList = useSelector((state) => state.categoryList);
const { loading, error, categories , page, pages} = categoryList;

useEffect(() => {

    dispatch(listCategoryDetails());
}, [dispatch, match]);

After

const { id } = useParams();
console.log(id);
const dispatch = useDispatch();
const categoryList = useSelector((state) => state.categoryList);
const { loading, error, categories , page, pages} = categoryList;

useEffect(() => {

    dispatch(listCategoryDetails(id));
}, [dispatch, match]);

Inside UseEffect You Are Not Passing id Variable So its Saying Id Is Undefined


问:
Find all the tasks assigned to a member inside assignedTo array
```<code>[
 {
  _id: 1,
  title: "Task 1",
  assignedTo: ["userId1", "userId2", "userId3"]
  status: "To do"
 },
 {
  _id: 2,
  title: "Task 2",
  assignedTo: ["userId1", "userId2"],
  status: "In progress"
 },
 {
  _id: 3,
  title: "Task 3",
  assignedTo: ["userId3"],
  status: "Completed"
 }
]
</code>```

I want to use MongoDB aggregate to return all the tasks assigned to a user and group them by status. For example, the input is: userId: "userId1" , and the expected output should be something like this:

```<code>{
  results: [
    {
      status: "To do",
      tasks: [
          {
            _id: 1,
            title: "Task 1",
            assignedTo: ["userId1", "userId2", "userId3"]
           }
         ]
    },
    {
      status: "In progress",
      tasks: [
          {
            _id: 2,
            title: "Task 2",
            assignedTo: ["userId1", "userId2"]
           }
         ]
    },
    {
      status: "Completed",
      tasks: []
    },
  ]
}

</code>```

答:
you can group by status and push items if it matches the userId1

you can test it here mongodb playground

```<code>db.collection.aggregate([
  {
    "$group": {
      "_id": {
        status: "$status"
      },
      tasks: {
        "$push": {
          $cond: [
            {
              "$in": [
                "userId1",
                "$assignedTo"
              ]
            },
            {
              _id: "$_id",
              title: "$title",
              assignedTo: "$assignedTo"
            },
            "$$REMOVE"
          ]
        }
      }
    }
  },
  {
    "$project": {
      status: "$_id.status",
      tasks: 1,
      _id: 0
    }
  }
])
</code>```

Body:
[
 {
  _id: 1,
  title: "Task 1",
  assignedTo: ["userId1", "userId2", "userId3"]
  status: "To do"
 },
 {
  _id: 2,
  title: "Task 2",
  assignedTo: ["userId1", "userId2"],
  status: "In progress"
 },
 {
  _id: 3,
  title: "Task 3",
  assignedTo: ["userId3"],
  status: "Completed"
 }
]

I want to use MongoDB aggregate to return all the tasks assigned to a user and group them by status. For example, the input is: userId: "userId1" , and the expected output should be something like this:

{
  results: [
    {
      status: "To do",
      tasks: [
          {
            _id: 1,
            title: "Task 1",
            assignedTo: ["userId1", "userId2", "userId3"]
           }
         ]
    },
    {
      status: "In progress",
      tasks: [
          {
            _id: 2,
            title: "Task 2",
            assignedTo: ["userId1", "userId2"]
           }
         ]
    },
    {
      status: "Completed",
      tasks: []
    },
  ]
}

Body:
you can group by status and push items if it matches the userId1

you can test it here mongodb playground

db.collection.aggregate([
  {
    "$group": {
      "_id": {
        status: "$status"
      },
      tasks: {
        "$push": {
          $cond: [
            {
              "$in": [
                "userId1",
                "$assignedTo"
              ]
            },
            {
              _id: "$_id",
              title: "$title",
              assignedTo: "$assignedTo"
            },
            "$$REMOVE"
          ]
        }
      }
    }
  },
  {
    "$project": {
      status: "$_id.status",
      tasks: 1,
      _id: 0
    }
  }
])


问:
How can I use AccountManager in Android with Google Account?
I want to use AccountManager in Android, to verify a com.google account. I've already know how to get the account, But I've got several questions,

If the account is not in AccountManager, and the account self is under com.google domain, then how can I add it?

How AccountManager manage tokens? It retrieves tokens automatically, or I need to do it manually?

I'm trying to use Google Reader API with ClientLogin, then I may need password for the first time. If some com.google accounts are stored previously by other apps, can I use them to get the password?

Edit on 2011.08.20

To clarify the question, what I want to ask it this,

Google applications on Android has its own routine to verify Google accounts, and I want to know whether it's possible to call the routine created by Google applications, and get my own authority?

If there's no Google Account on Android phone, how can I add an account, which will be accepted by Google applications later?

答:
If the account is not in AccountManager, and the account self is under com.google domain, then how can I add it?

If you simply want to have, for example, a button that lets the user add a Google account, consider invoking the ADD_ACCOUNT intent. Another, more advanced, option is to use AccountManager.addAccount.

How AccountManager manage tokens? It retrieves tokens automatically, or I need to do it manually?

The system manages tokens. Well, actually, applications register 'authenticators' which manage tokens for their corresponding service. An authenticator for Google accounts comes preloaded with most Android devices, and third party apps like Twitter add their own authenticators when installed. Apps that want to use Google accounts can request authentication tokens using AccountManager.getAuthToken.

I'm trying to use Google Reader API with ClientLogin, then I may need password for the first time. If some com.google accounts are stored previously by other apps, can I use them to get the password?

Your app should never ask the user for her Google password. Use the relevant AccountManager methods to request an auth token for Reader. Unfortunately, since Google Reader doesn't have a public API I can't assist further.


问:
How could get Size of element in ArraySeq and also extract 1 by 1 element from it
I am new in scala. and I want to get below size of element from ArraySeq(Split by comma)

```<code>ArraySeq(A,B,C,D) // 4
ArraySeq(A,B,C)) // 3
ArraySeq(A,B)) //2
ArraySeq(A,B,C,D,E)) // 5
</code>```

Also I would like to access each element from ArraySeq.

Does anyone can help me out of that?

答:
You can use .size on any of the scala collections.

e.g. scala ArraySeq(A,B,C,D).size would return 4

There are a few ways to go about accessing the elements of the sequence

val example = ArraySeq(1,2,3,4,5)

// Using the apply method
example(1) // Result 2
example(10) // ArrayIndexOutOfBoundsException is thrown

// Using .get to avoid exceptions
example.get(2) // Result Some(3)
example.get(10) // Result None

// You can transform all elements using map
example.map(_  * 2) // Result ArraySeq(2,4,6,8,10)

// Or do something with all elements
example.foreach(println) // prints 1,2,3,4,5 separated by newlines
```
<p>If you have a nested ArraySeq (i,e, ArraySeq[ArraySet[T]]) you can get the total size using:</p>
```val exampleNested = ArraySeq(ArraySeq(1,2),ArraySeq(3,4,5), ArraySeq(6,7,8))

exampleNested.map(_.size).sum // Returns total size of 8
```
<p>You can also flatten the nested collections to a single array seq for ease of use with</p>
<pre class="lang-scala prettyprint-override"><code>exampleNested.flatten // Result ArraySeq(1, 2, 3, 4, 5, 6, 7, 8)
</code>```

Body:
I am new in scala. and I want to get below size of element from ArraySeq(Split by comma)

ArraySeq(A,B,C,D) // 4
ArraySeq(A,B,C)) // 3
ArraySeq(A,B)) //2
ArraySeq(A,B,C,D,E)) // 5

Also I would like to access each element from ArraySeq.

Does anyone can help me out of that?

Body:
You can use .size on any of the scala collections.

e.g. scala ArraySeq(A,B,C,D).size would return 4

There are a few ways to go about accessing the elements of the sequence

val example = ArraySeq(1,2,3,4,5)

// Using the apply method
example(1) // Result 2
example(10) // ArrayIndexOutOfBoundsException is thrown

// Using .get to avoid exceptions
example.get(2) // Result Some(3)
example.get(10) // Result None

// You can transform all elements using map
example.map(_  * 2) // Result ArraySeq(2,4,6,8,10)

// Or do something with all elements
example.foreach(println) // prints 1,2,3,4,5 separated by newlines

If you have a nested ArraySeq (i,e, ArraySeq[ArraySet[T]]) you can get the total size using:

val exampleNested = ArraySeq(ArraySeq(1,2),ArraySeq(3,4,5), ArraySeq(6,7,8))

exampleNested.map(_.size).sum // Returns total size of 8

You can also flatten the nested collections to a single array seq for ease of use with

exampleNested.flatten // Result ArraySeq(1, 2, 3, 4, 5, 6, 7, 8)


问:
Configuring Barebox bootloader for Raspberry Pi CM4
Advice on working with barebox bootloader on Raspberry Pi Cmpute Module 4 will be helpful.

I recently got my hands on a RPi CM4 Lite and now I want to build Yocto image with barebox as bootloader. I have few doubts before I get started.

How should I do the Barebox configuration? For example, for raspberrypi3 we can have machine config in conf/local.conf as:

```<code>BAREBOX_CONFIG_raspberrypi3 = "rpi_defconfig"
BAREBOX_IMAGE_SRC_raspberrypi3 = "images/barebox-raspberry-pi-3.img"
COMPATIBLE_MACHINE_pn-barebox_raspberrypi3 = "raspberrypi3"
</code>```

For RPi CM4, I am using MACHINE="raspberrypi4-64". How should this be used for barebox config?

In order to boot from uSD (for CM4 Lite) how should I copy the bootloader files? Will there be any difference between BCM283x RPi like RPi2/3 and BCM2711 based RPi CM4 Lite? In the Barebox manual steps are given for BCM283x machines.

I am trying to understand how boot process happens for RPi CM4 with barebox bootloader and yocto. My goal is to build an update with RAUC and Barebox.

Has anyone tried to configure barebox for RPi CM4?

Your help will be much appreciated.

Thanks in advance.

答: Starting with barebox v2022.08.0, there's now first upstream barebox support for the Raspberry Pi 4. There's still stuff missing, e.g. Ethernet for network boot, but Linux can be booted from SD. If you are willing to help with getting it to run on the CM4, you can mention that on the mailing list: https://lists.infradead.org/mailman/listinfo/barebox</p>

Body:
Advice on working with barebox bootloader on Raspberry Pi Cmpute Module 4 will be helpful.

I recently got my hands on a RPi CM4 Lite and now I want to build Yocto image with barebox as bootloader. I have few doubts before I get started.

How should I do the Barebox configuration? For example, for raspberrypi3 we can have machine config in conf/local.conf as:

BAREBOX_CONFIG_raspberrypi3 = "rpi_defconfig"
BAREBOX_IMAGE_SRC_raspberrypi3 = "images/barebox-raspberry-pi-3.img"
COMPATIBLE_MACHINE_pn-barebox_raspberrypi3 = "raspberrypi3"

For RPi CM4, I am using MACHINE="raspberrypi4-64". How should this be used for barebox config?

In order to boot from uSD (for CM4 Lite) how should I copy the bootloader files? Will there be any difference between BCM283x RPi like RPi2/3 and BCM2711 based RPi CM4 Lite? In the Barebox manual steps are given for BCM283x machines.

I am trying to understand how boot process happens for RPi CM4 with barebox bootloader and yocto. My goal is to build an update with RAUC and Barebox.

Has anyone tried to configure barebox for RPi CM4?

Your help will be much appreciated.

Thanks in advance.


问:
I want to take the data and close the current layout on the click on the item of recyclerview
I'm stuck by a problem and I don't know how too resolve it.
I want to click on my item in my recycler view, and at this click the layout with the recylcer view will be closed, and my mainActivity will be refresh with the data of the item who i have click on.</p>

答:
you start new activity to get Data but here you start a normal intent you need to start Activity For Result like

```<code>startActivityForResult(intent,REQUEST_CODE);
</code>```

or new Way

```<code>    ActivityResultLauncher<Intent> result = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
    @Override
    public void onActivityResult(ActivityResult result) {
        if(result.getResultCode() == RESULT_OK){
            String data =  result.getData().getStringExtra("Data");
            // here your data come from next Activity
        }
    }
});
</code>```

then call result by

```<code> result.launch(Intent);
</code>```

and in other Activity activity

you need to call

```<code>setResult(RESULT_OK,Intent);
    finish();
</code>```

this intent hold your data and will return to previous activity with it

Body:
you start new activity to get Data but here you start a normal intent you need to start Activity For Result like

startActivityForResult(intent,REQUEST_CODE);

or new Way

    ActivityResultLauncher<Intent> result = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
    @Override
    public void onActivityResult(ActivityResult result) {
        if(result.getResultCode() == RESULT_OK){
            String data =  result.getData().getStringExtra("Data");
            // here your data come from next Activity
        }
    }
});

then call result by

 result.launch(Intent);

and in other Activity activity

you need to call

setResult(RESULT_OK,Intent);
    finish();

this intent hold your data and will return to previous activity with it


问:
What would be the best approach to emulate "templates hierarchy"?
Ansible Tower does not offer directory hierarchy for templates and workflows.

How should  we manage their growing number in a flat structure?

I know we could use labels, but their use seems a bit tedious and assume that users already knows  label for template they look for.
Are there any best practices which we could follow?

答:
Ansible Tower does not offer directory hierarchy for templates and workflows.

Right, according the documentation the Job Templates view is a list only.

This list is sorted alphabetically by name, but you can sort by other criteria, or search by various fields and attributes of a template.

If using Labels

Labels can be used to group and filter job templates and completed jobs in the Tower display.

are not helpful

I know we could use labels, but their use seems a bit tedious and assume that users already knows label for template they look for.

there might the possibility to introduce a structured Naming Convention for TEMPLATES / NAME.

Since Job Templates are usually for automating administrative tasks like rollouts, updates, restarts, etc. you could have a structure there like DEP_ROLENAME_TASKNAME. This would also be possible for TEMPLATES DESCRIPTION. It is than easier to look them up via UI, as well REST API

```<code>curl --silent -u "${ACCOUNT}:${PASSWORD}" https://${TOWER_URL}/api/v2/job_templates/?search=DEP_ROLENAME_TASKNAME | jq .
</code>```

A better approach might be to introduce Teams

a subdivision of an organization with associated users, projects, credentials, and permissions. Teams provide a means to implement role-based access control schemes and delegate responsibilities across organizations.

and Add Permission for certain Job Templates. A specific team or users can than only see Job Templates for tasks which they are supposed to do. There would be no need for lookup, searching and filtering anymore.

Further reading

How to design role-based access control (RBAC)?

Ansible Tower Organizations

Body:
Ansible Tower does not offer directory hierarchy for templates and workflows.

Right, according the documentation the Job Templates view is a list only.

This list is sorted alphabetically by name, but you can sort by other criteria, or search by various fields and attributes of a template.

If using Labels

Labels can be used to group and filter job templates and completed jobs in the Tower display.

are not helpful

I know we could use labels, but their use seems a bit tedious and assume that users already knows label for template they look for.

there might the possibility to introduce a structured Naming Convention for TEMPLATES / NAME.

Since Job Templates are usually for automating administrative tasks like rollouts, updates, restarts, etc. you could have a structure there like DEP_ROLENAME_TASKNAME. This would also be possible for TEMPLATES DESCRIPTION. It is than easier to look them up via UI, as well REST API

curl --silent -u "${ACCOUNT}:${PASSWORD}" https://${TOWER_URL}/api/v2/job_templates/?search=DEP_ROLENAME_TASKNAME | jq .

A better approach might be to introduce Teams

a subdivision of an organization with associated users, projects, credentials, and permissions. Teams provide a means to implement role-based access control schemes and delegate responsibilities across organizations.

and Add Permission for certain Job Templates. A specific team or users can than only see Job Templates for tasks which they are supposed to do. There would be no need for lookup, searching and filtering anymore.

Further reading

How to design role-based access control (RBAC)?

Ansible Tower Organizations


问:
Cannot resolve viewModel injection with delegate style declaration
I have a custom view class. I need to use my viewModel class here but it doesn't allow it.</p>
```<code>class CustomOverlayView(private val context: Context) {

    private val viewModel = SampleViewModel(context as Application)

}
</code>```

答:
I think i made it:</p>
```<code>private val viewModel = SampleViewModel(context as Application)
</code>```

Body:
I have a custom view class. I need to use my viewModel class here but it doesn't allow it.

class CustomOverlayView(private val context: Context) {

    private val viewModel = SampleViewModel(context as Application)

}

Body:
I think i made it:

private val viewModel = SampleViewModel(context as Application)


问:
What Join is it called and how to do it in Oracle SQL
Please have a look at these Tables below. I've three tables where Invoice and Receipt tables don't have any direct link. They can only be linked using another Table and here it is "Invoice * Receipt Link Table"

Invoice Table

Invoice No

1

2

Receipt Table

Receipt No

1

2

Invoice * Receipt Link Table

Invoice No
Receipt No

2
1

Result table I'm expecting

Invoice No
Receipt No

1
null

2
1

null
2

What kind of join do we even call it and how to make a join among these three tables to get result as in the 4th table?

答:
Use a FULL OUTER JOIN:

SELECT i.invoice_no,
       r.receipt_no
FROM   invoice i
       FULL OUTER JOIN link l
       ON (i.invoice_no = l.invoice_no)
       FULL OUTER JOIN receipt r
       ON (r.receipt_no = l.receipt_no)
```
<p>Which, for the sample data:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE invoice (Invoice_No) AS
SELECT 1 FROM DUAL UNION ALL
SELECT 2 FROM DUAL;

CREATE TABLE receipt (receipt_No) AS
SELECT 1 FROM DUAL UNION ALL
SELECT 2 FROM DUAL;

CREATE TABLE link (invoice_no, receipt_No) AS
SELECT 2, 1 FROM DUAL;
</code>```

Outputs:

INVOICE_NO
RECEIPT_NO

2
1

null
2

1
null

db<>fiddle here

Body:
Use a FULL OUTER JOIN:

SELECT i.invoice_no,
       r.receipt_no
FROM   invoice i
       FULL OUTER JOIN link l
       ON (i.invoice_no = l.invoice_no)
       FULL OUTER JOIN receipt r
       ON (r.receipt_no = l.receipt_no)

Which, for the sample data:

CREATE TABLE invoice (Invoice_No) AS
SELECT 1 FROM DUAL UNION ALL
SELECT 2 FROM DUAL;

CREATE TABLE receipt (receipt_No) AS
SELECT 1 FROM DUAL UNION ALL
SELECT 2 FROM DUAL;

CREATE TABLE link (invoice_no, receipt_No) AS
SELECT 2, 1 FROM DUAL;

Outputs:

INVOICE_NO
RECEIPT_NO

2
1

null
2

1
null

db<>fiddle here


问:
How to display all array elements in one column of table
I have three arrays and I want to display each of the array in a separate column of the table. My HTML table contains 3 columns.
I want to display these arrays like this.

        First Column
        Second Column
        Third Column

    Array 1 first value
        Array 2 first value
        Array 3 first value

     Array 1 second value
        Array 2 second value
        Array 3 second value

    Array 1 third value
        Array 2 third value
        Array 3 third value

```
</div>
</div>
</p>
<p>This is how my arrays look like.</p>
``` $arr1 = array(1, 2, 3, 4);
 $arr2 = array(a, b, c, d);
 $arr3 = array(1, 2, 3, 4);
 $array = array($arr1, $arr2, $arr3);
```
<p>This is how I tried to display but it did not work as expected.</p>
```foreach($array as $key => $arr){
echo '
';

?>
        <?php
        echo $arr[$key]->post_title;
        ?>
        <?php
        echo $arr[$key]->post_title;
        ?>
        <?php
        echo $arr[$key]->post_title;
        ?>
    <?php

echo '
';
}
```

It may be simple but I could not develop the logic to get this working. Any suggestion will be much appreciated.

答:
```<code><?php
$array1 = [
    'Array 1 first value',
    'Array 1 second value',
    'Array 1 third value',
];
$array2 = [
    'Array 2 first value',
    'Array 2 second value',
    'Array 2 third value',
];
$array3 = [
    'Array 3 first value',
    'Array 3 second value',
    'Array 3 third value',
];
?>

<!-- Html part -->
<table>
    <tr>
        <th>First Column</th>
        <th>Second Column</th>
        <th>Third Column</th>
    </tr>
    <?php
        foreach($array1 as $key => $value){
            ?>
            <tr>
                <td><?php echo $array1[$key] ?? '' ?></td>
                <td><?php echo $array2[$key] ?? '' ?></td>
                <td><?php echo $array3[$key] ?? '' ?></td>
            </tr>
            <?php
        }
    ?>
</table>
</code>```

Html Output:

```<code><table>
   <tr>
      <th>First Column</th>
      <th>Second Column</th>
      <th>Third Column</th>
   </tr>
   <tr>
      <td>Array 1 first value</td>
      <td>Array 2 first value</td>
      <td>Array 3 first value</td>
   </tr>
   <tr>
      <td>Array 1 second value</td>
      <td>Array 2 second value</td>
      <td>Array 3 second value</td>
   </tr>
   <tr>
      <td>Array 1 third value</td>
      <td>Array 2 third value</td>
      <td>Array 3 third value</td>
   </tr>
</table>
</code>```

Body:
I have three arrays and I want to display each of the array in a separate column of the table. My HTML table contains 3 columns.
I want to display these arrays like this.

        First Column
        Second Column
        Third Column

    Array 1 first value
        Array 2 first value
        Array 3 first value

     Array 1 second value
        Array 2 second value
        Array 3 second value

    Array 1 third value
        Array 2 third value
        Array 3 third value

This is how my arrays look like.

 $arr1 = array(1, 2, 3, 4);
 $arr2 = array(a, b, c, d);
 $arr3 = array(1, 2, 3, 4);
 $array = array($arr1, $arr2, $arr3);

This is how I tried to display but it did not work as expected.

foreach($array as $key => $arr){
echo '
';

?>
        <?php
        echo $arr[$key]->post_title;
        ?>
        <?php
        echo $arr[$key]->post_title;
        ?>
        <?php
        echo $arr[$key]->post_title;
        ?>
    <?php

echo '
';
}

It may be simple but I could not develop the logic to get this working. Any suggestion will be much appreciated.

Body:
<?php
$array1 = [
    'Array 1 first value',
    'Array 1 second value',
    'Array 1 third value',
];
$array2 = [
    'Array 2 first value',
    'Array 2 second value',
    'Array 2 third value',
];
$array3 = [
    'Array 3 first value',
    'Array 3 second value',
    'Array 3 third value',
];
?>

<!-- Html part -->
<table>
    <tr>
        <th>First Column</th>
        <th>Second Column</th>
        <th>Third Column</th>
    </tr>
    <?php
        foreach($array1 as $key => $value){
            ?>
            <tr>
                <td><?php echo $array1[$key] ?? '' ?></td>
                <td><?php echo $array2[$key] ?? '' ?></td>
                <td><?php echo $array3[$key] ?? '' ?></td>
            </tr>
            <?php
        }
    ?>
</table>

Html Output:

<table>
   <tr>
      <th>First Column</th>
      <th>Second Column</th>
      <th>Third Column</th>
   </tr>
   <tr>
      <td>Array 1 first value</td>
      <td>Array 2 first value</td>
      <td>Array 3 first value</td>
   </tr>
   <tr>
      <td>Array 1 second value</td>
      <td>Array 2 second value</td>
      <td>Array 3 second value</td>
   </tr>
   <tr>
      <td>Array 1 third value</td>
      <td>Array 2 third value</td>
      <td>Array 3 third value</td>
   </tr>
</table>


答:
This is called a full outer join.

One way to express it:

```<code>select *
from invoice
full outer join receipt
     on (invoice_id, receipt_id) in (
         select invoice_id, receipt_id from invoice_receipt
     )
</code>```

Title: What Join is it called and how to do it in Oracle SQL

Body:
Please have a look at these Tables below. I've three tables where Invoice and Receipt tables don't have any direct link. They can only be linked using another Table and here it is "Invoice * Receipt Link Table"

Invoice Table

Invoice No

1

2

Receipt Table

Receipt No

1

2

Invoice * Receipt Link Table

Invoice No
Receipt No

2
1

Result table I'm expecting

Invoice No
Receipt No

1
null

2
1

null
2

What kind of join do we even call it and how to make a join among these three tables to get result as in the 4th table?

Body:
This is called a full outer join.

One way to express it:

select *
from invoice
full outer join receipt
     on (invoice_id, receipt_id) in (
         select invoice_id, receipt_id from invoice_receipt
     )


问:
Get from api react with useState, useEffect
I am a beginner.
I have such a fetch

```<code>const getMovieByDecade = (decade) => {
    return api.get(`movie/years/${decade}`)
}
</code>```

API for ${decade} ex.1920 :

```<code> "id": "aebfdffa-748d-4e33-bf2c-da353b185aac",
"title": "Some Movie ",
"year": 1925,
</code>```

How can I download and return movies from this Api sequentially by decade using React Hooks (useState, UseEffetct) ?

```<code>export const YearOfProduction = () => {

return (
    <HomeWrapper>
        <BackButton />
        <YearOfProductionHeader>
            <h1>Year YearOfProduction</h1>
            <img className="clock" src="/images/clock.png"></img>
        </YearOfProductionHeader>
        <YearsOfProductionWrapper>
            <div className="XIXcentury">
                <span className="century">XIX</span>
                <Years>'90</Years>
            </div>
            <div class="XXcentury">
                <span className="century">XX</span>
                <div className="ten_years">
                    <Years >'00</Years>
                    <Years>'10</Years>
                    <Years>'20</Years>
                    <Years>'30</Years>
                    <Years>'40</Years>
                </div>
                <div className="ten_years">
                    <Years>'50</Years>
                    <Years>'60</Years>
                    <Years>'70</Years>
                    <Years>'80</Years>
                    <Years>'90</Years>
                </div>
            </div>
        </YearsOfProductionWrapper>
      // here I is place for movie list after decades after Click Years

    </HomeWrapper>

)
</code>```

}

答:
Supposing that you have a form or selector, where the user selects a decade and you fetch movies for the decade, this should work :

const [decade, setDecade] = useState(1990)
const [movies, setMovies] = useState({})

useEffect(() => {

  const getData = async() => {
    await getMovieByDecade(decade);
    setMovies(movies)
  }
  getData()
}, [decade])```

Body:
I am a beginner.
I have such a fetch

const getMovieByDecade = (decade) => {
    return api.get(`movie/years/${decade}`)
}

API for ${decade} ex.1920 :

 "id": "aebfdffa-748d-4e33-bf2c-da353b185aac",
"title": "Some Movie ",
"year": 1925,

How can I download and return movies from this Api sequentially by decade using React Hooks (useState, UseEffetct) ?

export const YearOfProduction = () => {

return (
    <HomeWrapper>
        <BackButton />
        <YearOfProductionHeader>

Year YearOfProduction

        </YearOfProductionHeader>
        <YearsOfProductionWrapper>

                XIX
                <Years>'90</Years>

                XX

                    <Years >'00</Years>
                    <Years>'10</Years>
                    <Years>'20</Years>
                    <Years>'30</Years>
                    <Years>'40</Years>

                    <Years>'50</Years>
                    <Years>'60</Years>
                    <Years>'70</Years>
                    <Years>'80</Years>
                    <Years>'90</Years>

        </YearsOfProductionWrapper>
      // here I is place for movie list after decades after Click Years

    </HomeWrapper>

)

}


问:
Is Linq to objects join default order specified when no order by is used?
I got following query

```<code>IEnumerable<string> values = from first in goodOrdered
join second in badOrdered on first.ToLower() equals
second.ToLower()
select second;
</code>```

Currently my tests show that end result is actually goodOrdered, like I want it. Can I expect that to always be true or I should provide an order by statement that will force to keep goodOrdered order ( it will make query more complex, because goodOrdered can look like 1, 9, 2, 7, 6)?

答:
Yes, it does.  According to the MSDN documentation:

Join preserves the order of the elements of outer, and for each of
  these elements, the order of the matching elements of inner.

Of course, if it was not specified in the documentation it would be an entirely different matter.  Another issue you may want to consider is developers who will be responsible for maintaining the code, and whether you would expect them to know/remember that Join's contract includes preserving order of the outer sequence...

Body:
I got following query

IEnumerable<string> values = from first in goodOrdered
join second in badOrdered on first.ToLower() equals
second.ToLower()
select second;

Currently my tests show that end result is actually goodOrdered, like I want it. Can I expect that to always be true or I should provide an order by statement that will force to keep goodOrdered order ( it will make query more complex, because goodOrdered can look like 1, 9, 2, 7, 6)?


问:
Creating and iterating a 2d array in Ruby
I have very little knowledge about Ruby and cant find a way to create 2d array. Can anyone provide me some snippets or information to get me started? </p>

答:
Creating a 2d array in Ruby

In ruby, every method accepts a block.

```<code>two_d_array = Array.new(3) do
  Array.new(3) do
    0
  end
end
</code>```

The same can be written In oneline (macro style)

```<code>two_d_array = Array.new(3) { Array.new(3) { 0 } }
</code>```

Output

```<code>[
 [0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]
]
</code>```

Iterating a 2d array in Ruby

I can think of three ways.

1: Using range

```<code>(0...two_d_array.size).each do |i|
  (0...(two_d_array[i].length)).each do |j|
    puts two_d_array[i][j]
  end
end
</code>```

2: Using for

```<code>for i in (0...two_d_array.size)
 for j in (0...two_d_array[i].length)
  puts two_d_array[i][j]
 end
end
</code>```

3: Using Each_with_index method

```<code>two_d_array.each_with_index do |sub_array, i|
  sub_array.each_with_index do |item, j|
    puts two_d_array[i][j]
  end
end
</code>```

Body:
Creating a 2d array in Ruby

In ruby, every method accepts a block.

two_d_array = Array.new(3) do
  Array.new(3) do
    0
  end
end

The same can be written In oneline (macro style)

two_d_array = Array.new(3) { Array.new(3) { 0 } }

Output

[
 [0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]
]

Iterating a 2d array in Ruby

I can think of three ways.

1: Using range

(0...two_d_array.size).each do |i|
  (0...(two_d_array[i].length)).each do |j|
    puts two_d_array[i][j]
  end
end

2: Using for

for i in (0...two_d_array.size)
 for j in (0...two_d_array[i].length)
  puts two_d_array[i][j]
 end
end

3: Using Each_with_index method

two_d_array.each_with_index do |sub_array, i|
  sub_array.each_with_index do |item, j|
    puts two_d_array[i][j]
  end
end


问:
What can MyPy detect and what can it not?
I just started with MyPy to add more static typing to my python programs. I tried this:

```<code>import sys

def summe (a: int, b: int):
    print (a + b)

def main():
    x: int = 10
    y: int = 20
    z: str = '30'
    summe (x, y)
    summe (x, z)

if __name__ == '__main__':
    sys.exit(main())
</code>```

and this is obviously a type error and crashes at runtime but MyPy says: Success: no issues found in 1 source file

Am I doing something wrong, missed some setting? I have Windows 10, Python 3.10, latest MyPy under Eclipse.

答:
Your main is not being type-checked as you have not annotated it. Add the annotation:

```<code>def main() -> None:
</code>```

And the second summe call will cause a type error as you expect.

Body:
I just started with MyPy to add more static typing to my python programs. I tried this:

import sys

def summe (a: int, b: int):
    print (a + b)

def main():
    x: int = 10
    y: int = 20
    z: str = '30'
    summe (x, y)
    summe (x, z)

if __name__ == '__main__':
    sys.exit(main())

and this is obviously a type error and crashes at runtime but MyPy says: Success: no issues found in 1 source file

Am I doing something wrong, missed some setting? I have Windows 10, Python 3.10, latest MyPy under Eclipse.

Body:
Your main is not being type-checked as you have not annotated it. Add the annotation:

def main() -> None:

And the second summe call will cause a type error as you expect.


问:
Spring Boot 2.6.X + JRE 17 Openj9 - Unhandled exception Type=Segmentation error
Target of this post is to help to solve the the problem in the title.

Infos:

java -version

```<code>openjdk version "17.0.2" 2022-01-18
IBM Semeru Runtime Open Edition 17.0.2.0 (build 17.0.2+8)
Eclipse OpenJ9 VM 17.0.2.0 (build openj9-0.30.0, JRE 17 Linux amd64-64-Bit Compressed References 20220128_115 (JIT enabled, AOT enabled)
OpenJ9   - 9dccbe076
OMR      - dac962a28
JCL      - 64cd399ca28 based on jdk-17.0.2+8)
</code>```

SpringBoot version: v2.6.2

Detailed error:

```<code>    Unhandled exception
    Type=Segmentation error vmState=0x00000000
    J9Generic_Signal_Number=00000018 Signal_Number=0000000b Error_Value=00000000 Signal_Code=00000001
    Handler1=00007FD4FEE86560 Handler2=00007FD4FEBE4BA0 InaccessibleAddress=00000000FFFFF780
    [...]
    Module=/opt/jre-17.0.2+8-openj9/lib/default/libj9vm29.so
</code>```

答:
After much tries, I isolated the problem: it seems that the problem only occurs when the following dependency is active (maven syntax):

```<code><dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>${springdoc.version}</version>
</dependency>
</code>```

where ${springdoc.version} is 1.6.3 (or <= 1.6.3)

Use dependency >= 1.6.4 and the problem is solved.

Body:
Target of this post is to help to solve the the problem in the title.

Infos:

java -version

openjdk version "17.0.2" 2022-01-18
IBM Semeru Runtime Open Edition 17.0.2.0 (build 17.0.2+8)
Eclipse OpenJ9 VM 17.0.2.0 (build openj9-0.30.0, JRE 17 Linux amd64-64-Bit Compressed References 20220128_115 (JIT enabled, AOT enabled)
OpenJ9   - 9dccbe076
OMR      - dac962a28
JCL      - 64cd399ca28 based on jdk-17.0.2+8)

SpringBoot version: v2.6.2

Detailed error:

    Unhandled exception
    Type=Segmentation error vmState=0x00000000
    J9Generic_Signal_Number=00000018 Signal_Number=0000000b Error_Value=00000000 Signal_Code=00000001
    Handler1=00007FD4FEE86560 Handler2=00007FD4FEBE4BA0 InaccessibleAddress=00000000FFFFF780
    [...]
    Module=/opt/jre-17.0.2+8-openj9/lib/default/libj9vm29.so

Body:
After much tries, I isolated the problem: it seems that the problem only occurs when the following dependency is active (maven syntax):

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>${springdoc.version}</version>
</dependency>

where ${springdoc.version} is 1.6.3 (or <= 1.6.3)

Use dependency >= 1.6.4 and the problem is solved.


问:
file does not begin with %pdf-
I asked this question and have now got it mostly working.

However I am still getting the titled error and cannot seem to find any reference to anyone that has solved it.

This is driving me insane!

My ASHX C# code looks like this;

```<code>context.Response.Clear();
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.Buffer = true;
context.Response.Charset = "";
context.Response.AddHeader("Content-Disposition", "inline;filename=file.pdf");
context.Response.ContentType = "application/pdf";

Stream fileStream = publishBookManager.GetFile();
byte[] buffer = new byte[32 * 1024];
using (MemoryStream ms = new MemoryStream())
{
  int read;
  while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
  {
    ms.Write(buffer, 0, read);
  }
}

context.Response.BinaryWrite(buffer);
context.Response.Flush();
context.Response.Close();
</code>```

And my jQuery / javascript looks like;

```<code>window.open('/UserControls/download.ashx?format=pdf&bookId=' + bookId, "pdfViewer");
</code>```

答:
There's several problems with this code - you write out the content of buffer when you probably meant to write out the contents of your memory stream, which you dispose of without using - but why not just do

```<code>fileStream.CopyTo(context.Response.OutputStream);
</code>```

Title: file does not begin with %pdf-

Body:
I asked this question and have now got it mostly working.

However I am still getting the titled error and cannot seem to find any reference to anyone that has solved it.

This is driving me insane!

My ASHX C# code looks like this;

context.Response.Clear();
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.Buffer = true;
context.Response.Charset = "";
context.Response.AddHeader("Content-Disposition", "inline;filename=file.pdf");
context.Response.ContentType = "application/pdf";

Stream fileStream = publishBookManager.GetFile();
byte[] buffer = new byte[32 * 1024];
using (MemoryStream ms = new MemoryStream())
{
  int read;
  while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
  {
    ms.Write(buffer, 0, read);
  }
}

context.Response.BinaryWrite(buffer);
context.Response.Flush();
context.Response.Close();

And my jQuery / javascript looks like;

window.open('/UserControls/download.ashx?format=pdf&bookId=' + bookId, "pdfViewer");

Body:
There's several problems with this code - you write out the content of buffer when you probably meant to write out the contents of your memory stream, which you dispose of without using - but why not just do

fileStream.CopyTo(context.Response.OutputStream);


问:
Spring boot: push message to specific topic for each request
I am using pub sub integration with spring boot, for which my configuration class look like this:

```<code>@Configuration
public class PubSubConfiguration {

    @Value("${spring.pubsub.topic.name}")
    private String topicName;

    @Bean
    @ServiceActivator(inputChannel = "MyOutputChannel")
    public PubSubMessageHandler messageSender(PubSubTemplate pubsubTemplate) {
        return new PubSubMessageHandler(pubsubTemplate, topicName);
    }

    @MessagingGateway(defaultRequestChannel = "MyOutputChannel")
    public interface PubsubOutboundGateway {
        void sendToPubsub(String attribute);
    }

}
</code>```

So now, I was calling only sendToPubSub method which add payload into topic from my app, like this:

```<code>@Autowired
private PubSubConfiguration.PubsubOutboundGateway outboundGateway;

// used line in my code wherever is needed.
outboundGateway.sendToPubsub(jsonInString);
</code>```

The above code is just meant for one topic which i loaded from application property file.

But now I wanted to make my topic name is dynamically added into messageSender, how to do that.

答:
To override the default topic you can use the GcpPubSubHeaders.TOPIC header.

final Message<?> message = MessageBuilder
        .withPayload(msg.getPayload())
        .setHeader(GcpPubSubHeaders.TOPIC, "newTopic").build();
```

and modify your sendToPubsub(Message<byte[]> message) to use message as input.

Refer for more information

Body:
I am using pub sub integration with spring boot, for which my configuration class look like this:

@Configuration
public class PubSubConfiguration {

    @Value("${spring.pubsub.topic.name}")
    private String topicName;

    @Bean
    @ServiceActivator(inputChannel = "MyOutputChannel")
    public PubSubMessageHandler messageSender(PubSubTemplate pubsubTemplate) {
        return new PubSubMessageHandler(pubsubTemplate, topicName);
    }

    @MessagingGateway(defaultRequestChannel = "MyOutputChannel")
    public interface PubsubOutboundGateway {
        void sendToPubsub(String attribute);
    }

}

So now, I was calling only sendToPubSub method which add payload into topic from my app, like this:

@Autowired
private PubSubConfiguration.PubsubOutboundGateway outboundGateway;

// used line in my code wherever is needed.
outboundGateway.sendToPubsub(jsonInString);

The above code is just meant for one topic which i loaded from application property file.

But now I wanted to make my topic name is dynamically added into messageSender, how to do that.

Body:
To override the default topic you can use the GcpPubSubHeaders.TOPIC header.

final Message<?> message = MessageBuilder
        .withPayload(msg.getPayload())
        .setHeader(GcpPubSubHeaders.TOPIC, "newTopic").build();

and modify your sendToPubsub(Message<byte[]> message) to use message as input.

Refer for more information


问:
WKWebView does not open https://itunes.apple.com/app/id123456 link
Here is a little problem I just noticed in one of my iOS apps.

I use Xcode Version 10.1 and Swift 4.2.

The app has a button which when pushed brings up a view controller, this VC is in charge of opening a link to the app itself in itunes. I have done this many times with no problems in the past.

But this time, a blank pages opens up and nothing else. I have tried to replace only the URL I am interested in by "https://www.google.com/" and it works perfectly as expected (i.e. the Google page shows up). Of course I have verified that my URL is correct.

Can anybody see what could be the issue?
Thanks in advance for any relevant tip.

Here is the code for the whole view controller.

```<code>import UIKit
import WebKit

class appStore_ViewController: UIViewController, WKNavigationDelegate {
    let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
    var webView: WKWebView!

    override func loadView() {
        webView = WKWebView()
        webView.navigationDelegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let appStoreURL = URL(string: "https://itunes.apple.com/app/id\ (appDelegate.applicationID)?mt=8")
        //let appStoreURL = URL(string: "https://www.google.com/") // This works as     expected.
        print("The link: \(appStoreURL!.absoluteString)") // This shows what is expected     (a working URL).
        webView.load(URLRequest(url: appStoreURL!))
    }
}
</code>```

答:
You need to implement the decidePolicyForNavigationAction method of  WKNavigationDelegate for this to work.

```<code>    - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)

    (WKNavigationActionPolicy))decisionHandler {
    /* Code to handle other schemes such as file, https, http, etc. if required
    */
    if ([[[navigationAction.request URL] scheme] isEqual:@"itms-appss"])
  {

        [[UIApplication sharedApplication] openURL:[navigationAction.request URL]];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
   }
}
</code>```

WKWebview does not inherently support different schemes such as "itms-appss" and you need to check and implement the url scheme you want to support.

You also need to check if you are running in iPadOS and set WKWebpagePreference to use mobile content mode if you do so.

Body:
Here is a little problem I just noticed in one of my iOS apps.

I use Xcode Version 10.1 and Swift 4.2.

The app has a button which when pushed brings up a view controller, this VC is in charge of opening a link to the app itself in itunes. I have done this many times with no problems in the past.

But this time, a blank pages opens up and nothing else. I have tried to replace only the URL I am interested in by "https://www.google.com/" and it works perfectly as expected (i.e. the Google page shows up). Of course I have verified that my URL is correct.

Can anybody see what could be the issue?
Thanks in advance for any relevant tip.

Here is the code for the whole view controller.

import UIKit
import WebKit

class appStore_ViewController: UIViewController, WKNavigationDelegate {
    let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
    var webView: WKWebView!

    override func loadView() {
        webView = WKWebView()
        webView.navigationDelegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let appStoreURL = URL(string: "https://itunes.apple.com/app/id\ (appDelegate.applicationID)?mt=8")
        //let appStoreURL = URL(string: "https://www.google.com/") // This works as     expected.
        print("The link: \(appStoreURL!.absoluteString)") // This shows what is expected     (a working URL).
        webView.load(URLRequest(url: appStoreURL!))
    }
}

Body:
You need to implement the decidePolicyForNavigationAction method of  WKNavigationDelegate for this to work.

    - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)

    (WKNavigationActionPolicy))decisionHandler {
    /* Code to handle other schemes such as file, https, http, etc. if required
    */
    if ([[[navigationAction.request URL] scheme] isEqual:@"itms-appss"])
  {

        [[UIApplication sharedApplication] openURL:[navigationAction.request URL]];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
   }
}

WKWebview does not inherently support different schemes such as "itms-appss" and you need to check and implement the url scheme you want to support.

You also need to check if you are running in iPadOS and set WKWebpagePreference to use mobile content mode if you do so.


问:
How can I make an Author Role publish content on the Strapi dashboard?
I've been developing a blog for a few days, my idea is to give public access to the delivered news, but in the backend managed with Strapi, I have my role of superAdmin, Editor and Author. The Author can only add post, but when they do it, it is saved as draf, without the option of being able to publish.
I have 4 users with the Author Role in the Strapi admin panel. and what I want to know is if there is any possibility to give the Author Role the possibility to Publish the content.
(All the above mentioned is from the Roles of the Strapi Administration panel, I am not talking about the Roles of Public and Authenticated)

答:
I am new to Strapi and I have been making some tests about the default roles of Strapi.

It appears that currently the default behaviour for the role Author in Strapi community edition is:

The Author can only see content that it created

The Author can NOT publish any content.

Therefor if you want to change that behaviour you need Strapi enterprise edition that gives you a granular access control.

If you go to the pricing page of Strapi (https://strapi.io/pricing-self-hosted) you can click on Free Enterprise Edition trial under the Silver plan to check if that actually fits your needs.


问:
I run into problems when i add ".slice()" to the line of code
I'm new to vue.js.
I'm making a fast typing application.

Everything was as it should be, but when I wrote and ran this line of code, I got this error in the terminal:

**INFO  Starting development server...
98% after emitting CopyPlugin
ERROR  Failed to compile with 1 error                                            23:59:37
This dependency was not found:

core-js/modules/es.array.slice.js in ./node_modules/cache-loader/dist/cjs.js??ref--13-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--1-0!./node_modules/vue-loader-v16/dist??ref--1-1!./src/components/Main.vue?vue&type=script&lang=js

To install it, you can run: npm install --save core-js/modules/es.array.slice.js
Error from chokidar (C:): Error: EBUSY: resource busy or locked, lstat 'C:\DumpStack.log.tmp'**

As it told me to, I ran: npm install --save core-js/modules/es.array.slice.js

Then it looks like this:

npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path C:\Users\user\fast-typing\core-js\modules\es.array.slice.js/package.json
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\user\fast-typing\core-js\modules\es.array.slice.js\package.json'
npm ERR! enoent This is related to npm not being able to find a file.

npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\user\AppData\Local\npm-cache_logs\2022-02-06T21_06_50_092Z-debug.log

Local ekranım ise şu şekilde :

./src/components/Main.vue?vue&type=script&lang=js (./node_modules/cache-loader/dist/cjs.js??ref--13-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--1-0!./node_modules/vue-loader-v16/dist??ref--1-1!./src/components/Main.vue?vue&type=script&lang=js)
Module not found: Error: Can't resolve 'core-js/modules/es.array.slice.js' in 'C:\Users\user\fast-typing\src\components'

Note: I tried npm install --save core-js and npm install --save corejs@2 but the problem is not solved

Thanks in advance for your answers!

答:
seems like you're dealing with version problems of core-js package. You can look at package.json file and check "core-js" version. Let's update core-js package via npm.

Try:

```<code>npm install core-js@3.6.5
</code>```

or

```<code>npm install core-js@3
</code>```

Body:
seems like you're dealing with version problems of core-js package. You can look at package.json file and check "core-js" version. Let's update core-js package via npm.

Try:

npm install core-js@3.6.5

or

npm install core-js@3


问:
Reading an Image (standard format png,jpeg etc) and writing the Image Data to a binary file using Objective C
I am pretty new to Objective C and working with Cocoa Framework. I want to read an image and then extract the image data (just pixel data and not  the header) and then write the data to a binary file. I am kind of stuck with this, I was going through the methods of NSImage but I couldn't find a suitable one. Can anyone suggest me some other ways of doing this?

答:
Cocoa-wise, the easiest approach is to use the NSBitmapImageRep class. Once initialized with a NSData object, for example, you can access the color value at any coordinate as a NSColor object using the -setColor:atX:y: and -colorAtX:y: methods. Note that if you call these methods in tight loops, you may suffer a performance hit from objc_msg_send. You could consider accessing the raw bitmap data as C array via the -bitmapData method. When dealing with a RGB image, for example, the color values for each channel are stored at offsets of 3.

For example:

```<code>color values: [R,G,B][R,G,B][R,G,B]
     indices: [0,1,2, 3,4,5, 6,7,8]
</code>```

To loop through each pixel in the image and extract the RGB components:

```<code>unsigned char *bitmapData = [bitmapRep bitmapData];

if ([bitmapRep samplesPerPixel] == 3) {
    for (i = 0; i < [image size].width * [image size].height; i++) {
        int base = (i * 3);

        // these range from 0-255
        unsigned char red = bitmapData[base + 0];
        unsigned char green = bitmapData[base + 1];
        unsigned char blue = bitmapData[base + 2];
    }
}
</code>```

Body:
Cocoa-wise, the easiest approach is to use the NSBitmapImageRep class. Once initialized with a NSData object, for example, you can access the color value at any coordinate as a NSColor object using the -setColor:atX:y: and -colorAtX:y: methods. Note that if you call these methods in tight loops, you may suffer a performance hit from objc_msg_send. You could consider accessing the raw bitmap data as C array via the -bitmapData method. When dealing with a RGB image, for example, the color values for each channel are stored at offsets of 3.

For example:

color values: [R,G,B][R,G,B][R,G,B]
     indices: [0,1,2, 3,4,5, 6,7,8]

To loop through each pixel in the image and extract the RGB components:

unsigned char *bitmapData = [bitmapRep bitmapData];

if ([bitmapRep samplesPerPixel] == 3) {
    for (i = 0; i < [image size].width * [image size].height; i++) {
        int base = (i * 3);

        // these range from 0-255
        unsigned char red = bitmapData[base + 0];
        unsigned char green = bitmapData[base + 1];
        unsigned char blue = bitmapData[base + 2];
    }
}