问:
Nonlinear constrained optimization with optimx
I'm trying to use optimx for a constrained nonlinear problem, but I just can't find an example online that I can adjust (I'm not an R programmer). I found that I should be using the below to test a few algorithms

```<code>optimx(par, fn, lower=low, upper=up, method=c("CG", "L-BFGS-B", "spg", "nlm"))
</code>```

I understand par is just an example of a feasible solution. So, if I have two variables and (0,3) is feasible I can just do par <- c(0,3). If I want to minimise

```<code>2x+3y
</code>```

subject to

```<code>2x^2 + 3y^2 <= 100
x<=3
-x<=0
-y<=-3
</code>```

I guess i can set fn like

```<code>fn <- function(x){return 2*x[0]+3*x[1]}
</code>```

but how do I set lower and upper for my constraints?

Many thanks!

答:
1) We can incorporate the constraints within the objective function by returning a large number if any constraint is violated.

For most methods (but not Nelder Mead) the requirement is that the objective function be continuous and differentiable and requires a starting value in the interior of the feasible region, not the boundary. These requirements are not satisfied for f below but we will try it anyways.

```<code>library(optimx)

f <- function(z, x = z[1], y = z[2]) {
  if (2*x^2 + 3*y^2 <= 100 && x<=3 && -x<=0 && -y<=-3) 2*x+3*y else 1e10
}

optimx(c(0, 3), f, method = c("Nelder", "CG", "L-BFGS-B", "spg", "nlm"))
##             p1 p2 value fevals gevals niter convcode  kkt1  kkt2 xtime
## Nelder-Mead  0  3     9    187     NA    NA        0 FALSE FALSE  0.00
## CG           0  3     9     41      1    NA        0 FALSE FALSE  0.00
## L-BFGS-B     0  3     9     21     21    NA       52 FALSE FALSE  0.00
## spg          0  3     9   1077     NA     1        0 FALSE FALSE  0.05
## nlm          0  3     9     NA     NA     1        0 FALSE FALSE  0.00
</code>```

1a) This also works with optim where Nelder Mead is the default (or you could try constrOptim which explcitly supports inequality constraints).

```<code>optim(c(0, 3), f)
## $par
## [1] 0 3
##
## $value
## [1] 9
##
## $counts
## function gradient
##      187       NA

$convergence
[1] 0

$message
NULL
</code>```

2) Above we notice that the 2x^2 + 3y^2 <= 100 constraint is not active so we can drop it. Now since the objective function is increasing in both x and y independently it is obvious that we want to set both of them to their lower bounds so c(0, 3) is the answer.

If we want to use optimx anyways then we just use upper= and lower= arguments for those methods that use them.

```<code>f2 <- function(z, x = z[1], y = z[2]) 2*x+3*y
optimx(c(0, 3), f2, lower = c(0, 3), upper = c(3, Inf),
  method = c("L-BFGS-B", "spg", "nlm"))
##          p1 p2 value fevals gevals niter convcode  kkt1 kkt2 xtime
## L-BFGS-B  0  3     9      1      1    NA        0 FALSE   NA  0.00
## spg       0  3     9      1     NA     0        0 FALSE   NA  0.01
## nlminb    0  3     9      1      2     1        0 FALSE   NA  0.00
## Warning message:
## In BB::spg(par = par, fn = ufn, gr = ugr, lower = lower, upper = upper,  :
##   convergence tolerance satisified at intial parameter values.
</code>```

Body:
I'm trying to use optimx for a constrained nonlinear problem, but I just can't find an example online that I can adjust (I'm not an R programmer). I found that I should be using the below to test a few algorithms

optimx(par, fn, lower=low, upper=up, method=c("CG", "L-BFGS-B", "spg", "nlm"))

I understand par is just an example of a feasible solution. So, if I have two variables and (0,3) is feasible I can just do par <- c(0,3). If I want to minimise

2x+3y

subject to

2x^2 + 3y^2 <= 100
x<=3
-x<=0
-y<=-3

I guess i can set fn like

fn <- function(x){return 2*x[0]+3*x[1]}

but how do I set lower and upper for my constraints?

Many thanks!

Body:
1) We can incorporate the constraints within the objective function by returning a large number if any constraint is violated.

For most methods (but not Nelder Mead) the requirement is that the objective function be continuous and differentiable and requires a starting value in the interior of the feasible region, not the boundary. These requirements are not satisfied for f below but we will try it anyways.

library(optimx)

f <- function(z, x = z[1], y = z[2]) {
  if (2*x^2 + 3*y^2 <= 100 && x<=3 && -x<=0 && -y<=-3) 2*x+3*y else 1e10
}

optimx(c(0, 3), f, method = c("Nelder", "CG", "L-BFGS-B", "spg", "nlm"))
##             p1 p2 value fevals gevals niter convcode  kkt1  kkt2 xtime
## Nelder-Mead  0  3     9    187     NA    NA        0 FALSE FALSE  0.00
## CG           0  3     9     41      1    NA        0 FALSE FALSE  0.00
## L-BFGS-B     0  3     9     21     21    NA       52 FALSE FALSE  0.00
## spg          0  3     9   1077     NA     1        0 FALSE FALSE  0.05
## nlm          0  3     9     NA     NA     1        0 FALSE FALSE  0.00

1a) This also works with optim where Nelder Mead is the default (or you could try constrOptim which explcitly supports inequality constraints).

optim(c(0, 3), f)
## $par
## [1] 0 3
##
## $value
## [1] 9
##
## $counts
## function gradient
##      187       NA

$convergence
[1] 0

$message
NULL

2) Above we notice that the 2x^2 + 3y^2 <= 100 constraint is not active so we can drop it. Now since the objective function is increasing in both x and y independently it is obvious that we want to set both of them to their lower bounds so c(0, 3) is the answer.

If we want to use optimx anyways then we just use upper= and lower= arguments for those methods that use them.

f2 <- function(z, x = z[1], y = z[2]) 2*x+3*y
optimx(c(0, 3), f2, lower = c(0, 3), upper = c(3, Inf),
  method = c("L-BFGS-B", "spg", "nlm"))
##          p1 p2 value fevals gevals niter convcode  kkt1 kkt2 xtime
## L-BFGS-B  0  3     9      1      1    NA        0 FALSE   NA  0.00
## spg       0  3     9      1     NA     0        0 FALSE   NA  0.01
## nlminb    0  3     9      1      2     1        0 FALSE   NA  0.00
## Warning message:
## In BB::spg(par = par, fn = ufn, gr = ugr, lower = lower, upper = upper,  :
##   convergence tolerance satisified at intial parameter values.


来源: stackexchange

问:
Deployment Group and Environment in Azure devops
I want to understand the difference between environment and deployment group in Azure Devops.

And when should I use one and not the other?

Thanks

答:
Deployment Groups were the "old way" to do rolling deployment across multiple VMs. The new way is to use environments with the 'rolling' strategy from yaml.

My recommendation would be to let Deployment Groups lie and invest in Environments and YAML.

See:

https://learn.microsoft.com/en-us/azure/devops/pipelines/process/deployment-group-phases?view=azure-devops&tabs=yaml

ContentLicense: CC BY-SA 4.0


问:
How to simply download a JAR using Maven?
How do I download JAR during a build in Maven script? </p>

答:
Normally you don't use Maven for "just downloading", but for your build process. So normally, you do the following steps:

Define a new project by defining the archetype of your project and some needed properties.

Define as a dependency the library you want to use.

Run Maven with mvn compile

As a side effect, you will have downloaded the library to your local Maven repository. There are a lot of plugins to do something with dependencies, so have e.g. a look at the Maven Dependency plugin.

ContentLicense: CC BY-SA 3.0


问:
Configure reducers of connected-react-router and Redux Toolkit Query properly
I am trying to setup reducers of both connected-react-router and RTK Query.

(The old code base has connected-react-router already)

Then I received this error.

fail to setup connectRouter

```<code>Type 'Reducer<RouterState<unknown>, AnyAction>' is not assignable to type 'Reducer<unknown, AnyAction>'.
Types of parameters 'state' and 'state' are incompatible.
Type 'unknown' is not assignable to type 'RouterState<unknown>'.
</code>```

My "mockApi" is quite simple. "orderApi" is somewhat the same.

```<code>export const mockApi = createApi({
  reducerPath: "mockupPath",
  baseQuery: fetchBaseQuery({ baseUrl: "http://jsonplaceholder.typicode.com" }),
  endpoints: (builder) => ({
    getPost: builder.query<MockResonse, number>({
      query: (id) => `/posts/${id}`,
    }),
  }),
})
interface MockResonse { userId: number, id: number, title: string, body: string, }
</code>```

While using combineReducers produces no type error,

```<code>reducer: combineReducers({
  router: connectRouter(history),
  [mockApi.reducerPath]: mockApi.reducer,
}),
</code>```

but I lose the type of the store.

Knowing the type of the store is a huge advantage in development, so I'm trying to figure out how to solve the error.

May I know if I'm wrong somewhere?

答:
Seems like you can use Type Assertions here.

https://github.com/supasate/connected-react-router/issues/195

```<code>router: connectRouter(history) as Reducer,
</code>```

Body:
I am trying to setup reducers of both connected-react-router and RTK Query.

(The old code base has connected-react-router already)

Then I received this error.

fail to setup connectRouter

Type 'Reducer<RouterState<unknown>, AnyAction>' is not assignable to type 'Reducer<unknown, AnyAction>'.
Types of parameters 'state' and 'state' are incompatible.
Type 'unknown' is not assignable to type 'RouterState<unknown>'.

My "mockApi" is quite simple. "orderApi" is somewhat the same.

export const mockApi = createApi({
  reducerPath: "mockupPath",
  baseQuery: fetchBaseQuery({ baseUrl: "http://jsonplaceholder.typicode.com" }),
  endpoints: (builder) => ({
    getPost: builder.query<MockResonse, number>({
      query: (id) => `/posts/${id}`,
    }),
  }),
})
interface MockResonse { userId: number, id: number, title: string, body: string, }

While using combineReducers produces no type error,

reducer: combineReducers({
  router: connectRouter(history),
  [mockApi.reducerPath]: mockApi.reducer,
}),

but I lose the type of the store.

Knowing the type of the store is a huge advantage in development, so I'm trying to figure out how to solve the error.

May I know if I'm wrong somewhere?

Body:
Seems like you can use Type Assertions here.

https://github.com/supasate/connected-react-router/issues/195

router: connectRouter(history) as Reducer,


问:
How should I write test leavesIsCorrectWhenTreeIsPerfect() for a Binary search tree
I have implemented a Binary search tree and I have written a test class (in JUNIT testing) for it. All the test except for one test goes through. The test leavesIsCorrectWhenTreeIsPerfect() gets a message when I debug the code.

Expected: <4> but: was <5> . I do not know have to fix this.

Keep in mind that all the other tests goes through, and I do not think that it is a problem with the tree code.

How do you understand the description for the test?

```<code>/**
 * A Binary Search tree.
 */
public class Tree <T extends Comparable <T>> implements BinaryTree <T>{
    private int size;
    private Node root;
    public class Node{
        private Node Left;
        private Node Right;
        private T data;

        public Node(T data){
            this.data = data;
        }
    }
    public Tree (){
        size = 0;
        root = null;
    }

    /**
     * Test for presence of a value.
     * @param elem
     * @return true/false
     */
    @Override
    public boolean search(T elem) {
        if(root == null ||elem == null){
        return false;
        }
        Node node = root;
        while(true){
            if(node.data.compareTo(elem) > 0){
                if(node.Right == null){
                    return false;
                } else{
                    node = node.Right;
                }
            } else if(node.data.compareTo(elem) == 0){
                break;
            } else{
                if(node.Left== null){
                    return false;
                }
                else{
                    node = node.Left;
                }
            }
        }
        return true;
    }

    /**
     * Add value to tree; duplicates are not allowed.
     * Return true if the element is not already present (and is thus inserted),
     * false otherwise.
     *
     * @param elem
     * @return true/false
     */
    @Override
    public boolean insert(T elem) {
        if (elem == null){
            return false;
        }
        if (root == null){
            root = new Node(elem);
            size++;
            return true;
        }
        Node node = root;
        while (true){
            if (node.data.compareTo(elem) > 0) {
                if (node.Right == null){
                    node.Right = new Node(elem);
                    size++;
                    break;
                } else {
                    node = node.Right;
                }

            } else if (node.data.compareTo(elem) == 0) {
                return false;
            } else {
                if (node.Left == null){
                    node.Left = new Node(elem);
                    size++;
                    break;
                } else {
                    node = node.Left;
                }
            }
        }
        return true;
    }

    /**
     * The number of elements in the tree
     * @return size.
     */
    @Override
    public int size() {
        return size;
    }

    /**
     * The height of the tree.
     * The empty tree and the tree with only the root node both have height 0.
     * @return the height of the tree.
     */
    @Override
    public int height() {
        return countHeight(root);
    }
    /**
     * Helper method for height
     */
    private int countHeight(Node node){
        if(node == null) {
            return 0;
        }
        if (node.Left == null && node.Right == null) {
            return 0;
        }
        return 1 + Math.max(countHeight(node.Left), countHeight(node.Right));
    }

    /**
     * The number of leaves in the tree.
     * @return the amount of leaves the tree have.
     */
    @Override
    public int leaves() {
        return countLeaves(root);
    }
    /**
     * Helper method for leaves
     */
    private int countLeaves(Node node) {
        if (node == null) {
            return 0;
        }
        if (node.Left == null && node.Right == null) {
            return 1;
        }
        return countLeaves(node.Left) + countLeaves(node.Right);
    }

    /**
     * A string describing the tree
     * @return
     */
    public String toString(){
        String str = "[" + helpToString(root);
        if (str.length() > 1) {
            str = str.substring(0, str.length() - 2);
        } return str + "]";
    }

    /**
     * Helper method for toString
     */
    private String helpToString(Node node) {
        String str = "";
        if (node != null) {
            str += helpToString(node.Right);
            str += node.data + ", ";
            str += helpToString(node.Left);
        }
        return str;
      }
}

</code>```

Test class:

```<code>import org.junit.Test;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.Timeout;
import static org.junit.Assert.*;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import java.util.Arrays;
import java.util.stream.IntStream;
/**
 * Test class for a tree.
 */
public class TreeTest{
    @Rule public Timeout globalTimeout = Timeout.seconds(5);

    Tree<Integer> tree;
    int[] elementsInTree;
    int[] elementsNotInTree;

    @Before
    public void setUp() {
        /**
         * This tree should look like this:
         *
         *               8
         *             /  \
         *            3   10
         *           / \    \
         *          1   6    14
         *             / \   /
         *            4   7 13
         */
        tree = new Tree<>();
        elementsInTree = new int[] {8, 10, 14, 13, 3, 1, 6, 4, 7};
        for (int elem : elementsInTree) {
            tree.insert(elem);
        }
        elementsNotInTree = new int[] {34, -3, -10, 12, 74, 5};
    }

    @Test
    public void leavesIsTwoWhenPerfectTreeHasThreeNodes() {
        // Arrange
        Tree<Integer> tree = new Tree<>();
        // root must be smaller than one and larger than the other child
        tree.insert(1338); // root
        tree.insert(1337); // smaller child
        tree.insert(1396); // larger child

        // Act
        int numLeaves = tree.leaves();
        // Assert
        assertThat(numLeaves, equalTo(2));
    }

    @Test
    public void leavesIsCorrectWhenTreeIsPerfect() { //TEST
        // A perfect tree has all leaves at the same depth, and all internal nodes
        // (i.e. non-leaves) have two children
        //
        // This test should assert that a perfect tree with 2*n-1 nodes total,
        // has exactly n leaves (i.e. that Tree.leaves() returns n).
        //
        // An example is the perfect three-node tree from the test above:
        //
        //                        (1338)
        //                        /    \
        //                    (1337)  (1396)

        // You have to construct our own tree here, with n >= 4
        int n = 4;
        int nodes = 2*n-1;
       for(int i = 0; i < nodes ; i++) {
           tree.insert(i);
       }
         int leaves = tree.leaves();
         assertThat(leaves,equalTo(n));
    }

    @Test
    public void leavesIsOneWhenElementsWereInsertedInAscendingOrder() {
        // Arrange
        Tree<Integer> tree = new Tree<>();
        // insert elements in ascending order => all elements are inserted to the right
        int numElements = 100;
        for (int i = 0; i < numElements; i++) {
            tree.insert(i);
        }

        // Act
        int numLeaves = tree.leaves();
        // Assert
        assertThat(numLeaves, equalTo(1));
    }

    // Tests for height
    @Test
    public void heightIsZeroWhenTreeIsEmpty() {
        // Arrange
        Tree<Integer> emptyTree = new Tree<>();
        // Act
        int height = emptyTree.height();
        // Assert
        assertThat(height, equalTo(0));
    }

    @Test
    public void heightIsLogOfNumLeavesTreeIsPerfect() {
        // For a perfect tree, tree.height() == log2(tree.leaves()

        // Arrange
        Tree<Integer> tree = new Tree<>();
        int[] elements = new int[] {8, 3, 10, 1, 6, 9, 14};
        int numLeaves = 4;
        int logNumLeaves = (int) Math.round(Math.log(numLeaves) / Math.log(2));
        for (int elem : elements) {
            tree.insert(elem);
        }

        // Act
        int height = tree.height();
        // Assert
        assertThat(height, equalTo(logNumLeaves));
    }

    // Tests for insert/height
    @Test
    public void insertValuesInAscendingOrderIncrementsHeight() {
        // When inserting elements in ascending order, each element is inserted
        // to the right of the deepest node, so the height should increment by
        // 1 for each element inserted.
        Tree <Integer> tree = new Tree<>();
        int val = 100;
        for(int i = 0; i < val; i++){
            tree.insert(i);
        }
            int treeHeight = tree.height();
        treeHeight++;
            assertThat(val,equalTo(treeHeight));
    }
}

</code>```

答:
The leaves method counts the number of leaves that you have. Your expectation is that there will be four leaves. However, the result is 5. The method that you use in order to count the leaves appears to be correct:

```<code>    /**
     * Helper method for leaves
     */
    private int countLeaves(Node node) {
        if (node == null) {
            return 0;
        }
        if (node.Left == null && node.Right == null) {
            return 1;
        }
        return countLeaves(node.Left) + countLeaves(node.Right);
    }
</code>```

It essentially counts the items (in a breadth-first-search fashion) that have no children. What could be the reason? Your main thing to find out how your tree looks alike. Based on your insert method:

```<code>    @Override
    public boolean insert(T elem) {
        if (elem == null){
            return false;
        }
        if (root == null){
            root = new Node(elem);
            size++;
            return true;
        }
        Node node = root;
        while (true){
            if (node.data.compareTo(elem) > 0) {
                if (node.Right == null){
                    node.Right = new Node(elem);
                    size++;
                    break;
                } else {
                    node = node.Right;
                }

            } else if (node.data.compareTo(elem) == 0) {
                return false;
            } else {
                if (node.Left == null){
                    node.Left = new Node(elem);
                    size++;
                    break;
                } else {
                    node = node.Left;
                }
            }
        }
        return true;
    }
</code>```

and knowing that 2*n-1 in your test is 7, so the input numbers are 0, 1, 2, 3, 4, 5, 6, it seems to me that the tree could be

```<code>            0
           /
          1
         /
        2
       /
      3
     /
    4
   /
  5
 /
6
</code>```

which would have a single leaf, because if the node has a greater value than the item you are about to insert, then you add it to the node's right. However, the results of your test are different. For some reason you have 5 leaves. You would need to check the reason of that by first finding out how your table looks alike at the end and second by looking into the insert method with a debugger for this input.

Body:
I have implemented a Binary search tree and I have written a test class (in JUNIT testing) for it. All the test except for one test goes through. The test leavesIsCorrectWhenTreeIsPerfect() gets a message when I debug the code.

Expected: <4> but: was <5> . I do not know have to fix this.

Keep in mind that all the other tests goes through, and I do not think that it is a problem with the tree code.

How do you understand the description for the test?

/**
 * A Binary Search tree.
 */
public class Tree <T extends Comparable <T>> implements BinaryTree <T>{
    private int size;
    private Node root;
    public class Node{
        private Node Left;
        private Node Right;
        private T data;

        public Node(T data){
            this.data = data;
        }
    }
    public Tree (){
        size = 0;
        root = null;
    }

    /**
     * Test for presence of a value.
     * @param elem
     * @return true/false
     */
    @Override
    public boolean search(T elem) {
        if(root == null ||elem == null){
        return false;
        }
        Node node = root;
        while(true){
            if(node.data.compareTo(elem) > 0){
                if(node.Right == null){
                    return false;
                } else{
                    node = node.Right;
                }
            } else if(node.data.compareTo(elem) == 0){
                break;
            } else{
                if(node.Left== null){
                    return false;
                }
                else{
                    node = node.Left;
                }
            }
        }
        return true;
    }

    /**
     * Add value to tree; duplicates are not allowed.
     * Return true if the element is not already present (and is thus inserted),
     * false otherwise.
     *
     * @param elem
     * @return true/false
     */
    @Override
    public boolean insert(T elem) {
        if (elem == null){
            return false;
        }
        if (root == null){
            root = new Node(elem);
            size++;
            return true;
        }
        Node node = root;
        while (true){
            if (node.data.compareTo(elem) > 0) {
                if (node.Right == null){
                    node.Right = new Node(elem);
                    size++;
                    break;
                } else {
                    node = node.Right;
                }

            } else if (node.data.compareTo(elem) == 0) {
                return false;
            } else {
                if (node.Left == null){
                    node.Left = new Node(elem);
                    size++;
                    break;
                } else {
                    node = node.Left;
                }
            }
        }
        return true;
    }

    /**
     * The number of elements in the tree
     * @return size.
     */
    @Override
    public int size() {
        return size;
    }

    /**
     * The height of the tree.
     * The empty tree and the tree with only the root node both have height 0.
     * @return the height of the tree.
     */
    @Override
    public int height() {
        return countHeight(root);
    }
    /**
     * Helper method for height
     */
    private int countHeight(Node node){
        if(node == null) {
            return 0;
        }
        if (node.Left == null && node.Right == null) {
            return 0;
        }
        return 1 + Math.max(countHeight(node.Left), countHeight(node.Right));
    }

    /**
     * The number of leaves in the tree.
     * @return the amount of leaves the tree have.
     */
    @Override
    public int leaves() {
        return countLeaves(root);
    }
    /**
     * Helper method for leaves
     */
    private int countLeaves(Node node) {
        if (node == null) {
            return 0;
        }
        if (node.Left == null && node.Right == null) {
            return 1;
        }
        return countLeaves(node.Left) + countLeaves(node.Right);
    }

    /**
     * A string describing the tree
     * @return
     */
    public String toString(){
        String str = "[" + helpToString(root);
        if (str.length() > 1) {
            str = str.substring(0, str.length() - 2);
        } return str + "]";
    }

    /**
     * Helper method for toString
     */
    private String helpToString(Node node) {
        String str = "";
        if (node != null) {
            str += helpToString(node.Right);
            str += node.data + ", ";
            str += helpToString(node.Left);
        }
        return str;
      }
}

Test class:

import org.junit.Test;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.Timeout;
import static org.junit.Assert.*;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import java.util.Arrays;
import java.util.stream.IntStream;
/**
 * Test class for a tree.
 */
public class TreeTest{
    @Rule public Timeout globalTimeout = Timeout.seconds(5);

    Tree<Integer> tree;
    int[] elementsInTree;
    int[] elementsNotInTree;

    @Before
    public void setUp() {
        /**
         * This tree should look like this:
         *
         *               8
         *             /  \
         *            3   10
         *           / \    \
         *          1   6    14
         *             / \   /
         *            4   7 13
         */
        tree = new Tree<>();
        elementsInTree = new int[] {8, 10, 14, 13, 3, 1, 6, 4, 7};
        for (int elem : elementsInTree) {
            tree.insert(elem);
        }
        elementsNotInTree = new int[] {34, -3, -10, 12, 74, 5};
    }

    @Test
    public void leavesIsTwoWhenPerfectTreeHasThreeNodes() {
        // Arrange
        Tree<Integer> tree = new Tree<>();
        // root must be smaller than one and larger than the other child
        tree.insert(1338); // root
        tree.insert(1337); // smaller child
        tree.insert(1396); // larger child

        // Act
        int numLeaves = tree.leaves();
        // Assert
        assertThat(numLeaves, equalTo(2));
    }

    @Test
    public void leavesIsCorrectWhenTreeIsPerfect() { //TEST
        // A perfect tree has all leaves at the same depth, and all internal nodes
        // (i.e. non-leaves) have two children
        //
        // This test should assert that a perfect tree with 2*n-1 nodes total,
        // has exactly n leaves (i.e. that Tree.leaves() returns n).
        //
        // An example is the perfect three-node tree from the test above:
        //
        //                        (1338)
        //                        /    \
        //                    (1337)  (1396)

        // You have to construct our own tree here, with n >= 4
        int n = 4;
        int nodes = 2*n-1;
       for(int i = 0; i < nodes ; i++) {
           tree.insert(i);
       }
         int leaves = tree.leaves();
         assertThat(leaves,equalTo(n));
    }

    @Test
    public void leavesIsOneWhenElementsWereInsertedInAscendingOrder() {
        // Arrange
        Tree<Integer> tree = new Tree<>();
        // insert elements in ascending order => all elements are inserted to the right
        int numElements = 100;
        for (int i = 0; i < numElements; i++) {
            tree.insert(i);
        }

        // Act
        int numLeaves = tree.leaves();
        // Assert
        assertThat(numLeaves, equalTo(1));
    }

    // Tests for height
    @Test
    public void heightIsZeroWhenTreeIsEmpty() {
        // Arrange
        Tree<Integer> emptyTree = new Tree<>();
        // Act
        int height = emptyTree.height();
        // Assert
        assertThat(height, equalTo(0));
    }

    @Test
    public void heightIsLogOfNumLeavesTreeIsPerfect() {
        // For a perfect tree, tree.height() == log2(tree.leaves()

        // Arrange
        Tree<Integer> tree = new Tree<>();
        int[] elements = new int[] {8, 3, 10, 1, 6, 9, 14};
        int numLeaves = 4;
        int logNumLeaves = (int) Math.round(Math.log(numLeaves) / Math.log(2));
        for (int elem : elements) {
            tree.insert(elem);
        }

        // Act
        int height = tree.height();
        // Assert
        assertThat(height, equalTo(logNumLeaves));
    }

    // Tests for insert/height
    @Test
    public void insertValuesInAscendingOrderIncrementsHeight() {
        // When inserting elements in ascending order, each element is inserted
        // to the right of the deepest node, so the height should increment by
        // 1 for each element inserted.
        Tree <Integer> tree = new Tree<>();
        int val = 100;
        for(int i = 0; i < val; i++){
            tree.insert(i);
        }
            int treeHeight = tree.height();
        treeHeight++;
            assertThat(val,equalTo(treeHeight));
    }
}

Body:
The leaves method counts the number of leaves that you have. Your expectation is that there will be four leaves. However, the result is 5. The method that you use in order to count the leaves appears to be correct:

    /**
     * Helper method for leaves
     */
    private int countLeaves(Node node) {
        if (node == null) {
            return 0;
        }
        if (node.Left == null && node.Right == null) {
            return 1;
        }
        return countLeaves(node.Left) + countLeaves(node.Right);
    }

It essentially counts the items (in a breadth-first-search fashion) that have no children. What could be the reason? Your main thing to find out how your tree looks alike. Based on your insert method:

    @Override
    public boolean insert(T elem) {
        if (elem == null){
            return false;
        }
        if (root == null){
            root = new Node(elem);
            size++;
            return true;
        }
        Node node = root;
        while (true){
            if (node.data.compareTo(elem) > 0) {
                if (node.Right == null){
                    node.Right = new Node(elem);
                    size++;
                    break;
                } else {
                    node = node.Right;
                }

            } else if (node.data.compareTo(elem) == 0) {
                return false;
            } else {
                if (node.Left == null){
                    node.Left = new Node(elem);
                    size++;
                    break;
                } else {
                    node = node.Left;
                }
            }
        }
        return true;
    }

and knowing that 2*n-1 in your test is 7, so the input numbers are 0, 1, 2, 3, 4, 5, 6, it seems to me that the tree could be

            0
           /
          1
         /
        2
       /
      3
     /
    4
   /
  5
 /
6

which would have a single leaf, because if the node has a greater value than the item you are about to insert, then you add it to the node's right. However, the results of your test are different. For some reason you have 5 leaves. You would need to check the reason of that by first finding out how your table looks alike at the end and second by looking into the insert method with a debugger for this input.


问:
Pass data from a form component to another component in react hook
I have the following form, and I need that when submitting the form, its information is displayed in a new component.

Perhaps the issue of redirecting to the other component could be done by creating a route. But I don't know how said component obtains the information of the form

import {useState, useRef} from 'React'

export default const FormX = () => {
  const [formValues, setFormValues] = useState({
    name: "",
    priceUnitary: "",
    size: "",
    description: "",
  });

  const inputFileRef = useRef();

  const handleChange = (event) => {
    const { name, value } = event.target;
    console.log(name, value);

    setFormValues({ ...formValues, [name]: value });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(formValues);
    console.log(inputFileRef.current.files);
  };

  return (
    <>
      <form id="formu" onSubmit={handleSubmit} className="row">

FORM SEND

          Name
          <input
            placeholder="Text input"
            name="name"
            value={formValues.name}
            onChange={handleChange}
          />

          Size
          <input
            type="number"
            placeholder="Text input"
            name="size"
            value={formValues.size}
            onChange={handleChange}
          />

          Price Unitary
          <input
            type="number"
            placeholder="Text input"
            name="priceUnitary"
            value={formValues.priceUnitary}
            onChange={handleChange}
          />

          Description
          <input
            placeholder="Text input"
            name="description"
            value={formValues.description}
            onChange={handleChange}
          />

          File / Image
          <input type="file" ref={inputFileRef} />

        <button type="submit" className="color-primary">
          Save
        </button>
      </form>
    </>
  );
};```

Link:
https://codesandbox.io/s/send-form-dcj5v?file=/src/App.js

答:
You can hide your form by change your state on form sumbit and display another component. You have to pass formValue as props in View component. Now think you have better idea what you have to do...

Here i added new component, that display form value on submit

App.js

```<code>import { useState, useRef } from "react";
import View from "./View";

const FormX = () => {
    const [formValues, setFormValues] = useState({
      name: "",
      priceUnitary: "",
      size: "",
      description: ""
    });
    const [isFormVisible, setIsFormVisible] = useState(true);

    const inputFileRef = useRef();

    const handleChange = (event) => {
        const { name, value } = event.target;
        console.log(name, value);

        setFormValues({ ...formValues, [name]: value });
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        console.log(formValues);
        console.log(inputFileRef?.current?.files);
        setIsFormVisible(false);
    };

    return (
    <>
      {isFormVisible ? (
        <form id="formu" onSubmit={handleSubmit} className="row">
          <h1>FORM SEND</h1>
          <div className="col-md-6">
            <label>Name</label>
            <input
              placeholder="Text input"
              name="name"
              value={formValues?.name}
              onChange={handleChange}
            />
          </div>
          <div className="col-md-6">
            <label>Size</label>
            <input
              type="number"
              placeholder="Text input"
              name="size"
              value={formValues.size}
              onChange={handleChange}
            />
          </div>
          <div className="col-md-6">
            <label>Price Unitary</label>
            <input
              type="number"
              placeholder="Text input"
              name="priceUnitary"
              value={formValues.priceUnitary}
              onChange={handleChange}
            />
          </div>
          <div className="col-md-6">
            <label>Description</label>
            <input
              placeholder="Text input"
              name="description"
              value={formValues.description}
              onChange={handleChange}
            />
          </div>
          <div className="col-md-6">
            <label>File / Image</label>
            <input type="file" ref={inputFileRef} />
          </div>
          <button type="submit" className="color-primary">
            Save
          </button>
        </form>
      ) : (
        <View data={formValues} />
      )}
    </>
  );
};

export default FormX;
</code>```

View.js

```<code>import React from "react";

const View = ({ data }) => {
  return (
    <div>
      <p>Name: {data?.name}</p>
      <p>priceUnitary: {data?.priceUnitary}</p>
      <p>description: {data?.description}</p>
    </div>
  );
};

export default View;
</code>```

Body:
I have the following form, and I need that when submitting the form, its information is displayed in a new component.

Perhaps the issue of redirecting to the other component could be done by creating a route. But I don't know how said component obtains the information of the form

import {useState, useRef} from 'React'

export default const FormX = () => {
  const [formValues, setFormValues] = useState({
    name: "",
    priceUnitary: "",
    size: "",
    description: "",
  });

  const inputFileRef = useRef();

  const handleChange = (event) => {
    const { name, value } = event.target;
    console.log(name, value);

    setFormValues({ ...formValues, [name]: value });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(formValues);
    console.log(inputFileRef.current.files);
  };

  return (
    <>
      <form id="formu" onSubmit={handleSubmit} className="row">

FORM SEND

          Name
          <input
            placeholder="Text input"
            name="name"
            value={formValues.name}
            onChange={handleChange}
          />

          Size
          <input
            type="number"
            placeholder="Text input"
            name="size"
            value={formValues.size}
            onChange={handleChange}
          />

          Price Unitary
          <input
            type="number"
            placeholder="Text input"
            name="priceUnitary"
            value={formValues.priceUnitary}
            onChange={handleChange}
          />

          Description
          <input
            placeholder="Text input"
            name="description"
            value={formValues.description}
            onChange={handleChange}
          />

          File / Image
          <input type="file" ref={inputFileRef} />

        <button type="submit" className="color-primary">
          Save
        </button>
      </form>
    </>
  );
};

Link:
https://codesandbox.io/s/send-form-dcj5v?file=/src/App.js

Body:
You can hide your form by change your state on form sumbit and display another component. You have to pass formValue as props in View component. Now think you have better idea what you have to do...

Here i added new component, that display form value on submit

App.js

import { useState, useRef } from "react";
import View from "./View";

const FormX = () => {
    const [formValues, setFormValues] = useState({
      name: "",
      priceUnitary: "",
      size: "",
      description: ""
    });
    const [isFormVisible, setIsFormVisible] = useState(true);

    const inputFileRef = useRef();

    const handleChange = (event) => {
        const { name, value } = event.target;
        console.log(name, value);

        setFormValues({ ...formValues, [name]: value });
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        console.log(formValues);
        console.log(inputFileRef?.current?.files);
        setIsFormVisible(false);
    };

    return (
    <>
      {isFormVisible ? (
        <form id="formu" onSubmit={handleSubmit} className="row">
          <h1>FORM SEND</h1>
          <div className="col-md-6">
            <label>Name</label>
            <input
              placeholder="Text input"
              name="name"
              value={formValues?.name}
              onChange={handleChange}
            />
          </div>
          <div className="col-md-6">
            <label>Size</label>
            <input
              type="number"
              placeholder="Text input"
              name="size"
              value={formValues.size}
              onChange={handleChange}
            />
          </div>
          <div className="col-md-6">
            <label>Price Unitary</label>
            <input
              type="number"
              placeholder="Text input"
              name="priceUnitary"
              value={formValues.priceUnitary}
              onChange={handleChange}
            />
          </div>
          <div className="col-md-6">
            <label>Description</label>
            <input
              placeholder="Text input"
              name="description"
              value={formValues.description}
              onChange={handleChange}
            />
          </div>
          <div className="col-md-6">
            <label>File / Image</label>
            <input type="file" ref={inputFileRef} />
          </div>
          <button type="submit" className="color-primary">
            Save
          </button>
        </form>
      ) : (
        <View data={formValues} />
      )}
    </>
  );
};

export default FormX;

View.js

import React from "react";

const View = ({ data }) => {
  return (
    <div>
      <p>Name: {data?.name}</p>
      <p>priceUnitary: {data?.priceUnitary}</p>
      <p>description: {data?.description}</p>
    </div>
  );
};

export default View;


问:
How to find multiple elements in a list using linear search
I have three parallel arrays product, store and price. The program should ask for the product and store name and then display all the prices against that product and store. I have the following code but it's stopped displaying price once it's found the first value in the sorted price list. Is there any way to search for more than one value from the list? Here is my code.

```<code>product = ["Milk","Peanut","Onions","Milk","Onions","Cheese","Potatoes","Cheese"]
store = ["Axep","Dominion","Fortions","Axep","Extra Foods","Loblow","Axep","Loblow"]
price = [2,2,4,10,10,10,17,23]

def search(product,store,price):

  enterProduct = input("Enter product: ")
  enterStore = input("Enter store: ")

  counter = 0
  position = 0
  found = False

  while counter < len(price) and found == False:
    if product[counter] == enterProduct and store[counter] == enterStore:
      found = True
      position = counter

    counter = counter + 1

    if found == True:
      print(f"The price for {product[position]} in {store[position]} are {price[position]}")

def main():

  search(product,store,price)

main()
</code>```

Here is the output:

```<code>Enter product: Milk
Enter store: Axep
The price for Milk in Axep are 2
</code>```

which should be:

```<code>The price for Milk in Axep are:
2
10
</code>```

答:
You could use this code to get the exact functionality you want:

```<code>product = ["Milk", "Peanut", "Onions", "Milk", "Onions", "Cheese", "Potatoes", "Cheese"]
store = ["Axep", "Dominion", "Fortions", "Axep", "Extra Foods", "Loblow", "Axep", "Loblow"]
price = [2, 2, 4, 10, 10, 10, 17, 23]

pr = input("Enter product: ")
st = input("Enter store: ")
print(f"The price for {pr} in {st} are:")
[print(m) for (p, s, m) in zip(product, store, price) if (pr, st) == (p, s)]
</code>```

output:

```<code>Enter product: Milk
Enter store: Axep
The price for Milk in Axep are:
2
10
</code>```

You could also look into pandas DataFrames as a overall better solution.
official docs
GeeksForGeeks

Body:
I have three parallel arrays product, store and price. The program should ask for the product and store name and then display all the prices against that product and store. I have the following code but it's stopped displaying price once it's found the first value in the sorted price list. Is there any way to search for more than one value from the list? Here is my code.

product = ["Milk","Peanut","Onions","Milk","Onions","Cheese","Potatoes","Cheese"]
store = ["Axep","Dominion","Fortions","Axep","Extra Foods","Loblow","Axep","Loblow"]
price = [2,2,4,10,10,10,17,23]

def search(product,store,price):

  enterProduct = input("Enter product: ")
  enterStore = input("Enter store: ")

  counter = 0
  position = 0
  found = False

  while counter < len(price) and found == False:
    if product[counter] == enterProduct and store[counter] == enterStore:
      found = True
      position = counter

    counter = counter + 1

    if found == True:
      print(f"The price for {product[position]} in {store[position]} are {price[position]}")

def main():

  search(product,store,price)

main()

Here is the output:

Enter product: Milk
Enter store: Axep
The price for Milk in Axep are 2

which should be:

The price for Milk in Axep are:
2
10

Body:
You could use this code to get the exact functionality you want:

product = ["Milk", "Peanut", "Onions", "Milk", "Onions", "Cheese", "Potatoes", "Cheese"]
store = ["Axep", "Dominion", "Fortions", "Axep", "Extra Foods", "Loblow", "Axep", "Loblow"]
price = [2, 2, 4, 10, 10, 10, 17, 23]

pr = input("Enter product: ")
st = input("Enter store: ")
print(f"The price for {pr} in {st} are:")
[print(m) for (p, s, m) in zip(product, store, price) if (pr, st) == (p, s)]

output:

Enter product: Milk
Enter store: Axep
The price for Milk in Axep are:
2
10

You could also look into pandas DataFrames as a overall better solution.
official docs
GeeksForGeeks


问:
How can I compile TypeScript within a JavaScript app?
I have a build.js file which, as you may have guessed, builds my project. This file aims to:

Compile .ts files and place them into a new directory.

Create an asar containing the compiled files.

Because typescript (tsc) is an NPM package, I figured I might be able to use it inside of a JavaScript file, in the same way I can use the asar package. I was right; I can use the typescript package as a regular Node.JS module, however, I do not know how to use it, and ESLint doesn't help me out too much.

Here's my current build.js:

const typescript = require("typescript");
```

I cannot find any documentation for this, all I want to do is replicate what tsc . would do.

EDIT: I do not want to use child_process, because it creates new issues, especially when it comes to cross-compatibility and safety.

答:
You can use child process to spawn a shell and run the tsc command or use the exec() to spawn the shell first then run the command

https://www.geeksforgeeks.org/node-js-child-process/

You can achieve this with something like

const { exec } = require('child_process');
exec('tsc', (error, stdout, stderr) => {
  if (error) {
    console.error(`exec error: ${error}`);
    return;
  }
console.log(stdout);
  if (stderr!= "")
  console.error(`stderr: ${stderr}`);
});
```

Body:
I have a build.js file which, as you may have guessed, builds my project. This file aims to:

Compile .ts files and place them into a new directory.

Create an asar containing the compiled files.

Because typescript (tsc) is an NPM package, I figured I might be able to use it inside of a JavaScript file, in the same way I can use the asar package. I was right; I can use the typescript package as a regular Node.JS module, however, I do not know how to use it, and ESLint doesn't help me out too much.

Here's my current build.js:

const typescript = require("typescript");

I cannot find any documentation for this, all I want to do is replicate what tsc . would do.

EDIT: I do not want to use child_process, because it creates new issues, especially when it comes to cross-compatibility and safety.


问:
Save Theme Primary Color and Theme Brightness, and load on startup Flutter
I am using this code to switch between light mode and dark mode and choose the primary color.
Works well, but it doesn't save nor load on app restart. How to fix that?</p>

答:
You can save user's option in his device using package localstorage.

Init localstorage somewhere (in global state) with

```<code>final storage = new LocalStorage('my_data.json');
</code>```

in main() func check if your storage ready to work with

```<code>void main() async {
await storage.ready;
runApp(App());
}

</code>```

Set data with

```<code>const String themeKey = 'theme'; // or any key you want
await storage.setItem(themeKey , 'light'); // or 'dark' or any value you want

</code>```

You can put that in Provider consturctor:

```<code>class ThemeProvider with ChangeNotifier {
ThemeProvider({this.selectedThemeMode});
  ThemeMode selectedThemeMode;
///....
}
</code>```

And  put in it like that:

```<code>final savedTheme = storage.getItem(themeKey);
    ThemeMode selectedThemeMode = appThemes[0].mode;

swtich(savedTheme) {
    case 'ligth':
    selectedThemeMode = appThemes[0].mode;
    /// other cases
    }

return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (_) => ThemeProvider(selectedThemeMode: selectedThemeMode),
        ),
// ....
</code>```

and use that value to specify choosed theme.

Body:
You can save user's option in his device using package localstorage.

Init localstorage somewhere (in global state) with

final storage = new LocalStorage('my_data.json');

in main() func check if your storage ready to work with

void main() async {
await storage.ready;
runApp(App());
}

Set data with

const String themeKey = 'theme'; // or any key you want
await storage.setItem(themeKey , 'light'); // or 'dark' or any value you want

You can put that in Provider consturctor:

class ThemeProvider with ChangeNotifier {
ThemeProvider({this.selectedThemeMode});
  ThemeMode selectedThemeMode;
///....
}

And  put in it like that:

final savedTheme = storage.getItem(themeKey);
    ThemeMode selectedThemeMode = appThemes[0].mode;

swtich(savedTheme) {
    case 'ligth':
    selectedThemeMode = appThemes[0].mode;
    /// other cases
    }

return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (_) => ThemeProvider(selectedThemeMode: selectedThemeMode),
        ),
// ....

and use that value to specify choosed theme.


问:
How to Append a table with specified data from Google Spreadsheet to Google Doc using Google App Script?
As title, I've tried to append a table to Google Docs from Google Spreadsheet using GAS. So far, the post and some scripts I can find is about appending the whole sheet, not the selected or specified row or column. Below is the snippet. What should I do to make the snippet meet my need? Please advice.

p.s. the exception message:
Exception: The parameters (number[]) don't match the method signature for DocumentApp.Body.appendTable. would pop up after i execute the script.

```<code>function get_insertion_and_deletion_value(fileID)
{
  var url="MY URL";
  var SpreadSheet = SpreadsheetApp.openByUrl(url);
  var  ss = SpreadSheet.getSheetByName("LOG");
  var values = ss.getDataRange().getValues();
  var reportHeader = "Report Header";
  var ad= DocumentApp.openById("MY ID");
  var body = ad.getBody();
  var info_table=[];
  for(var i=0, iLen=values.length; i<iLen; i++)
  {
    if(values[i][0]=="MYID")
    {
      var delete_string=ss.getRange(i+1,3).getValue();
      var insert_string=ss.getRange(i+1,7).getValue();
      var error_type=ss.getRange(i+1,13).getValue();
      var correction_content=ss.getRange(i+1,14).getValue();
      info_table.push(ss.getRange(i+1,3).getValue(),ss.getRange(i+1,7).getValue(),ss.getRange(i+1,13).getValue(),ss.getRange(i+1,14).getValue())
    }
  }
  body.insertParagraph(0, reportHeader).setHeading(DocumentApp.ParagraphHeading.HEADING1);
  table = body.appendTable(info_table);

  var tableHeader = table.getRow(0);
  tableHeader.editAsText().setBold(true).setForegroundColor('#ffffff');
  var getCells = tableHeader.getNumCells();

  for(var i = 0; i < getCells; i++)
  {
    tableHeader.getCell(i).setBackgroundColor('#BBB9B9');
  }

   return info_table;
}

</code>```

答:
Might I suggest you change your for loop as shown. I deleted the unused variables.  1st your need to construct rows just like Spreadsheet setValues() so I've enclosed the list of values within [].  2nd you already have the values so all these ss.getRange(i+1,3).getValue() are redundant and cause another call to the server.  Remember column 3 is index 2 in the values array.  So I've just used the values you got from getDataRange().getValues().</p>
```<code>for(var i=0, iLen=values.length; i<iLen; i++)
{
  if(values[i][0]=="MYID")
  {
    info_table.push([values[i][2],values[i][6],values[i][12],values[i][13]]);
  }
}
</code>```

Body:
As title, I've tried to append a table to Google Docs from Google Spreadsheet using GAS. So far, the post and some scripts I can find is about appending the whole sheet, not the selected or specified row or column. Below is the snippet. What should I do to make the snippet meet my need? Please advice.

p.s. the exception message:
Exception: The parameters (number[]) don't match the method signature for DocumentApp.Body.appendTable. would pop up after i execute the script.

function get_insertion_and_deletion_value(fileID)
{
  var url="MY URL";
  var SpreadSheet = SpreadsheetApp.openByUrl(url);
  var  ss = SpreadSheet.getSheetByName("LOG");
  var values = ss.getDataRange().getValues();
  var reportHeader = "Report Header";
  var ad= DocumentApp.openById("MY ID");
  var body = ad.getBody();
  var info_table=[];
  for(var i=0, iLen=values.length; i<iLen; i++)
  {
    if(values[i][0]=="MYID")
    {
      var delete_string=ss.getRange(i+1,3).getValue();
      var insert_string=ss.getRange(i+1,7).getValue();
      var error_type=ss.getRange(i+1,13).getValue();
      var correction_content=ss.getRange(i+1,14).getValue();
      info_table.push(ss.getRange(i+1,3).getValue(),ss.getRange(i+1,7).getValue(),ss.getRange(i+1,13).getValue(),ss.getRange(i+1,14).getValue())
    }
  }
  body.insertParagraph(0, reportHeader).setHeading(DocumentApp.ParagraphHeading.HEADING1);
  table = body.appendTable(info_table);

  var tableHeader = table.getRow(0);
  tableHeader.editAsText().setBold(true).setForegroundColor('#ffffff');
  var getCells = tableHeader.getNumCells();

  for(var i = 0; i < getCells; i++)
  {
    tableHeader.getCell(i).setBackgroundColor('#BBB9B9');
  }

   return info_table;
}

Body:
Might I suggest you change your for loop as shown. I deleted the unused variables.  1st your need to construct rows just like Spreadsheet setValues() so I've enclosed the list of values within [].  2nd you already have the values so all these ss.getRange(i+1,3).getValue() are redundant and cause another call to the server.  Remember column 3 is index 2 in the values array.  So I've just used the values you got from getDataRange().getValues().

for(var i=0, iLen=values.length; i<iLen; i++)
{
  if(values[i][0]=="MYID")
  {
    info_table.push([values[i][2],values[i][6],values[i][12],values[i][13]]);
  }
}


问:
AWS ECS Fargate Outbound Internet Connectivity
I've a small Fargate cluster with a service running and found that if I disable the public IP the container won't build as it doesn't have a route to pull the image.

The ELB for ECS Fargate is part of a subnet which has:

internet gateway configured and attached

route table allowing unrestricted outgoing

security policy on the ECS service allows unrestricted outgoing

DNS enabled

My understanding is the internet gateway is a NAT and the above actions should permit outgoing internet access however I can't make it so. What else is missing?

答:
Just like all other resources in your AWS VPC, if you don't attach a public IP address, then it needs either to be placed in a subnet with a route to a NAT Gateway to access things outside the VPC, or it needs VPC endpoints to access those resources.

I have set-up a EBL for a persistent public & subnet IP. As far as I
can tell my subnet has outgoing internet unrestricted (internet
gateway attached and route opens up all outgoing traffic to 0.0.0.0/0.
I'm unsure if the service setup will configure the EC2 to use this
first then attempt to set-up the container. If not then it probably
doesn't apply.

ELB is for inbound traffic only, it does not provide any sort of outbound networking functionality for your EC2 or Fargate instance. The ELB is not in any way involved when ECS tries to pull a container image.

Having a volatile public IP address is a bit annoying as my
understanding is the security policy will apply to both the
ELB/Elastic provided IP and this one.

What "security policy" are you referring to? I'm not aware of security policies on AWS that are applied directly to IP addresses. Assuming you mean the Security Group when you say "security policy", your understanding is incorrect. Both the EC2 or Fargate instance and the ELB should have different security groups assigned to them. The ELB would have a security group allowing all inbound traffic, if you want it to be public on the Internet. The EC2 or Fargate instance should have a security group only allowing inbound traffic from the ELB (by specifying the ELB's security group ID in the inbound rule).

I want to point out you say "EC2" in your question and never mention Fargate, but you tagged your question with Fargate twice and didn't tag it with EC2. EC2 and Fargate are separate compute services on AWS. You would either be using one or the other. It doesn't really matter in this case given the issue you are encountering, but it helps to be clear in your questions.


问:
Missing Android platform(s) detected
After trying to gradle sync... it fails and says in the messages dialog box

```<code>Missing Android platform(s) detected: 'android-26' Install missing platform(s)
and sync project
</code>```

when im clicking Install missing platform(s) and sync project a progress bar window pops up which says Downloading and when reaching about half way it just closes and nothing happens
ive installed api 26 from the settings and tried uninstall and install again.

答:
This is the solution I found by watching this video.

Link - Find the missed Image Asset in Android studio

Steps to be taken(Assuming You are working on Android, but It worked for me working on flutter as well)

Open the PARENT android project in a new Android Studio Window. Open the Android project in a new Window

Search for the Android root folder. Let the Gradle Sync run for some time

Try again, right clicking the res folder. This time it will come up.

Core Problem - It is an Issue with the Gradle sync not done properly, but with the above approach we forced Android Studio to resync it.

Title: Missing Android platform(s) detected

Body:
After trying to gradle sync... it fails and says in the messages dialog box

Missing Android platform(s) detected: 'android-26' Install missing platform(s)
and sync project

when im clicking Install missing platform(s) and sync project a progress bar window pops up which says Downloading and when reaching about half way it just closes and nothing happens
ive installed api 26 from the settings and tried uninstall and install again.


问:
Informatica. How to reject whole source file if source and target have duplicates
I have a mapping which compares target with source. In expression there is a condition which checks if there are duplicates. How can I stop whole data flow if condition returns true? DD_Reject does not work as it only rejects one record.</p>

答:
To stop the flow use the available Expression Transformation ABORT function. This will NOT rollback the already process rows though. If you need that as well, then two sessions will be needed, one to check the duplicates, another to perform the actual load, linked with SUCCEEDED condition.

```<code>Start -> s_check_duplicates -succeeded-> s_load_data
</code>```

Body:
To stop the flow use the available Expression Transformation ABORT function. This will NOT rollback the already process rows though. If you need that as well, then two sessions will be needed, one to check the duplicates, another to perform the actual load, linked with SUCCEEDED condition.

Start -> s_check_duplicates -succeeded-> s_load_data


问:
equivalent of audioPlayer.isPlaying() in AudioKit
I am using the AudioKit's AudioPlayer!.  My earlier version of the code had
audioPlayer.isPlaying flag to check if the player is still playing or paused/stopped. Now that isPlaying flag has been removed, can someone please guide me on what is the equivalent code?

thanks,
-Vittal

答:
Try isStarted

From AudioPlayer+Playback:

```<code>/// Synonym for isPlaying
public var isStarted: Bool { status == .playing }
</code>```

Body:
Try isStarted

From AudioPlayer+Playback:

/// Synonym for isPlaying
public var isStarted: Bool { status == .playing }


问:
Swift UI Scroll View: Set frame for drag indicator
I have following problem. I want to create a vertical ScrollView with many rows. At the bottom of the view I have an info bar which appears over the scroll view because I put all the items in a ZStack. Here is my code and what it produces:

struct ProblemView: View {

    var body: some View {
        ZStack {
            ScrollView(.vertical, showsIndicators: true) {

                VStack {
                    ForEach(0..<100, id:\.self) {i in
                        HStack {
                            Text("Text \(i)")
                                .foregroundColor(.red)
                            Spacer()
                            Image(systemName: "plus")
                                .foregroundColor(.blue)
                        }
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .padding()
                        Divider()

                    }
                }
            }

            VStack {
                Spacer()
                HStack {
                    Text("Some Info here")
                    Image(systemName: "info.circle")
                        .foregroundColor(.blue)
                }
                .padding()
                .frame(maxWidth: .infinity)
                .ignoresSafeArea()
                .background(.ultraThinMaterial)

            }

        }
    }

}

struct ProblemView_Previews: PreviewProvider {
    static var previews: some View {
        ProblemView()
    }
}
```

As you can see the drag indicator is hidden behind the info frame. Also the last item can't be seen because it is also behind the other frame. What

I want is that the drag indicator stops at this info frame. Why am I using a ZStack and not just a VStack? I want that this opacity effect behind the info frame, you get when you scroll.

答:
We cannot control offset of indicator, but we can make all needed views visible by injecting last empty view with the same height (calculated dynamically) as info panel.

Here is possible approach. Tested with Xcode 13.2 / iOS 15.2

```<code>struct ProblemView: View {
    @State private var viewHeight = CGFloat.zero

    var body: some View {
        ZStack {
            ScrollView(.vertical, showsIndicators: true) {

                VStack {
                    ForEach(0..<100, id:\.self) {i in
                        HStack {
                            Text("Text \(i)")
                                .foregroundColor(.red)
                            Spacer()
                            Image(systemName: "plus")
                                .foregroundColor(.blue)
                        }
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .padding()
                        Divider()

                    }
                    Color.clear
                        .frame(minHeight: viewHeight)     // << here !!
                }
            }

            VStack {
                Spacer()
                HStack {
                    Text("Some Info here")
                    Image(systemName: "info.circle")
                        .foregroundColor(.blue)
                }
                .padding()
                .frame(maxWidth: .infinity)
                .ignoresSafeArea()
                .background(.ultraThinMaterial)
                .background(GeometryReader {
                    Color.clear.preference(key: ViewHeightKey.self,
                                           value: $0.frame(in: .local).size.height)
                })

            }

        }
        .onPreferenceChange(ViewHeightKey.self) {
            self.viewHeight = $0
        }
    }
}

struct ViewHeightKey: PreferenceKey {
    static var defaultValue: CGFloat { 0 }
    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
        value = value + nextValue()
    }
}
</code>```

Body:
I have following problem. I want to create a vertical ScrollView with many rows. At the bottom of the view I have an info bar which appears over the scroll view because I put all the items in a ZStack. Here is my code and what it produces:

struct ProblemView: View {

    var body: some View {
        ZStack {
            ScrollView(.vertical, showsIndicators: true) {

                VStack {
                    ForEach(0..<100, id:\.self) {i in
                        HStack {
                            Text("Text \(i)")
                                .foregroundColor(.red)
                            Spacer()
                            Image(systemName: "plus")
                                .foregroundColor(.blue)
                        }
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .padding()
                        Divider()

                    }
                }
            }

            VStack {
                Spacer()
                HStack {
                    Text("Some Info here")
                    Image(systemName: "info.circle")
                        .foregroundColor(.blue)
                }
                .padding()
                .frame(maxWidth: .infinity)
                .ignoresSafeArea()
                .background(.ultraThinMaterial)

            }

        }
    }

}

struct ProblemView_Previews: PreviewProvider {
    static var previews: some View {
        ProblemView()
    }
}

As you can see the drag indicator is hidden behind the info frame. Also the last item can't be seen because it is also behind the other frame. What

I want is that the drag indicator stops at this info frame. Why am I using a ZStack and not just a VStack? I want that this opacity effect behind the info frame, you get when you scroll.

Body:
We cannot control offset of indicator, but we can make all needed views visible by injecting last empty view with the same height (calculated dynamically) as info panel.

Here is possible approach. Tested with Xcode 13.2 / iOS 15.2

struct ProblemView: View {
    @State private var viewHeight = CGFloat.zero

    var body: some View {
        ZStack {
            ScrollView(.vertical, showsIndicators: true) {

                VStack {
                    ForEach(0..<100, id:\.self) {i in
                        HStack {
                            Text("Text \(i)")
                                .foregroundColor(.red)
                            Spacer()
                            Image(systemName: "plus")
                                .foregroundColor(.blue)
                        }
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .padding()
                        Divider()

                    }
                    Color.clear
                        .frame(minHeight: viewHeight)     // << here !!
                }
            }

            VStack {
                Spacer()
                HStack {
                    Text("Some Info here")
                    Image(systemName: "info.circle")
                        .foregroundColor(.blue)
                }
                .padding()
                .frame(maxWidth: .infinity)
                .ignoresSafeArea()
                .background(.ultraThinMaterial)
                .background(GeometryReader {
                    Color.clear.preference(key: ViewHeightKey.self,
                                           value: $0.frame(in: .local).size.height)
                })

            }

        }
        .onPreferenceChange(ViewHeightKey.self) {
            self.viewHeight = $0
        }
    }
}

struct ViewHeightKey: PreferenceKey {
    static var defaultValue: CGFloat { 0 }
    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
        value = value + nextValue()
    }
}


问:
How can I autopopulate selection list in javascript?
I would like to auto populate my HTML table with drop down list.

I used below code, but the problem is, I need to specify 24 option to this drop down list, and if I would like add all 24, this line will be extremly long.

Can I ask if there is any way to solve it a bit shorter code and better way?

List:

AC Propulsion

Ajax

AM General

Ambassador

AMC

American

American Underslung

Anteros Coachworks

Apollo

Apperson

Arnolt

Auburn

Aurica Motors

Avanti

Brewster

Brisco

Brush

BXR

Carroll Shelby

Case

Chadwick

Chandler

Checker

Comet

```<code>row2.insertCell(count + 1).innerHTML = '<select id="' + count2 + '"' + 'name="cars"><option value="volvo">Volvo</option><option value="saab">Saab</option></select>'
</code>```

答:
Try store them in an array and use template literal to loop over it:

```<code>let list = [AC Propulsion,Ajax,AM General,Ambassador,AMC,American,American, Underslung,Anteros Coachworks, Apollo,Apperson,Arnolt,Auburn,Aurica,Motors,Avanti,Brewster,Brisco,Brush,BXR,Carroll,Shelby,Case,Chadwick,Chandler,Checker,Comet]

row2.insertCell(count + 1).innerHTML = '<select id="sec"></select>'
list.forEach(item=>{
    document.querySelector('#sec').innerHTML +=`<option value=${item}>${item}</option>`
})
</code>```

If you want to make value lower case, just use:

```<code>let list = [AC Propulsion,Ajax,AM General,Ambassador,AMC,American,American, Underslung,Anteros Coachworks, Apollo,Apperson,Arnolt,Auburn,Aurica,Motors,Avanti,Brewster,Brisco,Brush,BXR,Carroll,Shelby,Case,Chadwick,Chandler,Checker,Comet]

row2.insertCell(count + 1).innerHTML = '<select id="sec"></select>'
list.forEach(item=>{
    document.querySelector('#sec').innerHTML +=`<option value=${item.toLowerCase()}>${item}</option>`
})
</code>```

Body:
I would like to auto populate my HTML table with drop down list.

I used below code, but the problem is, I need to specify 24 option to this drop down list, and if I would like add all 24, this line will be extremly long.

Can I ask if there is any way to solve it a bit shorter code and better way?

List:

AC Propulsion

Ajax

AM General

Ambassador

AMC

American

American Underslung

Anteros Coachworks

Apollo

Apperson

Arnolt

Auburn

Aurica Motors

Avanti

Brewster

Brisco

Brush

BXR

Carroll Shelby

Case

Chadwick

Chandler

Checker

Comet

row2.insertCell(count + 1).innerHTML = '<select id="' + count2 + '"' + 'name="cars"><option value="volvo">Volvo</option><option value="saab">Saab</option></select>'

Body:
Try store them in an array and use template literal to loop over it:

let list = [AC Propulsion,Ajax,AM General,Ambassador,AMC,American,American, Underslung,Anteros Coachworks, Apollo,Apperson,Arnolt,Auburn,Aurica,Motors,Avanti,Brewster,Brisco,Brush,BXR,Carroll,Shelby,Case,Chadwick,Chandler,Checker,Comet]

row2.insertCell(count + 1).innerHTML = '<select id="sec"></select>'
list.forEach(item=>{
    document.querySelector('#sec').innerHTML +=`<option value=${item}>${item}</option>`
})

If you want to make value lower case, just use:

let list = [AC Propulsion,Ajax,AM General,Ambassador,AMC,American,American, Underslung,Anteros Coachworks, Apollo,Apperson,Arnolt,Auburn,Aurica,Motors,Avanti,Brewster,Brisco,Brush,BXR,Carroll,Shelby,Case,Chadwick,Chandler,Checker,Comet]

row2.insertCell(count + 1).innerHTML = '<select id="sec"></select>'
list.forEach(item=>{
    document.querySelector('#sec').innerHTML +=`<option value=${item.toLowerCase()}>${item}</option>`
})


问:
GCP GCS (Google Cloud Storage) object-level retention policy
Is it possible to define retention policy for individual file in a GCS bucket?

For example, if the bucket is set to have minimum retention of 1 year:

Is it possible for "file A" retention policy set to 2 years and "file B" set to 5 years?

If yes, is it done using prefixes (like AWS S3)? Can I immediately set to x number of year for the file?

答:
GCS allows for object holds on individual objects. These are metatdata flags set on the object that force retention (no deletes or modifications) regardless of the bucket policy, and must be manually removed in the future.

There are 2 types:

Event-based holds will start the retention countdown clock once the hold is removed.

Temporary holds have no effect on the retention countdown so it starts when the object is first created.


问:
How to show selected date inside the button ---- Date picker -- Flutter
I have built a date picker where users can select the date and I want to update the selected date inside the elevated button, but when the date is updated it also starts showing the time inside the elevated button
Also, I want to keep the same format of date, I have specified above in the code
I am providing my code and snapshots

```<code>[class CashInCashOut extends StatefulWidget {
  const CashInCashOut({Key? key}) : super(key: key);

  @override
  _CashInCashOutState createState() => _CashInCashOutState();
}

class _CashInCashOutState extends State<CashInCashOut> {
  DateTime date = DateTime.now();
  late var formattedDate = DateFormat('d-MMM-yy').format(date);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("Cash Out"),
        ),
        body: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            children: \[
              const TextField(
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(labelText: "Amount"),
              ),
              const TextField(
                decoration: InputDecoration(labelText: "Detail (optional)"),
              ),
              Row(
                children: \[
                  ElevatedButton(
                    child: Text(formattedDate),
                    onPressed: () async {
                      DateTime? _newDate = await showDatePicker(
                        context: context,
                        initialDate: date,
                        firstDate: DateTime(2022),
                        lastDate: DateTime(2030),
                      );
                      setState(() {
                        if (_newDate == null) {
                          return;
                        } else {
                          formattedDate = _newDate.toString();
                        }
                      });
                    },
                  ),
                  const Spacer(),
                  ReusableButton(text: "Add bills"),
                \],
              ),
            \],
          ),
        ));
  }
}
</code>```

state of my application before selecting date

state of my application after selecting the date from date picker

答:
You should format the date when the button is pressed. Just replace this code portion with yours:

```<code>if (_newDate == null) {
    return
} else {
    formattedDate = DateFormat.yMd().format(_newDate);
}
</code>```

Note: You can change date format according to what you want. Just change yMd to any other format you want. Hover over DateFormat, and your IDE will help you.

Body:
I have built a date picker where users can select the date and I want to update the selected date inside the elevated button, but when the date is updated it also starts showing the time inside the elevated button
Also, I want to keep the same format of date, I have specified above in the code
I am providing my code and snapshots

[class CashInCashOut extends StatefulWidget {
  const CashInCashOut({Key? key}) : super(key: key);

  @override
  _CashInCashOutState createState() => _CashInCashOutState();
}

class _CashInCashOutState extends State<CashInCashOut> {
  DateTime date = DateTime.now();
  late var formattedDate = DateFormat('d-MMM-yy').format(date);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("Cash Out"),
        ),
        body: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            children: \[
              const TextField(
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(labelText: "Amount"),
              ),
              const TextField(
                decoration: InputDecoration(labelText: "Detail (optional)"),
              ),
              Row(
                children: \[
                  ElevatedButton(
                    child: Text(formattedDate),
                    onPressed: () async {
                      DateTime? _newDate = await showDatePicker(
                        context: context,
                        initialDate: date,
                        firstDate: DateTime(2022),
                        lastDate: DateTime(2030),
                      );
                      setState(() {
                        if (_newDate == null) {
                          return;
                        } else {
                          formattedDate = _newDate.toString();
                        }
                      });
                    },
                  ),
                  const Spacer(),
                  ReusableButton(text: "Add bills"),
                \],
              ),
            \],
          ),
        ));
  }
}

state of my application before selecting date

state of my application after selecting the date from date picker

Body:
You should format the date when the button is pressed. Just replace this code portion with yours:

if (_newDate == null) {
    return
} else {
    formattedDate = DateFormat.yMd().format(_newDate);
}

Note: You can change date format according to what you want. Just change yMd to any other format you want. Hover over DateFormat, and your IDE will help you.


问:
Show duplicate entries removed by a set
I expect the below program to print the duplicate entries, which were removed by the Set.
But it always prints a empty array. What could be wrong?</p>
```<code>
public class HelloWorld{
    public static void main(String[] args){
        String str="HelloWorld";
        String[] strChar=str.split("");

        //Remove the duplicates
        Set<String> strSet=new LinkedHashSet<String>(Arrays.asList(strChar));

        List<String> strList=new ArrayList<String>(Arrays.asList(strChar));
        System.out.println(strList);
        System.out.println(strSet);

        //Show the duplicate entries that were removed by the set
        strList.removeAll(strSet);

        System.out.println(strList);
    }
}```
</code>```

答:
Output of the provided code:

```<code>$ javac HelloWorld.java && java HelloWorld
[H, e, l, l, o, W, o, r, l, d]
[H, e, l, o, W, r, d]
[]
</code>```

The line:

```<code>System.out.println(strList);
</code>```

is displaying empty set because of all the entries are removed because of the below statement

```<code>strList.removeAll(strSet);#serSet is having [H, e, l, o, W, r, d] removeAll will make strList empty
</code>```

The output is correct.

Solution

Below program displays the duplicate values which are removed.Here we are using map to map each character to the occurance of character if. If it occurs more than one time it means it was removed .

```<code>import java.util.*;

public class HelloWorld{
    public static void main(String[] args){
        String str="HelloWorld";
        String[] strChar=str.split("");

        //Remove the duplicates
        Set<String> strSet=new LinkedHashSet<String>(Arrays.asList(strChar));

        List<String> strList=new ArrayList<String>(Arrays.asList(strChar));
        System.out.println(strList);
        System.out.println(strSet);

        //Show the duplicate entries that were removed by the set
        strList.removeAll(strSet);

    //Using map to remember the occurence of characters
    Map<Character,Integer> map = new LinkedHashMap<>();
    for(char ch : str.toCharArray())
        if(map.containsKey(ch))
            map.put(ch, map.get(ch)+1);
        else map.put(ch, 1);
    var out = System.out;
    //The duplicate entries which were remove are below
    for(var entry : map.entrySet())
        if(entry.getValue() != 1)
            out.print(entry.getKey()+" ");
    out.println();

        //System.out.println(strList);
    }
}
</code>```

Output:

```<code>$ javac HelloWorld.java && java HelloWorld
[H, e, l, l, o, W, o, r, l, d]
[H, e, l, o, W, r, d]
l o
</code>```

l and o are removed because they occur multiple times

Title: Show duplicate entries removed by a set

Body:
I expect the below program to print the duplicate entries, which were removed by the Set.
But it always prints a empty array. What could be wrong?

public class HelloWorld{
    public static void main(String[] args){
        String str="HelloWorld";
        String[] strChar=str.split("");

        //Remove the duplicates
        Set<String> strSet=new LinkedHashSet<String>(Arrays.asList(strChar));

        List<String> strList=new ArrayList<String>(Arrays.asList(strChar));
        System.out.println(strList);
        System.out.println(strSet);

        //Show the duplicate entries that were removed by the set
        strList.removeAll(strSet);

        System.out.println(strList);
    }
}```

Body:
Output of the provided code:

$ javac HelloWorld.java && java HelloWorld
[H, e, l, l, o, W, o, r, l, d]
[H, e, l, o, W, r, d]
[]

The line:

System.out.println(strList);

is displaying empty set because of all the entries are removed because of the below statement

strList.removeAll(strSet);#serSet is having [H, e, l, o, W, r, d] removeAll will make strList empty

The output is correct.

Solution

Below program displays the duplicate values which are removed.Here we are using map to map each character to the occurance of character if. If it occurs more than one time it means it was removed .

import java.util.*;

public class HelloWorld{
    public static void main(String[] args){
        String str="HelloWorld";
        String[] strChar=str.split("");

        //Remove the duplicates
        Set<String> strSet=new LinkedHashSet<String>(Arrays.asList(strChar));

        List<String> strList=new ArrayList<String>(Arrays.asList(strChar));
        System.out.println(strList);
        System.out.println(strSet);

        //Show the duplicate entries that were removed by the set
        strList.removeAll(strSet);

    //Using map to remember the occurence of characters
    Map<Character,Integer> map = new LinkedHashMap<>();
    for(char ch : str.toCharArray())
        if(map.containsKey(ch))
            map.put(ch, map.get(ch)+1);
        else map.put(ch, 1);
    var out = System.out;
    //The duplicate entries which were remove are below
    for(var entry : map.entrySet())
        if(entry.getValue() != 1)
            out.print(entry.getKey()+" ");
    out.println();

        //System.out.println(strList);
    }
}

Output:

$ javac HelloWorld.java && java HelloWorld
[H, e, l, l, o, W, o, r, l, d]
[H, e, l, o, W, r, d]
l o

l and o are removed because they occur multiple times


问:
Proper CPython String Concatenation
Last night I was at a Boston Python Meetup that described various Python implementations. Part of the discussion included string concatenation.

Apparently for CPython there is less heap fragmentation if strings are concatenated starting with an empty string and then using join.

Is this an OK way to construct a string

```<code>sql_statement = "select count(*) " + \
    "from ept_inv e " + \
    "where e.ept_type =  " + str(in_row[cs.DeviceType]) + " " + \
    "and e.inv_id = " + str(in_row[cs.EndpointID]) + " ; "
</code>```

or should I have set sql_statement to "" and then joined each piece?
Thanks.

答:
I suspect this would be premature optimization.  Just do it in the most readable/pythonic way and only optimize it if profiling with real world use cases reveals your string concatenation to be a hot spot.

Also, heed the comment.  :-)

Title: Proper CPython String Concatenation

Body:
Last night I was at a Boston Python Meetup that described various Python implementations. Part of the discussion included string concatenation.

Apparently for CPython there is less heap fragmentation if strings are concatenated starting with an empty string and then using join.

Is this an OK way to construct a string

sql_statement = "select count(*) " + \
    "from ept_inv e " + \
    "where e.ept_type =  " + str(in_row[cs.DeviceType]) + " " + \
    "and e.inv_id = " + str(in_row[cs.EndpointID]) + " ; "

or should I have set sql_statement to "" and then joined each piece?
Thanks.


问:
Using awk to read every 5 lines from a file to a new file with name file_# where # is incremented based on the current iteration
I have a file with 200 lines in it. I want awk to read every 5 lines and create a file for it (whose file name will be file_#).

When program reads the first 5 lines, it will create file_1 for these 5 lines. When program reads 6-10 lines, it will create file_2 for those 5 lines. This has to be done till it reaches the end of file.

答:
No need for awk or anything fancy. Using GNU split:

split --numeric-suffixes=1 -l5 file file_
```


问:
Why can't this be local?
This is a dummy variant of a setup I'm running. The Launcher function does not seem to see the GetLevel. At least the first print is seen but the second isn't. So the function never starts. Is that because the code comes after the place it is launched it in the code, and at the point Launcher executes it doesn't exist yet? When I remove the local tag it works. So global functions can be "seen" from anywhere in the script, but local ones only from later in the code?
I'm trying to find out which functions I can make local, as they are all currently global. Is there even a benefit to this - is there a difference between a function that's local to the entire script and one that's not local?</p>
```<code>local UseLevel = true
local Limit = 0

local function Launcher()
  print("trying to launch GetLevel now")
  GetLevel()
end

local function GetLevel()
  print("GetLevel was launched")
  if UseLevel then
    Limit = 4
  else
    Limit = 5
  end
end
</code>```

答:
So global functions can be "seen" from anywhere in the script, but local ones only from later in the code?

Yes, "global" means global.

You make something local if you don't want it to be visible outside of the script. A script should not expose something to the outside world unless the outside world needs to see it. Expose only interfaces, things the external code will actually talk to.

Title: Why can't this be local?

Body:
This is a dummy variant of a setup I'm running. The Launcher function does not seem to see the GetLevel. At least the first print is seen but the second isn't. So the function never starts. Is that because the code comes after the place it is launched it in the code, and at the point Launcher executes it doesn't exist yet? When I remove the local tag it works. So global functions can be "seen" from anywhere in the script, but local ones only from later in the code?
I'm trying to find out which functions I can make local, as they are all currently global. Is there even a benefit to this - is there a difference between a function that's local to the entire script and one that's not local?

local UseLevel = true
local Limit = 0

local function Launcher()
  print("trying to launch GetLevel now")
  GetLevel()
end

local function GetLevel()
  print("GetLevel was launched")
  if UseLevel then
    Limit = 4
  else
    Limit = 5
  end
end


问:
Amplify @hasMany relationship return null
This are my first question here.

I have this schema on amplify

type Products @model {
  id: ID!
  title: String!
  description: String!
  variations: [Variation] @hasMany(indexName: "byProduct", fields: ["id"])
}

type Variation @model {
  id: ID!
  productId: ID! @index(name: "byProduct")
  name: String!
  image: String!
  quantity: Int!
}
```
<p>When I test the query on AppSync this return the variations, but when I use</p>
<pre class="lang-js prettyprint-override"><code>const result = (await API.graphql(graphqlOperation(gql.listProducts))).data.listProducts.items;
</code>```

or with DataStore like this

await DataStore.query(Products)
```
<p>return a null or empty</p>
<pre class="lang-json prettyprint-override"><code>    variations: { nextToken: null, startedAt: null },
</code>```

Someone with the same issue ? or maybe I was missing something?

thanks

答:
Please check type of Products in local when await DataStore.query(Products)
and value of listProducts in gql when API.graphql.
I think you are missing a few fields.</p>

Body:
This are my first question here.

I have this schema on amplify

type Products @model {
  id: ID!
  title: String!
  description: String!
  variations: [Variation] @hasMany(indexName: "byProduct", fields: ["id"])
}

type Variation @model {
  id: ID!
  productId: ID! @index(name: "byProduct")
  name: String!
  image: String!
  quantity: Int!
}

When I test the query on AppSync this return the variations, but when I use

const result = (await API.graphql(graphqlOperation(gql.listProducts))).data.listProducts.items;

or with DataStore like this

await DataStore.query(Products)

return a null or empty

    variations: { nextToken: null, startedAt: null },

Someone with the same issue ? or maybe I was missing something?

thanks


问:
OJET table length attribute
I have recently started working on Oracle JET where I'm having a requirement of creating a table in which I have to populate the first three items or dataset from the api response data, I'm able to populate all the response data in the table but as I want to show the first three items only, is there any attribute which I can use to limit the dataset in the view?</p>

答:
In this example from the cookbook, set the below shown attributes and Apply the changes.</p>
```<code>scroll-policy-options='{"fetchSize":3}' style="height:200px"
</code>```

Title: OJET table length attribute

Body:
In this example from the cookbook, set the below shown attributes and Apply the changes.

scroll-policy-options='{"fetchSize":3}' style="height:200px"


问:
Show all results for employees earning less than ALLEN in SQL
I'm trying to do this query but it doesn't work for me.

Show all results for employees earning less than ALLEN

This is the employees table:

```<code> EmpNb, EName, -  Job,     Mgr,   HireDate,    Sal,       Comm,     DeptNb
 7499,  ALLEN,  SALESMAN,  7698,  1981-02-20,  1600.00 ,  300.00,   30
 7654,  MARTIN, SALESMAN,  7698,  1981-09-28,  1250.00,   1400.00,  30
 7934,  MILLER, CLERK,     7782,  1982-01-23,  1300.00,   NULL,     10
 7844,  TURNER, SALESMAN,  7698,  1981-09-08,  1500.00,   0.00,     30
 7782,  CLARK,  MANAGER,   7839,  1981-06-09,  2450.00,   NULL,     10
 7698,  BLAKE,  MANAGER,   7839,  1981-05-01,  2850.00,   NULL,     30
</code>```

I need help

答:
A subquery should do the job:</p>
```<code>select * from employees
where Sal < (select Sal from employees where EName = 'ALLEN')
</code>```

Body:
I'm trying to do this query but it doesn't work for me.

Show all results for employees earning less than ALLEN

This is the employees table:

 EmpNb, EName, -  Job,     Mgr,   HireDate,    Sal,       Comm,     DeptNb
 7499,  ALLEN,  SALESMAN,  7698,  1981-02-20,  1600.00 ,  300.00,   30
 7654,  MARTIN, SALESMAN,  7698,  1981-09-28,  1250.00,   1400.00,  30
 7934,  MILLER, CLERK,     7782,  1982-01-23,  1300.00,   NULL,     10
 7844,  TURNER, SALESMAN,  7698,  1981-09-08,  1500.00,   0.00,     30
 7782,  CLARK,  MANAGER,   7839,  1981-06-09,  2450.00,   NULL,     10
 7698,  BLAKE,  MANAGER,   7839,  1981-05-01,  2850.00,   NULL,     30

I need help

Body:
A subquery should do the job:

select * from employees
where Sal < (select Sal from employees where EName = 'ALLEN')


问:
React text dropdown toggle (toggles all)
I am trying to make a small text dropdown. When you click on the heading text, the p tag will show. It is working, but.. it is toggling all of them, when I only click on of them. I have multiple "li" tags with text and the function. So I am not looping anything</p>
```<code>const [isActive, setActive] = useState(false)

  const toggleText = () => {
    setActive(!isActive)
  }

  <li>
              <h2 onClick={toggleText}>Lorem ipsum dolar sit amet</h2>

              {isActive && (
                <p>
                  Lorem ipsum dolor sit, amet consectetur adipisicing elit. Ut
                  reprehenderit explicabo laudantium quas, minus recusandae
                  quibusdam dolorem dolorum possimus natus quod nam, et labore
                  iste eos? Ducimus optio dolor soluta!
                </p>
              )}
              <div onClick={toggleText} className='dropDown__plus'>
                {!isActive ? (
                  <img src={plusIcon} alt='Plus icon' />
                ) : (
                  <img src={minusIcon} alt='Minus Icon' />
                )}
              </div>
            </li>
</code>```

答:
Based on your question and the comments, you are reusing the isActive state across multiple elements in the same component, which means that each element does not have its own isActive state: they all share the same state globally.

You can create a child component that handles the state exclusively, while allowing it to receive contents in the form of props, e.g. for the heading and content:

```<code>import { useState } from "react";

export default function MyComponent(props) {
  const [isActive, setActive] = useState(false);

  const toggleText = () => {
    setActive(!isActive);
  };

  return (
    <li>
      <h2 onClick={toggleText}>{props.heading}</h2>

      {isActive && props.content}
      <button type="button" onClick={toggleText} className="dropDown__plus">
        {!isActive ? <>+</> : <>-</>}
      </button>
    </li>
  );
}
</code>```

Then, in your original parent component it's just a matter of using <MyComponent> to handle all your
 entries:

```<code><ul>
  <MyComponent
    heading="Lorem ipsum dolor sit amet"
    content={<p>Some text here</p>}
  />
  <MyComponent
    heading="Foo bar"
    content={<p>More foo bar content</p>}
  />
  <MyComponent
    heading="Last header"
    content={<p>C'est la vie</p>}
  />
</ul>
</code>```

You can see a proof-of-concept example here:

Body:
I am trying to make a small text dropdown. When you click on the heading text, the p tag will show. It is working, but.. it is toggling all of them, when I only click on of them. I have multiple "li" tags with text and the function. So I am not looping anything

const [isActive, setActive] = useState(false)

  const toggleText = () => {
    setActive(!isActive)
  }

Lorem ipsum dolar sit amet

              {isActive && (

                  Lorem ipsum dolor sit, amet consectetur adipisicing elit. Ut
                  reprehenderit explicabo laudantium quas, minus recusandae
                  quibusdam dolorem dolorum possimus natus quod nam, et labore
                  iste eos? Ducimus optio dolor soluta!

              )}

                {!isActive ? (

                ) : (

                )}

Body:
Based on your question and the comments, you are reusing the isActive state across multiple elements in the same component, which means that each element does not have its own isActive state: they all share the same state globally.

You can create a child component that handles the state exclusively, while allowing it to receive contents in the form of props, e.g. for the heading and content:

import { useState } from "react";

export default function MyComponent(props) {
  const [isActive, setActive] = useState(false);

  const toggleText = () => {
    setActive(!isActive);
  };

  return (
    <li>
      <h2 onClick={toggleText}>{props.heading}</h2>

      {isActive && props.content}
      <button type="button" onClick={toggleText} className="dropDown__plus">
        {!isActive ? <>+</> : <>-</>}
      </button>
    </li>
  );
}

Then, in your original parent component it's just a matter of using <MyComponent> to handle all your <li> entries:

<ul>
  <MyComponent
    heading="Lorem ipsum dolor sit amet"
    content={<p>Some text here</p>}
  />
  <MyComponent
    heading="Foo bar"
    content={<p>More foo bar content</p>}
  />
  <MyComponent
    heading="Last header"
    content={<p>C'est la vie</p>}
  />
</ul>

You can see a proof-of-concept example here: