问:
Resilience4j returning a CompletableFuture around tried method with parameter
I can't find out how to wrap a synchronous method with Resilience4j so that it returns a CompletableFuture, although this seems to be part of Resilience4j's target area.
Especially since the synchronous method I want to wrap can throw an Exception.
What I want in pseudo code:

boolean void syncMethod(Parameter param) throws Exception {
    // May throw Exception due to connection/authorization problems.
}

CompletableFuture<Boolean> asyncResilience4jWrapper() {
    CompletableFuture<Boolean> result =
        ...
            Resilience4j magic around "syncMethod(param)".
            Trying 4 calls, interval between calls of 100 ms.
        ...;
    return result;
}
```

Resilience4j should just try to call the method 4 times until it gives up, with intervals between the calls of 100 ms and then complete the asynchronous call.
The asyncResilience4jWrapper caller should just get back a CompletableFuture which doesn't block and don't care about any of that.

The really hard part seems to be to get it running for a method with a parameter, throwing an exception!

答:
just do</p>

```<code>CompletableFuture<Boolean> asyncResilience4jWrapper(Parameter param) {
   return CompletableFuture<Boolean> future = Decorators.ofCallable(() -> syncMethod(param))
    .withThreadPoolBulkhead(threadPoolBulkhead)
    .withTimeLimiter(timeLimiter, scheduledExecutorService)
    .withCircuitBreaker(circuitBreaker)
    .withRetry(retry)
    .withFallback(asList(TimeoutException.class, CallNotPermittedException.class, BulkheadFullException.class),
      throwable -> "Hello from Recovery")
    .get().toCompletableFuture();
}
</code>```

Body:
I can't find out how to wrap a synchronous method with Resilience4j so that it returns a CompletableFuture, although this seems to be part of Resilience4j's target area.
Especially since the synchronous method I want to wrap can throw an Exception.
What I want in pseudo code:

boolean void syncMethod(Parameter param) throws Exception {
    // May throw Exception due to connection/authorization problems.
}

CompletableFuture<Boolean> asyncResilience4jWrapper() {
    CompletableFuture<Boolean> result =
        ...
            Resilience4j magic around "syncMethod(param)".
            Trying 4 calls, interval between calls of 100 ms.
        ...;
    return result;
}

Resilience4j should just try to call the method 4 times until it gives up, with intervals between the calls of 100 ms and then complete the asynchronous call.
The asyncResilience4jWrapper caller should just get back a CompletableFuture which doesn't block and don't care about any of that.

The really hard part seems to be to get it running for a method with a parameter, throwing an exception!

Body:
just do

CompletableFuture<Boolean> asyncResilience4jWrapper(Parameter param) {
   return CompletableFuture<Boolean> future = Decorators.ofCallable(() -> syncMethod(param))
    .withThreadPoolBulkhead(threadPoolBulkhead)
    .withTimeLimiter(timeLimiter, scheduledExecutorService)
    .withCircuitBreaker(circuitBreaker)
    .withRetry(retry)
    .withFallback(asList(TimeoutException.class, CallNotPermittedException.class, BulkheadFullException.class),
      throwable -> "Hello from Recovery")
    .get().toCompletableFuture();
}


来源: stackexchange

问:
Why are my answer's decimals incorrect in Python?
I am currently busy with a question that requires for one to solve Ax = b using Jacobi method where the function created must return x and the 2 norm of x.

The question states that when b is inputted as

```<code>b = [71; 42;-11;-37;-61; 52]
T = 2
N = 2
</code>```

The answer that i am supposed to get is x = [2.73186728; 1.44791667; 0.62885802; 6.32696759; 6.390625; 3.33012821] and the norm of x 10.0953

However I get x = [ 3.07507642;  0.58675203; -0.64849988;  5.33343053; 6.66765397; 4.16161712] and the 2 norm of x 10.0221

I am trying to find where the error in my code is but finding it difficult...below is my code

import numpy as np
from numpy.linalg import norm
from numpy import array
from scipy.linalg import solve

def jacobi(A, b, x0, N):

    n = A.shape[0]
    x = x0.copy()
    k = 0
    x_prev= x0.copy()

    for i in range(0, n):
        subs = 0.0
        for j in range(0, n):
            if i != j:
                subs += np.matrix(A[i,j])*np.matrix(x_prev[j])

        x[i] = (b[i]-subs)/np.matrix(A[i,i])

    k += 1

    return(x)

A = array([[18, 1, 4, 3, -1, 2],
           [2, 12, -1, 7, -2, 1],
           [-1, 1, -9, 2, -5, 2],
           [2, 4, 1, -12, 1, 3],
           [1, 3, 1, 7, -16, 1],
           [-2, 1, 7, -1, 2, 13]])

x0 = array([[0],[0],[0],[0],[0],[0]])

elements_of_b_and_N = list(map(float, input().split(' ')))
b_and_N = array(elements_of_b_and_N).reshape(A.shape[0]+1, )
b = b_and_N[:A.shape[0]]
N = b_and_N[A.shape[0]]

x = jacobi(A, b, x0, N)
print((solve(A, b)))
print(round(norm((solve(A,b)), 2), 4))
```

ContentLicense: CC BY-SA 4.0

Body:
I am currently busy with a question that requires for one to solve Ax = b using Jacobi method where the function created must return x and the 2 norm of x.

The question states that when b is inputted as

b = [71; 42;-11;-37;-61; 52]
T = 2
N = 2

The answer that i am supposed to get is x = [2.73186728; 1.44791667; 0.62885802; 6.32696759; 6.390625; 3.33012821] and the norm of x 10.0953

However I get x = [ 3.07507642;  0.58675203; -0.64849988;  5.33343053; 6.66765397; 4.16161712] and the 2 norm of x 10.0221

I am trying to find where the error in my code is but finding it difficult...below is my code

import numpy as np
from numpy.linalg import norm
from numpy import array
from scipy.linalg import solve

def jacobi(A, b, x0, N):

    n = A.shape[0]
    x = x0.copy()
    k = 0
    x_prev= x0.copy()

    for i in range(0, n):
        subs = 0.0
        for j in range(0, n):
            if i != j:
                subs += np.matrix(A[i,j])*np.matrix(x_prev[j])

        x[i] = (b[i]-subs)/np.matrix(A[i,i])

    k += 1

    return(x)

A = array([[18, 1, 4, 3, -1, 2],
           [2, 12, -1, 7, -2, 1],
           [-1, 1, -9, 2, -5, 2],
           [2, 4, 1, -12, 1, 3],
           [1, 3, 1, 7, -16, 1],
           [-2, 1, 7, -1, 2, 13]])

x0 = array([[0],[0],[0],[0],[0],[0]])

elements_of_b_and_N = list(map(float, input().split(' ')))
b_and_N = array(elements_of_b_and_N).reshape(A.shape[0]+1, )
b = b_and_N[:A.shape[0]]
N = b_and_N[A.shape[0]]

x = jacobi(A, b, x0, N)
print((solve(A, b)))
print(round(norm((solve(A,b)), 2), 4))

Body:
How did you compute the true value ?

The question states that when b is inputted as b = [71;
  42;-11;-37;-61; 52]T and N = 2, the answer that i am supposed to get
  is x = [2.73186728; 1.44791667; 0.62885802; 6.32696759; 6.390625;
  3.33012821] and the norm of x 10.0953

When I execute :

x0 = array([[0], [0], [0], [0], [0], [0]], dtype=float)
A = array([[18, 1, 4, 3, -1, 2],
       [2, 12, -1, 7, -2, 1],
       [-1, 1, -9, 2, -5, 2],
       [2, 4, 1, -12, 1, 3],
       [1, 3, 1, 7, -16, 1],
       [-2, 1, 7, -1, 2, 13]])
b = array([[71], [42], [-11], [-37], [-61], [52]], dtype=float)

print(solve(A, b))

I get :

[[ 3.07507642]
[ 0.58675203]
[-0.64849988]
[ 5.33343053]
[ 6.66765397]
[ 4.16161712]]

As you do with Jacobi.

Hope this helps :)


问:
Error: Expected 'var' keyword in property declaration
I'm getting the following error: Expected 'var' keyword in property declaration in my enum re-assignment:

```<code>struct ContentView: View {
    // Return Screen based on State
    var screen = Screen.login
    screen = .editProfile // Expected 'var' keyword in property declaration
    var body: some View {
        if screen == .home {
            return AnyView(HomeView())
        }
        else if screen == .editProfile {
            return AnyView(LoginView())
        }
        else {
            return AnyView(LoginView())
        }
    }
}

enum Screen {
    case login, home, editProfile
}
</code>```

Any idea what the issue is?

答:
You cannot put instruction out of any execution block inside type declaration, so here is a possible examples</p>

```<code>struct ContentView: View {
    // Return Screen based on State
    var screen = Screen.login       // << initialisation !!

    var body: some View {
        if screen == .home {
            return AnyView(HomeView()
                     .onTapGesture {self.screen = .editProfile}) // << one !!
        }
        else if screen == .editProfile {
            return AnyView(LoginView())
        }
        else {
            return AnyView(LoginView()
                     .onAppear {self.screen = .editProfile})    // << two !!
        }
    }
}
</code>```

Body:
I'm getting the following error: Expected 'var' keyword in property declaration in my enum re-assignment:

struct ContentView: View {
    // Return Screen based on State
    var screen = Screen.login
    screen = .editProfile // Expected 'var' keyword in property declaration
    var body: some View {
        if screen == .home {
            return AnyView(HomeView())
        }
        else if screen == .editProfile {
            return AnyView(LoginView())
        }
        else {
            return AnyView(LoginView())
        }
    }
}

enum Screen {
    case login, home, editProfile
}

Any idea what the issue is?

Body:
You cannot put instruction out of any execution block inside type declaration, so here is a possible examples

struct ContentView: View {
    // Return Screen based on State
    var screen = Screen.login       // << initialisation !!

    var body: some View {
        if screen == .home {
            return AnyView(HomeView()
                     .onTapGesture {self.screen = .editProfile}) // << one !!
        }
        else if screen == .editProfile {
            return AnyView(LoginView())
        }
        else {
            return AnyView(LoginView()
                     .onAppear {self.screen = .editProfile})    // << two !!
        }
    }
}


问:
Haskell cabal: I just installed packages, but now the packages are not found
Over here is the only reason I can find that packages I'm installing using cabal are not being found by GHC:

This happens when you install a package globally, and the previous packages were installed locally. Note that cabal-install install locally by default [...]

Presumably, "local installation" means putting packages in ~/.cabal/.  First question: where are global installs?

I've been running cabal using sudo, so I guess that's a global install?  The reason I've been doing this is that it complains about permissions when run without sudo, so this contradicts the statement "cabal-install install locally by default".  Second question: how do I install locally and how do I install globally?

Trying to fix this mess, I've been randomly using sudo ghc-pkg unregister and randomly removing stuff from ~/.cabal/.  Consequently my package tree is broken, probably locally and globally.  Third question: How do I start again?

Edit: I'm running Ubuntu 10.10.  I installed the Haskell Platform 2011.

答:
Are you using Windows, OS X or some version of Linux? Are you using the Haskell Platform? Have you had a version of ghc or cabal before? For a Linux distribution, subtleties about your package manager may come in, of course. (Traces of an old ghc in particular, and an old ~/.ghc/ directory can be a source of trouble.)

Here are a few elementary thoughts of the type one goes through on #haskell with such problems. (My comprehension is not completely adequate, of course):

The chief question seems to be, Why you were being invited to do what should be local installs with sudo?  A global install (cabal install pony --global) would of course require privileges if ghc and its libraries are in /usr/... or some other protected place,   but otherwise sudo vs non-sudo is independent of the place of installation. What you do with cabal install pony --user (--user is the default, in theory) should not require superuser authority. (I have sometimes found on OS X that privileges are requested where the gcc needs to be called, but this has usually been due to curiosities about my setup.) But in any case sudo doesn't affect where cabal is putting them: the implicit --user and explicit --global, and more specific incantations for development, do that.

If you do ghc-pkg list, for example, it will divide the packages into the different places they are registered in according to two or more package.conf.d directories it is summarizing. On my laptop at the moment these are

```<code>/Users/applicative/.ghc/x86_64-darwin-7.0.3/package.conf.d/...
</code>```

for the local things in ~/.cabal/lib/... and the protected

```<code>/Library/Frameworks/GHC.framework/Versions/7.0.3-x86_64/usr/lib/ghc-7.0.3/package.conf.d
</code>```

for things that were installed globally with the Haskell Platform installer (this location involves some OS X peculiarities, ghc, ghci and so on are in the woods somewhere, but symlinked to /usr/bin).  The conf files for different packages tell you exactly where the libraries were installed. So, for example about the sacred base library,

```<code>$ cat base-4.3.1.0-f5c465200a37a65ca26c5c6c600f6c76.conf
</code>```

tells me:

```<code>import-dirs:
 /Library/Frameworks/GHC.framework/Versions/7.0.3-x86_64/usr/lib/ghc-7.0.3/base-4.3.1.0
library-dirs:
 /Library/Frameworks/GHC.framework/Versions/7.0.3-x86_64/usr/lib/ghc-7.0.3/base-4.3.1.0
</code>```

In any case, where does ghc-pkg list say your cabal install-ed packages are going?  In the ~/.cabal folder, look at the file config. If you haven't edited it, I think the commented and uncommented lines, if they state a preference, are stating the defaults for installation with --global and --user. In the ~.ghc/ directory check out the subdirectory myghcversion/package.conf.d and see if anything is there, which should be the same as what ghc-pkg tells you. (You might study the options for ghc-pkg in general, eg. ghc-pkg check and ghc-pkg recache, if you haven't. You may have installed something in some odd way.)

If you installed ghc and cabal and co. by installing the Haskell Platform with a binary installer or your package manager, which seems like a good idea, it is also a good idea, I think, to keep the Platform libraries as something sacred, and make sure you never install anything globally from Hackage; among other things this is likely to have you overwriting Platform libraries -- though this doesn't seem the difficulty here: it would be more obvious if it were.

ContentLicense: CC BY-SA 3.0

Body:
Are you using Windows, OS X or some version of Linux? Are you using the Haskell Platform? Have you had a version of ghc or cabal before? For a Linux distribution, subtleties about your package manager may come in, of course. (Traces of an old ghc in particular, and an old ~/.ghc/ directory can be a source of trouble.)

Here are a few elementary thoughts of the type one goes through on #haskell with such problems. (My comprehension is not completely adequate, of course):

The chief question seems to be, Why you were being invited to do what should be local installs with sudo?  A global install (cabal install pony --global) would of course require privileges if ghc and its libraries are in /usr/... or some other protected place,   but otherwise sudo vs non-sudo is independent of the place of installation. What you do with cabal install pony --user (--user is the default, in theory) should not require superuser authority. (I have sometimes found on OS X that privileges are requested where the gcc needs to be called, but this has usually been due to curiosities about my setup.) But in any case sudo doesn't affect where cabal is putting them: the implicit --user and explicit --global, and more specific incantations for development, do that.

If you do ghc-pkg list, for example, it will divide the packages into the different places they are registered in according to two or more package.conf.d directories it is summarizing. On my laptop at the moment these are

/Users/applicative/.ghc/x86_64-darwin-7.0.3/package.conf.d/...

for the local things in ~/.cabal/lib/... and the protected

/Library/Frameworks/GHC.framework/Versions/7.0.3-x86_64/usr/lib/ghc-7.0.3/package.conf.d

for things that were installed globally with the Haskell Platform installer (this location involves some OS X peculiarities, ghc, ghci and so on are in the woods somewhere, but symlinked to /usr/bin).  The conf files for different packages tell you exactly where the libraries were installed. So, for example about the sacred base library,

$ cat base-4.3.1.0-f5c465200a37a65ca26c5c6c600f6c76.conf

tells me:

import-dirs:
 /Library/Frameworks/GHC.framework/Versions/7.0.3-x86_64/usr/lib/ghc-7.0.3/base-4.3.1.0
library-dirs:
 /Library/Frameworks/GHC.framework/Versions/7.0.3-x86_64/usr/lib/ghc-7.0.3/base-4.3.1.0

In any case, where does ghc-pkg list say your cabal install-ed packages are going?  In the ~/.cabal folder, look at the file config. If you haven't edited it, I think the commented and uncommented lines, if they state a preference, are stating the defaults for installation with --global and --user. In the ~.ghc/ directory check out the subdirectory myghcversion/package.conf.d and see if anything is there, which should be the same as what ghc-pkg tells you. (You might study the options for ghc-pkg in general, eg. ghc-pkg check and ghc-pkg recache, if you haven't. You may have installed something in some odd way.)

If you installed ghc and cabal and co. by installing the Haskell Platform with a binary installer or your package manager, which seems like a good idea, it is also a good idea, I think, to keep the Platform libraries as something sacred, and make sure you never install anything globally from Hackage; among other things this is likely to have you overwriting Platform libraries -- though this doesn't seem the difficulty here: it would be more obvious if it were.


问:
GEt element By id angular 7
hello I need to retrieve the values entered by a form after the post method so I inserted at the service level this code :

```<code> list:Client[];

 constructor(private http:HttpClient) { }
 postClient(formData:Client){

  return this.http.post(this.rootURL+'/Clients/',formData);
 }
 putClient(formData:Client){

   return this.http.put(this.rootURL+'/Clients/'+formData.Engagement,formData);
  }
  getClient(formData:Client){

   return this.http.get(this.rootURL+'/Clients/GetClientByName/'+formData.Engagement);
  }
</code>```

and at the component level like this :

```<code> getClient(form:NgForm){

  this.clientservice.getClient(form.value).subscribe(
    res =>{this.client = res as Client}
  )

 }
</code>```

and in the HTML code this:

```<code><table class="table table-hover">
                            <tr>

                                <th class="tname">Client</th>
                                <th class="tname">Enagement</th>
                                <th class="tname">ERP</th>

                            </tr>
                            <tr *ngFor="let clt of client">

                                <td >{{clt.Clientname}}</td>
                                <td >{{clt.Engagement}}</td>
                                <td >{{clt.ERP}}</td>
</code>```

and I can’t get the values by ID with the get I don’t know  what is the problem I have neither result or error message

答:
I think your http service(this.rootURL+'/Clients/GetClientByName/) return Client[] not Client.
So, You should cast like this.

  this.clientservice.getClient(form.value).subscribe(
    res =>{this.client = res as Client[]}
  )
```

<p>But, your response is fixed</p>

``` {"Engagement":"56789","Clientname":"ClLIENT","ERP":"ERP"}
```

<p>at component level, no need to edit</p>

``` getClient(form:NgForm){

  this.clientservice.getClient(form.value).subscribe(
    res =>{this.client = res as Client}
  )

 }
```

<p>you should edit html file.</p>

<pre class="lang-html prettyprint-override"><code><table class="table table-hover">
                            <tr>

                                <th class="tname">Client</th>
                                <th class="tname">Enagement</th>
                                <th class="tname">ERP</th>

                            </tr>
                            <tr>
                                <td >{{client.Clientname}}</td>
                                <td >{{client.Engagement}}</td>
                                <td >{{client.ERP}}</td>
                            </tr>
</code>```

---------------------------

or need to use ngFor loop, edit component level. and no need to edit component level.

```<code> client: Client[] = [];
 getClient(form:NgForm){

  this.clientservice.getClient(form.value).subscribe(
    res =>{
            const cli = res as Client;
            this.client.length = 0;
            Array.prototype.push.apply(this.client, cli)
      }
  )

 }

</code>```

Title: GEt element By id angular 7

Body:
hello I need to retrieve the values entered by a form after the post method so I inserted at the service level this code :

 list:Client[];

 constructor(private http:HttpClient) { }
 postClient(formData:Client){

  return this.http.post(this.rootURL+'/Clients/',formData);
 }
 putClient(formData:Client){

   return this.http.put(this.rootURL+'/Clients/'+formData.Engagement,formData);
  }
  getClient(formData:Client){

   return this.http.get(this.rootURL+'/Clients/GetClientByName/'+formData.Engagement);
  }

and at the component level like this :

 getClient(form:NgForm){

  this.clientservice.getClient(form.value).subscribe(
    res =>{this.client = res as Client}
  )

 }

and in the HTML code this:

                                Client
                                Enagement
                                ERP

                                {{clt.Clientname}}
                                {{clt.Engagement}}
                                {{clt.ERP}}

and I can’t get the values by ID with the get I don’t know  what is the problem I have neither result or error message

Body:
I think your http service(this.rootURL+'/Clients/GetClientByName/) return Client[] not Client.
So, You should cast like this.

  this.clientservice.getClient(form.value).subscribe(
    res =>{this.client = res as Client[]}
  )

But, your response is fixed

 {"Engagement":"56789","Clientname":"ClLIENT","ERP":"ERP"}

at component level, no need to edit

 getClient(form:NgForm){

  this.clientservice.getClient(form.value).subscribe(
    res =>{this.client = res as Client}
  )

 }

you should edit html file.

<table class="table table-hover">
                            <tr>

                                <th class="tname">Client</th>
                                <th class="tname">Enagement</th>
                                <th class="tname">ERP</th>

                            </tr>
                            <tr>
                                <td >{{client.Clientname}}</td>
                                <td >{{client.Engagement}}</td>
                                <td >{{client.ERP}}</td>
                            </tr>

---------------------------

or need to use ngFor loop, edit component level. and no need to edit component level.

 client: Client[] = [];
 getClient(form:NgForm){

  this.clientservice.getClient(form.value).subscribe(
    res =>{
            const cli = res as Client;
            this.client.length = 0;
            Array.prototype.push.apply(this.client, cli)
      }
  )

 }


问:
Slicing a dictionary's value isn't working properly
So I have a json file which contains role ids (a dictionary named roles),with a key (which is the name of the role) and each key has the role's id as it's value

Looks something like this:

{"Ban": ["694175790639743076"], "Muted": ["692863646543380590"]}

I mostly just need the ids from the json

using something like roles['Muted'] or roles.get('Muted') gives me ['692863646543380590']:
Muted=roles.get('Muted')
print(Muted)

the functions take integers,so I have to remove [' from the output and get this: 692863646543380590

slicing just gives me [] no matter what slicing I use:
work=boost1[2:20] *or any other slice*
print(work)
gives out "[]"

why is slicing just not working here? and how do I fix this??

答:
Try this - </p>

```<code>work = int(boost1[0]) #fetching the first element of list and converting it into int
</code>```

Body:
Try this -

work = int(boost1[0]) #fetching the first element of list and converting it into int


问:
Is it possible to pass data while navigating up in android
I have two fragments A and B. I'm trying to navigate to B and then back to A. While doing this, I have some form data (a bunch of text fields) in A which I'd like to preserve while navigating back and forth to B. When I navigateUp() from B, the data in A is preserved but I'm not able to pass data from B to A. If I use bundles while navigating back to A, I'm unable to save the data using onSaveInstanceState(). I've used the following code in fragment A for saving the form data (got it from: https://developer.android.com/guide/components/activities/activity-lifecycle#instance-state)

```<code>override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if(savedInstanceState!=null){
            with(savedInstanceState) {
                inputName.setText(getString("Name"))
            }
        }
        else{
            //I just leave it since the text fields will be empty anyways
        }
    }

override fun onSaveInstanceState(outState: Bundle) {

        outState.run {
            putString("Name",inputName.text.toString())
        }
        super.onSaveInstanceState(outState)
    }
</code>```

But onSaveInstaceState is not being called when I navigate away (due to this when onCreate is called, the value ends up as null and the flow goes to the if statement). All I want to do is to save data in A while navigating from A to B.

答:
Not the best approach to follow (I'd suggest to share data using shared stateful view model but from your question it is not clear if you are using view models at all) :

Supply your fragment B with action like this:

```<code>        <action
            android:id="@+id/backToA"
            app:destination="@+id/A"
            app:popUpTo="@+id/B"
            app:popUpToInclusive="true" />
</code>```

Supply your fragment A with needed arguments that you'll pass from B.

From B, instead of navigateUp use navigate with action backToA and supply arguments you need to provide to A

You'll also have to take care of manual handling of "back by system back button" scenario (to override navigateUp), as well as, possibly, "back by toolbar back" if you have toolbar - but that's another story.

Body:
I have two fragments A and B. I'm trying to navigate to B and then back to A. While doing this, I have some form data (a bunch of text fields) in A which I'd like to preserve while navigating back and forth to B. When I navigateUp() from B, the data in A is preserved but I'm not able to pass data from B to A. If I use bundles while navigating back to A, I'm unable to save the data using onSaveInstanceState(). I've used the following code in fragment A for saving the form data (got it from: https://developer.android.com/guide/components/activities/activity-lifecycle#instance-state)

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if(savedInstanceState!=null){
            with(savedInstanceState) {
                inputName.setText(getString("Name"))
            }
        }
        else{
            //I just leave it since the text fields will be empty anyways
        }
    }

override fun onSaveInstanceState(outState: Bundle) {

        outState.run {
            putString("Name",inputName.text.toString())
        }
        super.onSaveInstanceState(outState)
    }

But onSaveInstaceState is not being called when I navigate away (due to this when onCreate is called, the value ends up as null and the flow goes to the if statement). All I want to do is to save data in A while navigating from A to B.

Body:
Not the best approach to follow (I'd suggest to share data using shared stateful view model but from your question it is not clear if you are using view models at all) :

Supply your fragment B with action like this:

        <action
            android:id="@+id/backToA"
            app:destination="@+id/A"
            app:popUpTo="@+id/B"
            app:popUpToInclusive="true" />

Supply your fragment A with needed arguments that you'll pass from B.

From B, instead of navigateUp use navigate with action backToA and supply arguments you need to provide to A

You'll also have to take care of manual handling of "back by system back button" scenario (to override navigateUp), as well as, possibly, "back by toolbar back" if you have toolbar - but that's another story.


问:
My tests were running and then I clicked "Run as --> Maven clean" and now when I click "Run as --> Maven test" it doesn't work anymore
My project worked after right-clicking on the pom.xml file in Eclipse and selecting: "Run as --> Maven install" and then "Run as --> Maven test".

I started experimenting around and selected: "Run as --> Maven clean" and then "Run as --> Maven install". This time around I got build errors and couldn't run "Run as --> Maven test". What happened? Why did I get build errors?

I can get the tests to work again if I exit out of Eclipse, delete everything in the .m2 folder, relaunch Eclipse, and click "Run as --> Maven install" twice (the first time produces an error, the second time does the trick). I have no clue as to why this works. I'm confused about what "Maven clean", "Maven install", and "Maven test" do. Yes, I've read the documentation on maven.apache.org but I'm still confused.

Here's my pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.ah</groupId>
  <artifactId>goToLinks</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>GoToLinks</name>

    <dependencies>
        <!-- selenium-java -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.141.59</version>
        </dependency>

        <!-- cucumber-java -->
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>5.7.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-junit -->
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>5.7.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M4</version>
                <configuration>
                    <parallel>methods</parallel>
                    <useUnlimitedThreads>true</useUnlimitedThreads>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

Here's the error I'm getting:

```<code>[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] Source option 5 is no longer supported. Use 7 or later.
[ERROR] Target option 5 is no longer supported. Use 7 or later.
[INFO] 2 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.540 s
[INFO] Finished at: 2020-06-01T19:47:03-04:00
[INFO] ------------------------------------------------------------------------
</code>```

答:
The maven compiler plugin defaults to Java 1.5 but the version of the JDK you use no longer supports that. You can resolve that by configuring the compiler plugin to use a different version of java.

https://maven.apache.org/plugins/maven-compiler-plugin/examples/set-compiler-source-and-target.html

```<code>    <project>
      [...]
      <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
      </properties>
      [...]
    </project>
</code>```

or configure the plugin directly:

```<code>    <project>
      [...]
      <build>
        [...]
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
              <source>1.8</source>
              <target>1.8</target>
            </configuration>
          </plugin>
        </plugins>
        [...]
      </build>
      [...]
    </project>
</code>```

Body:
My project worked after right-clicking on the pom.xml file in Eclipse and selecting: "Run as --> Maven install" and then "Run as --> Maven test".

I started experimenting around and selected: "Run as --> Maven clean" and then "Run as --> Maven install". This time around I got build errors and couldn't run "Run as --> Maven test". What happened? Why did I get build errors?

I can get the tests to work again if I exit out of Eclipse, delete everything in the .m2 folder, relaunch Eclipse, and click "Run as --> Maven install" twice (the first time produces an error, the second time does the trick). I have no clue as to why this works. I'm confused about what "Maven clean", "Maven install", and "Maven test" do. Yes, I've read the documentation on maven.apache.org but I'm still confused.

Here's my pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.ah</groupId>
  <artifactId>goToLinks</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>GoToLinks</name>

    <dependencies>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.141.59</version>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>5.7.0</version>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>5.7.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M4</version>
                <configuration>
                    <parallel>methods</parallel>
                    <useUnlimitedThreads>true</useUnlimitedThreads>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Here's the error I'm getting:

[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] Source option 5 is no longer supported. Use 7 or later.
[ERROR] Target option 5 is no longer supported. Use 7 or later.
[INFO] 2 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.540 s
[INFO] Finished at: 2020-06-01T19:47:03-04:00
[INFO] ------------------------------------------------------------------------

Body:
The maven compiler plugin defaults to Java 1.5 but the version of the JDK you use no longer supports that. You can resolve that by configuring the compiler plugin to use a different version of java.

https://maven.apache.org/plugins/maven-compiler-plugin/examples/set-compiler-source-and-target.html

    <project>
      [...]
      <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
      </properties>
      [...]
    </project>

or configure the plugin directly:

    <project>
      [...]
      <build>
        [...]
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
              <source>1.8</source>
              <target>1.8</target>
            </configuration>
          </plugin>
        </plugins>
        [...]
      </build>
      [...]
    </project>


问:
How to select correct sound output device in the NAudio, after added/removed a sound device?
I am using the NAudio library to test audio output devices on Win based PC.
Now, when I launch app, everything works fine, until I add, or remove new audio device - such as stick/remove headphones to the headphones audio jack.
Since this moment on, the static list of devices: var devs = NAudio.Wave.DirectSoundOut.Devices gets updated.
I look at the devices names, determine its index - in the IEnumerable devs
 but when I set the desired device number:

```<code>_nAudioSoundOut = new NAudio.Wave.WaveOut() { DeviceNumber = wantedDeviceIndex};
</code>```

then Init and play:

```<code>_nAudioSoundOut.Init(_mp3Reader);
_nAudioSoundOut.Play();
</code>```

then some of the devices seem to be confused (swapped).
Is there something I missed, doing wrong, or did I spot a bug ?

Yes, I made sure, I index proper device by its name, and yes I did consider the -1 to the index, as -1st is the default windows device, and first in the list is actually 0.

Thank you !

答:
The problem was, I used the static device list devs = NAudio.Wave.DirectSoundOut.Devices
which does not maintain same order as devices in NAudio.Wave.WaveOut.. Strange and confusing.
Hence, this is what I had to do to get fixed..

```<code>for (int idx = 0; idx < NAudio.Wave.WaveOut.DeviceCount; ++idx)
    {
        string devName = NAudio.Wave.WaveOut.GetCapabilities(idx).ProductName;
        if (devName.Contains(SelectedSpeaker.DisplayName) || SelectedSpeaker.DisplayName.Contains(devName))
        {
            indexSelectedSpeaker = idx;
            break;
        }
    }
</code>```

Body:
I am using the NAudio library to test audio output devices on Win based PC.
Now, when I launch app, everything works fine, until I add, or remove new audio device - such as stick/remove headphones to the headphones audio jack.
Since this moment on, the static list of devices: var devs = NAudio.Wave.DirectSoundOut.Devices gets updated.
I look at the devices names, determine its index - in the IEnumerable devs
 but when I set the desired device number:

_nAudioSoundOut = new NAudio.Wave.WaveOut() { DeviceNumber = wantedDeviceIndex};

then Init and play:

_nAudioSoundOut.Init(_mp3Reader);
_nAudioSoundOut.Play();

then some of the devices seem to be confused (swapped).
Is there something I missed, doing wrong, or did I spot a bug ?

Yes, I made sure, I index proper device by its name, and yes I did consider the -1 to the index, as -1st is the default windows device, and first in the list is actually 0.

Thank you !

Body:
The problem was, I used the static device list devs = NAudio.Wave.DirectSoundOut.Devices
which does not maintain same order as devices in NAudio.Wave.WaveOut.. Strange and confusing.
Hence, this is what I had to do to get fixed..

for (int idx = 0; idx < NAudio.Wave.WaveOut.DeviceCount; ++idx)
    {
        string devName = NAudio.Wave.WaveOut.GetCapabilities(idx).ProductName;
        if (devName.Contains(SelectedSpeaker.DisplayName) || SelectedSpeaker.DisplayName.Contains(devName))
        {
            indexSelectedSpeaker = idx;
            break;
        }
    }


问:
How to set authorization header coorectly?
Problem:

In my react native app in order to remove repeated calls I have developed a general POST GET methods in httpClient file. It code is look likes this.

```<code>import axios from 'axios';
import AsyncStorage from '@react-native-community/async-storage';

axios.defaults.headers.post['Content-Type'] = 'application/json';

var instance = null;

const setAuthorisationHeder = async () => {
  const token = JSON.parse(await AsyncStorage.getItem('auth_data'));
  if (token) {
    console.log('>>>>>> instance', instance);
    Object.assign(instance.headers, {
      Authorization: 'Bearer' + token.accessToken,
    });
  } else {
    console.log('>>>>>> instance', instance);
    Object.assign(instance.headers, {
      Authorization: '',
    });
  }
};

export const setHeader = () => {
  console.log('>>>>>>>> HIIII');
  instance = axios.create({
    baseURL: '',
    timeout: 150000,
    headers: {
      'Content-Type': 'application/json',
    },
  });
  instance.interceptors.response.use(
    function (response) {
      return response;
    },
    async function (error) {
      if (error.response.status) {
        if (error.response.status === 401) {
          AsyncStorage.removeItem('auth_data');
        } else {
          throw error;
        }
      } else {
        console.log(error);
      }
    },
  );
};

export const Get = (route, data) => {
  function getData() {
    return instance.get(
      route,
      data == null ? {data: {}} : {data: JSON.stringify(data)},
    );
  }
  if (instance) {
    console.log('>>>>>> HIIIIii');
    // setAuthorisationHeder();
    return getData();
  }
  return setHeader().then(getData);
};

export const Post = (route, data) => {
  console.log('>>>>>> route', route);
  function postData() {
    return instance.post(route, JSON.stringify(data));
  }
  if (instance) {
    console.log('>>>>>> HIIIIii');
    // setAuthorisationHeder();
    // setAuthorisationHeder();
    return postData();
  }

  return setHeader().then(postData);
};
</code>```

Can some tell me a way to add an authorization header to this instance? My token is storing the Asyncstorage in the middle of some actions so at the beginning called I don't have the token. As my code setHeader is running only one time so I created a method call setAuthorisationHeder() function. But it is giving me can not find property .then error when I am putting a request. Can someone help me to solve this issue? Thank you?

答:
you can define global headers once and use it in every network call.

https://github.com/axios/axios#global-axios-defaults

Body:
Problem:

In my react native app in order to remove repeated calls I have developed a general POST GET methods in httpClient file. It code is look likes this.

import axios from 'axios';
import AsyncStorage from '@react-native-community/async-storage';

axios.defaults.headers.post['Content-Type'] = 'application/json';

var instance = null;

const setAuthorisationHeder = async () => {
  const token = JSON.parse(await AsyncStorage.getItem('auth_data'));
  if (token) {
    console.log('>>>>>> instance', instance);
    Object.assign(instance.headers, {
      Authorization: 'Bearer' + token.accessToken,
    });
  } else {
    console.log('>>>>>> instance', instance);
    Object.assign(instance.headers, {
      Authorization: '',
    });
  }
};

export const setHeader = () => {
  console.log('>>>>>>>> HIIII');
  instance = axios.create({
    baseURL: '',
    timeout: 150000,
    headers: {
      'Content-Type': 'application/json',
    },
  });
  instance.interceptors.response.use(
    function (response) {
      return response;
    },
    async function (error) {
      if (error.response.status) {
        if (error.response.status === 401) {
          AsyncStorage.removeItem('auth_data');
        } else {
          throw error;
        }
      } else {
        console.log(error);
      }
    },
  );
};

export const Get = (route, data) => {
  function getData() {
    return instance.get(
      route,
      data == null ? {data: {}} : {data: JSON.stringify(data)},
    );
  }
  if (instance) {
    console.log('>>>>>> HIIIIii');
    // setAuthorisationHeder();
    return getData();
  }
  return setHeader().then(getData);
};

export const Post = (route, data) => {
  console.log('>>>>>> route', route);
  function postData() {
    return instance.post(route, JSON.stringify(data));
  }
  if (instance) {
    console.log('>>>>>> HIIIIii');
    // setAuthorisationHeder();
    // setAuthorisationHeder();
    return postData();
  }

  return setHeader().then(postData);
};

Can some tell me a way to add an authorization header to this instance? My token is storing the Asyncstorage in the middle of some actions so at the beginning called I don't have the token. As my code setHeader is running only one time so I created a method call setAuthorisationHeder() function. But it is giving me can not find property .then error when I am putting a request. Can someone help me to solve this issue? Thank you?


问:
Flutter: Can't access 'this' in a field initializer to read 'msgTextStyle', when trying to refer to a variable from another variable
I got error when trying to refer to a variable from another variable. In below code, error happen when refer to msgTextStyle in msgList.
Error: "Can't access 'this' in a field initializer to read 'msgTextStyle'."
How to fix this while still keep the my intention, and what is the best practice?
Thank you!</p>

```
    final msgTextStyle = TextStyle(
        fontFamily: 'Roboto',
        fontSize: 18,
        letterSpacing: 0.5,
        height: 2,
    );

    final msgList = Column( children: [
        Text('text 1.',style: msgTextStyle),
        Text('sync: added 4 numbers into call blacklist.',style: msgTextStyle)
    ]);

```

答: It seems like you're trying to access an instance variable (msgTextStyle), in another instance variable(msgList) before constructor is initialized. This is disallowed as you're trying to access something that isn't. Move the initialization of msgList to constructor or initState or perhaps try converting msgTextStyle to const.

Body:
I got error when trying to refer to a variable from another variable. In below code, error happen when refer to msgTextStyle in msgList.
Error: "Can't access 'this' in a field initializer to read 'msgTextStyle'."
How to fix this while still keep the my intention, and what is the best practice?
Thank you!

    final msgTextStyle = TextStyle(
        fontFamily: 'Roboto',
        fontSize: 18,
        letterSpacing: 0.5,
        height: 2,
    );

    final msgList = Column( children: [
        Text('text 1.',style: msgTextStyle),
        Text('sync: added 4 numbers into call blacklist.',style: msgTextStyle)
    ]);


问:
Flutter webview intercept and add headers to all requests
Using the webview_flutter package i could load my website and add session cookies to the initial URL.

```<code>_controller.future.then((controller) {
  _webViewController = controller;
  Map<String, String> header = {'Cookie': 'ci_session=${widget.sessionId}'};
  _webViewController.loadUrl('https://xxxx.com', headers: header);
});
</code>```

In order to keep the session going i need to add the same header for all requests not just for the initial one.
Is there any way to intercept all requests and modify them by adding headers to them?

the closest thing i found was navigationDelegate  but it only returns a NavigationDecision which isn't useful in my case.

答:
You can use my plugin flutter_inappwebview, which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews.

If you need to add custom headers for each request, you can use the shouldOverrideUrlLoading event (you need to enable it using useShouldOverrideUrlLoading: true option).

Instead, if you need to add cookies to your WebView, you can just use the CookieManager class (CookieManager.setCookie method to set a cookie).

Here is an example that set a cookie (named ci_session) in your WebView and also set a custom header (named My-Custom-Header) for each request:

import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;
  CookieManager _cookieManager = CookieManager.instance();

  @override
  void initState() {
    super.initState();

    _cookieManager.setCookie(
      url: "https://github.com/",
      name: "ci_session",
      value: "54th5hfdcfg34",
      domain: ".github.com",
      isSecure: true,
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
          Expanded(
              child: InAppWebView(
            initialUrl: "https://github.com/",
            initialHeaders: {'My-Custom-Header': 'custom_value=564hgf34'},
            initialOptions: InAppWebViewGroupOptions(
              crossPlatform: InAppWebViewOptions(
                debuggingEnabled: true,
                useShouldOverrideUrlLoading: true
              ),
            ),
            onWebViewCreated: (InAppWebViewController controller) {
              webView = controller;
            },
            onLoadStart: (InAppWebViewController controller, String url) {},
            onLoadStop: (InAppWebViewController controller, String url) async {
              List<Cookie> cookies = await _cookieManager.getCookies(url: url);
              cookies.forEach((cookie) {
                print(cookie.name + " " + cookie.value);
              });
            },
            shouldOverrideUrlLoading: (controller, shouldOverrideUrlLoadingRequest) async {
              print("URL: ${shouldOverrideUrlLoadingRequest.url}");

              if (Platform.isAndroid || shouldOverrideUrlLoadingRequest.iosWKNavigationType == IOSWKNavigationType.LINK_ACTIVATED) {
                controller.loadUrl(url: shouldOverrideUrlLoadingRequest.url, headers: {
                  'My-Custom-Header': 'custom_value=564hgf34'
                });
                return ShouldOverrideUrlLoadingAction.CANCEL;
              }
              return ShouldOverrideUrlLoadingAction.ALLOW;
            },
          ))
        ])),
      ),
    );
  }
}
```

Body:
Using the webview_flutter package i could load my website and add session cookies to the initial URL.

_controller.future.then((controller) {
  _webViewController = controller;
  Map<String, String> header = {'Cookie': 'ci_session=${widget.sessionId}'};
  _webViewController.loadUrl('https://xxxx.com', headers: header);
});

In order to keep the session going i need to add the same header for all requests not just for the initial one.
Is there any way to intercept all requests and modify them by adding headers to them?

the closest thing i found was navigationDelegate  but it only returns a NavigationDecision which isn't useful in my case.


问:
Create new file from templates with bash script
I have to create conf files and init.d which are very similar. These files permit to deploy new HTTP service on my servers. These files are the same and only some parameters change from one file to another (listen_port, domain, and path on server.)

As any error in these files leads to dysfunction of service I would like to create these files using a bash script.

For example:

```<code>generate_new_http_service.sh 8282 subdomain.domain.example /home/myapp/rootOfHTTPService
</code>```

I am looking for a kind of templating module that I could use with bash. This templating module would use some generic conf and init.d scripts to create new ones.

Could I could use python templating engine?

答:
you can do this directly in bash, you do not even need sed. Write a script like that:

```<code>#!/bin/bash

cat <<END
this is a template
with $foo
and $bar
END
</code>```

then call it like so:

```<code>foo=FOO bar=BAR ./template
</code>```

Body:
I have to create conf files and init.d which are very similar. These files permit to deploy new HTTP service on my servers. These files are the same and only some parameters change from one file to another (listen_port, domain, and path on server.)

As any error in these files leads to dysfunction of service I would like to create these files using a bash script.

For example:

generate_new_http_service.sh 8282 subdomain.domain.example /home/myapp/rootOfHTTPService

I am looking for a kind of templating module that I could use with bash. This templating module would use some generic conf and init.d scripts to create new ones.

Could I could use python templating engine?

Body:
you can do this directly in bash, you do not even need sed. Write a script like that:

#!/bin/bash

cat <<END
this is a template
with $foo
and $bar
END

then call it like so:

foo=FOO bar=BAR ./template


问:
Is there a way to make a specific variable from a set an integer in Ampl?
```<code>set P;
set K;
set I:= {i in K};
set J:={j in P};
param C {P} >=0;
param A {K,P} >=0;
param B {K} >=0;
var X{j in P} >=0;
</code>```

P consists of 4 set values, namely sweatshirt-f, sweatshirtB/F, tshirtf and tshirtBF, but I would like sweatshirt-f only to return an integer:

```<code>maximize f: sum{j in P} C[j]*X[j];
</code>```

s.t. Constraint {i in K}:

```<code>sum{j in P} A[i,j]*X[j]<=B[i];
</code>```

答:
Option 1: declare all of them as integer, then relax integer constraints for the others:

```<code>var X{j in P} >=0 integer;
let {i in P: i <> "sweatshirt-f"} X[i].relax := 1;
</code>```

Option 2: declare a dummy variable as integer, then constrain relevant value to match it:

```<code>var X{j in P} >=0;
var int_dummy integer;
s.t. force_integer: X["sweatshirt-f"] = int_dummy;
</code>```

I'm not able to test those right now, so you may have to do a little debugging, but that should get you in the neighbourhood of a solution.

Body:
set P;
set K;
set I:= {i in K};
set J:={j in P};
param C {P} >=0;
param A {K,P} >=0;
param B {K} >=0;
var X{j in P} >=0;

P consists of 4 set values, namely sweatshirt-f, sweatshirtB/F, tshirtf and tshirtBF, but I would like sweatshirt-f only to return an integer:

maximize f: sum{j in P} C[j]*X[j];

s.t. Constraint {i in K}:

sum{j in P} A[i,j]*X[j]<=B[i];

Body:
Option 1: declare all of them as integer, then relax integer constraints for the others:

var X{j in P} >=0 integer;
let {i in P: i <> "sweatshirt-f"} X[i].relax := 1;

Option 2: declare a dummy variable as integer, then constrain relevant value to match it:

var X{j in P} >=0;
var int_dummy integer;
s.t. force_integer: X["sweatshirt-f"] = int_dummy;

I'm not able to test those right now, so you may have to do a little debugging, but that should get you in the neighbourhood of a solution.


答:
Create a global auth variable where you'll store the auth data from storage. Before making a request get the auth data and use interceptor to set the bearer token.

```<code>let authToken = '';

const getAuthToken = async () => {
  // asumming auth token was saved as string
  authToken = await AsyncStorage.getItem('auth_data');
};
</code>```

Interceptor

```<code>// request interceptor
axiosInstance.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    config.headers.Authorization = `Bearer ${authToken}`;

    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);
</code>```

complete code

```<code>import axios from 'axios';
import AsyncStorage from '@react-native-community/async-storage';

let authToken = '';

const axiosInstance = axios.create({
  baseURL: '',
  timeout: 150000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// request interceptor
axiosInstance.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    config.headers.Authorization = `Bearer ${authToken}`;

    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

const getAuthToken = async () => {
  // asumming auth token was saved as string
  authToken = await AsyncStorage.getItem('auth_data');
};

export const Get = async (route, data = {}) => {
  // get and set auth token
  await getAuthToken();
  // route = /user?id=787878 or /user/787878
  return await axiosInstance.get(route);
};

export const Post = async (route, data = {}) => {
  await getAuthToken();
  return await axiosInstance.post(route, data);
};
</code>```

Title: How to set authorization header coorectly?

Body:
Create a global auth variable where you'll store the auth data from storage. Before making a request get the auth data and use interceptor to set the bearer token.

let authToken = '';

const getAuthToken = async () => {
  // asumming auth token was saved as string
  authToken = await AsyncStorage.getItem('auth_data');
};

Interceptor

// request interceptor
axiosInstance.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    config.headers.Authorization = `Bearer ${authToken}`;

    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

complete code

import axios from 'axios';
import AsyncStorage from '@react-native-community/async-storage';

let authToken = '';

const axiosInstance = axios.create({
  baseURL: '',
  timeout: 150000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// request interceptor
axiosInstance.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    config.headers.Authorization = `Bearer ${authToken}`;

    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

const getAuthToken = async () => {
  // asumming auth token was saved as string
  authToken = await AsyncStorage.getItem('auth_data');
};

export const Get = async (route, data = {}) => {
  // get and set auth token
  await getAuthToken();
  // route = /user?id=787878 or /user/787878
  return await axiosInstance.get(route);
};

export const Post = async (route, data = {}) => {
  await getAuthToken();
  return await axiosInstance.post(route, data);
};


问:
How can I convert multiple SQL records logs to one new single record?
I need to work with some logs and I realized they are saved on multiple SQL records.
For example :

As you can see, for the same "TRO_IdOrdre" I have different "TRO_TypeTrc" and so differents dates.
I know that each "TRO_TypeTrc" has a specific signification. For example :

1 : creation of the mission

2 : beginning of the mission

4 : end of the mission
etc.

The problem is not every mission has the same number of lines. It can be created and never start or it can start and then cancelled.

So I would like to know if there is a way to transform all my table in a new table with something like that :

Order Id

Creation date

Start date

End date

cancelled ? (yes/no)

cancelled date

Thanks

答:
You can use conditional aggregation:

```<code>select TRO_IdOrdre,
       max(case when TRO_TypeTrc = 1 then tro_date end),
       max(case when TRO_TypeTrc = 2 then tro_date end),
       max(case when TRO_TypeTrc = 6 then tro_date end),
       max(case when TRO_TypeTrc = 8 then tro_date end),
       coalesce(max(case when TRO_TypeTrc = 4 then 'Yes' end), 'No') as is_cancelled
from t
group by TRO_IdOrdre;
</code>```

You can fill in the names of the columns.

Body:
You can use conditional aggregation:

select TRO_IdOrdre,
       max(case when TRO_TypeTrc = 1 then tro_date end),
       max(case when TRO_TypeTrc = 2 then tro_date end),
       max(case when TRO_TypeTrc = 6 then tro_date end),
       max(case when TRO_TypeTrc = 8 then tro_date end),
       coalesce(max(case when TRO_TypeTrc = 4 then 'Yes' end), 'No') as is_cancelled
from t
group by TRO_IdOrdre;

You can fill in the names of the columns.


问:
How to evaluate index i in an if statement within a for loop in R?
I would like to create a new variable "Diff", which i-th value is the difference between the i-th value of the variable "Date" and the (i-1)th value of the variable "Date" itself.
Something like:

```<code>df$Date[2]-df$Date[1]
</code>```

iterated over the sequence 1:lenght(df$Date).

Obviously there is a problem when i is initialized at i=1, because i-1=0.

Trying to avoid this problem, nesting an if...else... statement within a for loop, I cannot manage to have "if" evaluating "i".

R gives me a syntax error which does not exist if I change the "if" condition.

This is my first attempt:

```<code>for (i in 1:length(df$Date)) {
  if (i=1) {
     df$Diff[[i]]<-0
  } else {
  df$Diff[[i]]<-df$Date[[i]] - df$Date[[i-1]]
  }
}
</code>```

The error is:

```<code>unexpected '}' in "  }"
</code>```

which is the "}" closing the else statement.

This is one of the (dirty) solutions I have found (sintax and parenthesis are the same):

```<code>for (i in 1:length(df$Date)) {
    if (df$Date[i]==df$Date[1]) {
        df$Diff[[i]]<-0
    } else {
        df$Diff[[i]]<-df$Date[[i]] - df$Date[[i-1]]
    }
}
</code>```

However, my question here is:
how can I directly evaluate the index (i, e.g.) of a for loop inside an if statement nested within the for loop?

Thank you for help and patience.

答:
Evaluating inside a for loop is no problem:

```<code>for (i in 1:10) {
  if (i  == 5) {print(i)}
  else {print("i is not 5")}
}
</code>```

As @Martin Gal mentioned, the problem is that you set (i=1) and not (i==1). I think another way to accomplish what you want to do using dplyr would be this:

```<code>library(dplyr)
df$Diff[[1]] <- 0
df %>%
  mutate(Diff = Date - lag(Date))
</code>```

Body:
I would like to create a new variable "Diff", which i-th value is the difference between the i-th value of the variable "Date" and the (i-1)th value of the variable "Date" itself.
Something like:

df$Date[2]-df$Date[1]

iterated over the sequence 1:lenght(df$Date).

Obviously there is a problem when i is initialized at i=1, because i-1=0.

Trying to avoid this problem, nesting an if...else... statement within a for loop, I cannot manage to have "if" evaluating "i".

R gives me a syntax error which does not exist if I change the "if" condition.

This is my first attempt:

for (i in 1:length(df$Date)) {
  if (i=1) {
     df$Diff[[i]]<-0
  } else {
  df$Diff[[i]]<-df$Date[[i]] - df$Date[[i-1]]
  }
}

The error is:

unexpected '}' in "  }"

which is the "}" closing the else statement.

This is one of the (dirty) solutions I have found (sintax and parenthesis are the same):

for (i in 1:length(df$Date)) {
    if (df$Date[i]==df$Date[1]) {
        df$Diff[[i]]<-0
    } else {
        df$Diff[[i]]<-df$Date[[i]] - df$Date[[i-1]]
    }
}

However, my question here is:
how can I directly evaluate the index (i, e.g.) of a for loop inside an if statement nested within the for loop?

Thank you for help and patience.

Body:
Evaluating inside a for loop is no problem:

for (i in 1:10) {
  if (i  == 5) {print(i)}
  else {print("i is not 5")}
}

As @Martin Gal mentioned, the problem is that you set (i=1) and not (i==1). I think another way to accomplish what you want to do using dplyr would be this:

library(dplyr)
df$Diff[[1]] <- 0
df %>%
  mutate(Diff = Date - lag(Date))


问:
How can I fix "index out of Range" for a multi-dimensional view in SwiftUI
I tried as much as I could before asking the next "Index out of Range" question, because generally I understand why an index out of range issue occurs, but this specific issues makes me crazy:

```<code>struct Parent: Identifiable {
    let id = UUID()
    let name: String
    var children: [Child]?
}

struct Child: Identifiable {
    let id = UUID()
    let name: String
    var puppets: [Puppet]?
}

struct Puppet: Identifiable {
    let id = UUID()
    let name: String
}

class AppState: ObservableObject {
    @Published var parents: [Parent]
    init() {
        self.parents = [
            Parent(name: "Foo", children: [Child(name: "bar", puppets: [Puppet(name: "Tom")])]),
            Parent(name: "FooBar", children: [Child(name: "foo", puppets: nil)]),
            Parent(name: "FooBar", children: nil)
        ]
    }
}

struct ContentView: View {
    @EnvironmentObject var appState: AppState
    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach (appState.parents.indices, id: \.self) { parentIndex in
                        NavigationLink (destination: ChildrenView(parentIndex: parentIndex).environmentObject(self.appState)) {
                            Text(self.appState.parents[parentIndex].name)
                        }
                    }
                    .onDelete(perform: deleteItem)
                }
                Button(action: {
                    self.appState.parents.append(Parent(name: "Test", children: nil))
                }) {
                    Text("Add")
                }
                .padding(.bottom, 15)
            }
        .navigationBarTitle(Text("Parents"))
        }
    }
    private func deleteItem(at indexSet: IndexSet) {
        self.appState.parents.remove(atOffsets: indexSet)
    }
}

struct ChildrenView: View {
    @EnvironmentObject var appState: AppState
    var parentIndex: Int
    var body: some View {
        let children = appState.parents[parentIndex].children
        return VStack {
            List {
                if (children?.indices != nil) {
                    ForEach (children!.indices, id: \.self) { childIndex in
                        NavigationLink (destination: PuppetsView(parentIndex: self.parentIndex, childIndex: childIndex).environmentObject(self.appState)) {
                            Text(children![childIndex].name)
                        }
                    }
                    .onDelete(perform: deleteItem)
                }
            }
            Button(action: {
                var children = self.appState.parents[self.parentIndex].children
                if (children != nil) {
                    children?.append(Child(name: "Teest"))
                } else {
                    children = [Child(name: "Teest")]
                }
            }) {
                Text("Add")
            }
            .padding(.bottom, 15)
        }
        .navigationBarTitle(Text("Children"))
    }
    private func deleteItem(at indexSet: IndexSet) {
        if (self.appState.parents[self.parentIndex].children != nil) {
            self.appState.parents[self.parentIndex].children!.remove(atOffsets: indexSet)
        }
    }
}

struct PuppetsView: View {
    @EnvironmentObject var appState: AppState
    var parentIndex: Int
    var childIndex: Int
    var body: some View {
        let child = appState.parents[parentIndex].children?[childIndex]
        return VStack {
            List {
                if (child != nil && child!.puppets?.indices != nil) {
                    ForEach (child!.puppets!.indices, id: \.self) { puppetIndex in
                        Text(self.appState.parents[self.parentIndex].children![self.childIndex].puppets![puppetIndex].name)
                    }
                    .onDelete(perform: deleteItem)
                }
            }
            Button(action: {
                var puppets = self.appState.parents[self.parentIndex].children![self.childIndex].puppets
                if (puppets != nil) {
                   puppets!.append(Puppet(name: "Teest"))
                } else {
                   puppets = [Puppet(name: "Teest")]
                }
            }) {
                Text("Add")
            }
            .padding(.bottom, 15)
        }
        .navigationBarTitle(Text("Puppets"))
    }
    private func deleteItem(at indexSet: IndexSet) {
        if (self.appState.parents[self.parentIndex].children != nil) {
            self.appState.parents[self.parentIndex].children![self.childIndex].puppets!.remove(atOffsets: indexSet)
        }
    }
}
</code>```

I can remove both children of Foo and FooBar without issues, but when I remove the Puppet of child bar first, then the app crashes like shown in the comments.

I unterstand that the childIndex doesn't exist anymore, but I don't understand why the view gets built again when there is no child with puppets.

答:
All the referencing of array indices looks pretty awful to me. Using array indices also requires that you pass the various objects down to the subviews.

To address this I started by changing your models - Make them classes rather than structs so you can make them @ObservableObject.  They also need to be Hashable and Equatable.

I also added add and remove functions to the model objects so that you don't need to worry about indices when adding/removing children/puppets.  The remove methods use an array extension that removes an Identifiable object without needing to know the index.

Finally, I changed the children and puppets arrays to be non-optional.  There is little semantic difference between a nil optional and an empty non-optional array, but the latter is much easier to deal with.

```<code>class Parent: ObservableObject, Hashable {

    static func == (lhs: Parent, rhs: Parent) -> Bool {
        lhs.id == rhs.id
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }

    let id = UUID()
    let name: String
    @Published var children: [Child]

    init(name: String, children: [Child]? = nil) {
        self.name = name
        self.children = children ?? []
    }

    func remove(child: Child) {
        self.children.remove(child)
    }

    func add(child: Child) {
        self.children.append(child)
    }
}

class Child: ObservableObject, Identifiable, Hashable {
    static func == (lhs: Child, rhs: Child) -> Bool {
        return lhs.id == rhs.id
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }

    let id = UUID()
    let name: String
    @Published var puppets: [Puppet]

    init(name: String, puppets:[Puppet]? = nil) {
        self.name = name
        self.puppets = puppets ?? []
    }

    func remove(puppet: Puppet) {
        self.puppets.remove(puppet)
    }

    func add(puppet: Puppet) {
        self.puppets.append(puppet)
    }
}

struct Puppet: Identifiable, Hashable {
    let id = UUID()
    let name: String
}

class AppState: ObservableObject {
    @Published var parents: [Parent]
    init() {
        self.parents = [
            Parent(name: "Foo", children: [Child(name: "bar", puppets: [Puppet(name: "Tom")])]),
            Parent(name: "FooBar", children: [Child(name: "foo", puppets: nil)])
        ]
    }
}

extension Array where Element: Identifiable {
    mutating func remove(_ object: Element) {
        if let index = self.firstIndex(where: { $0.id == object.id}) {
            self.remove(at: index)
        }
    }
}
</code>```

Having sorted out the model, the views then only need to know about their specific item:

```<code>struct ContentView: View {
    @EnvironmentObject var appState: AppState
    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach (appState.parents, id: \.self) {  parent in
                        NavigationLink (destination: ChildrenView(parent: parent)) {
                            Text(parent.name)
                        }
                    }
                    .onDelete(perform: deleteItem)
                }
                Button(action: {
                    self.appState.parents.append(Parent(name: "Test", children: nil))
                }) {
                    Text("Add")
                }
                .padding(.bottom, 15)
            }
            .navigationBarTitle(Text("Parents"))
        }
    }
    private func deleteItem(at indexSet: IndexSet) {
        self.appState.parents.remove(atOffsets: indexSet)
    }
}

struct ChildrenView: View {
    @ObservedObject var parent: Parent
    var body: some View {
        VStack {
            List {
                ForEach (self.parent.children, id: \.self) { child in
                    NavigationLink (destination: PuppetsView(child:child)) {
                        Text(child.name)
                    }
                }
                .onDelete(perform: deleteItem)
            }
            Button(action: {
                self.parent.add(child: Child(name: "Test"))
            }) {
                Text("Add")
            }
            .padding(.bottom, 15)
        }
        .navigationBarTitle(Text("Children"))
    }

    private func deleteItem(at indexSet: IndexSet) {
        let children = Array(indexSet).map { self.parent.children[$0]}
        for child in children {
            self.parent.remove(child: child)
        }
    }
}

struct PuppetsView: View {
    @ObservedObject var child: Child
    var body: some View {
        VStack {
            List {
                ForEach (child.puppets, id: \.self) { puppet in
                    Text(puppet.name)
                }
                .onDelete(perform: deleteItem)
            }
            Button(action: {
                self.child.add(puppet:Puppet(name: "Test"))
            })
            {
                Text("Add")
            }
            .padding(.bottom, 15)
        }
        .navigationBarTitle(Text("Puppets"))
    }

    func deleteItem(at indexSet: IndexSet) {
        let puppets = Array(indexSet).map { self.child.puppets[$0] }
        for puppet in puppets {
            self.child.remove(puppet:puppet)
        }
    }
}
</code>```

Body:
I tried as much as I could before asking the next "Index out of Range" question, because generally I understand why an index out of range issue occurs, but this specific issues makes me crazy:

struct Parent: Identifiable {
    let id = UUID()
    let name: String
    var children: [Child]?
}

struct Child: Identifiable {
    let id = UUID()
    let name: String
    var puppets: [Puppet]?
}

struct Puppet: Identifiable {
    let id = UUID()
    let name: String
}

class AppState: ObservableObject {
    @Published var parents: [Parent]
    init() {
        self.parents = [
            Parent(name: "Foo", children: [Child(name: "bar", puppets: [Puppet(name: "Tom")])]),
            Parent(name: "FooBar", children: [Child(name: "foo", puppets: nil)]),
            Parent(name: "FooBar", children: nil)
        ]
    }
}

struct ContentView: View {
    @EnvironmentObject var appState: AppState
    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach (appState.parents.indices, id: \.self) { parentIndex in
                        NavigationLink (destination: ChildrenView(parentIndex: parentIndex).environmentObject(self.appState)) {
                            Text(self.appState.parents[parentIndex].name)
                        }
                    }
                    .onDelete(perform: deleteItem)
                }
                Button(action: {
                    self.appState.parents.append(Parent(name: "Test", children: nil))
                }) {
                    Text("Add")
                }
                .padding(.bottom, 15)
            }
        .navigationBarTitle(Text("Parents"))
        }
    }
    private func deleteItem(at indexSet: IndexSet) {
        self.appState.parents.remove(atOffsets: indexSet)
    }
}

struct ChildrenView: View {
    @EnvironmentObject var appState: AppState
    var parentIndex: Int
    var body: some View {
        let children = appState.parents[parentIndex].children
        return VStack {
            List {
                if (children?.indices != nil) {
                    ForEach (children!.indices, id: \.self) { childIndex in
                        NavigationLink (destination: PuppetsView(parentIndex: self.parentIndex, childIndex: childIndex).environmentObject(self.appState)) {
                            Text(children![childIndex].name)
                        }
                    }
                    .onDelete(perform: deleteItem)
                }
            }
            Button(action: {
                var children = self.appState.parents[self.parentIndex].children
                if (children != nil) {
                    children?.append(Child(name: "Teest"))
                } else {
                    children = [Child(name: "Teest")]
                }
            }) {
                Text("Add")
            }
            .padding(.bottom, 15)
        }
        .navigationBarTitle(Text("Children"))
    }
    private func deleteItem(at indexSet: IndexSet) {
        if (self.appState.parents[self.parentIndex].children != nil) {
            self.appState.parents[self.parentIndex].children!.remove(atOffsets: indexSet)
        }
    }
}

struct PuppetsView: View {
    @EnvironmentObject var appState: AppState
    var parentIndex: Int
    var childIndex: Int
    var body: some View {
        let child = appState.parents[parentIndex].children?[childIndex]
        return VStack {
            List {
                if (child != nil && child!.puppets?.indices != nil) {
                    ForEach (child!.puppets!.indices, id: \.self) { puppetIndex in
                        Text(self.appState.parents[self.parentIndex].children![self.childIndex].puppets![puppetIndex].name)
                    }
                    .onDelete(perform: deleteItem)
                }
            }
            Button(action: {
                var puppets = self.appState.parents[self.parentIndex].children![self.childIndex].puppets
                if (puppets != nil) {
                   puppets!.append(Puppet(name: "Teest"))
                } else {
                   puppets = [Puppet(name: "Teest")]
                }
            }) {
                Text("Add")
            }
            .padding(.bottom, 15)
        }
        .navigationBarTitle(Text("Puppets"))
    }
    private func deleteItem(at indexSet: IndexSet) {
        if (self.appState.parents[self.parentIndex].children != nil) {
            self.appState.parents[self.parentIndex].children![self.childIndex].puppets!.remove(atOffsets: indexSet)
        }
    }
}

I can remove both children of Foo and FooBar without issues, but when I remove the Puppet of child bar first, then the app crashes like shown in the comments.

I unterstand that the childIndex doesn't exist anymore, but I don't understand why the view gets built again when there is no child with puppets.

Body:
All the referencing of array indices looks pretty awful to me. Using array indices also requires that you pass the various objects down to the subviews.

To address this I started by changing your models - Make them classes rather than structs so you can make them @ObservableObject.  They also need to be Hashable and Equatable.

I also added add and remove functions to the model objects so that you don't need to worry about indices when adding/removing children/puppets.  The remove methods use an array extension that removes an Identifiable object without needing to know the index.

Finally, I changed the children and puppets arrays to be non-optional.  There is little semantic difference between a nil optional and an empty non-optional array, but the latter is much easier to deal with.

class Parent: ObservableObject, Hashable {

    static func == (lhs: Parent, rhs: Parent) -> Bool {
        lhs.id == rhs.id
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }

    let id = UUID()
    let name: String
    @Published var children: [Child]

    init(name: String, children: [Child]? = nil) {
        self.name = name
        self.children = children ?? []
    }

    func remove(child: Child) {
        self.children.remove(child)
    }

    func add(child: Child) {
        self.children.append(child)
    }
}

class Child: ObservableObject, Identifiable, Hashable {
    static func == (lhs: Child, rhs: Child) -> Bool {
        return lhs.id == rhs.id
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }

    let id = UUID()
    let name: String
    @Published var puppets: [Puppet]

    init(name: String, puppets:[Puppet]? = nil) {
        self.name = name
        self.puppets = puppets ?? []
    }

    func remove(puppet: Puppet) {
        self.puppets.remove(puppet)
    }

    func add(puppet: Puppet) {
        self.puppets.append(puppet)
    }
}

struct Puppet: Identifiable, Hashable {
    let id = UUID()
    let name: String
}

class AppState: ObservableObject {
    @Published var parents: [Parent]
    init() {
        self.parents = [
            Parent(name: "Foo", children: [Child(name: "bar", puppets: [Puppet(name: "Tom")])]),
            Parent(name: "FooBar", children: [Child(name: "foo", puppets: nil)])
        ]
    }
}

extension Array where Element: Identifiable {
    mutating func remove(_ object: Element) {
        if let index = self.firstIndex(where: { $0.id == object.id}) {
            self.remove(at: index)
        }
    }
}

Having sorted out the model, the views then only need to know about their specific item:

struct ContentView: View {
    @EnvironmentObject var appState: AppState
    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach (appState.parents, id: \.self) {  parent in
                        NavigationLink (destination: ChildrenView(parent: parent)) {
                            Text(parent.name)
                        }
                    }
                    .onDelete(perform: deleteItem)
                }
                Button(action: {
                    self.appState.parents.append(Parent(name: "Test", children: nil))
                }) {
                    Text("Add")
                }
                .padding(.bottom, 15)
            }
            .navigationBarTitle(Text("Parents"))
        }
    }
    private func deleteItem(at indexSet: IndexSet) {
        self.appState.parents.remove(atOffsets: indexSet)
    }
}

struct ChildrenView: View {
    @ObservedObject var parent: Parent
    var body: some View {
        VStack {
            List {
                ForEach (self.parent.children, id: \.self) { child in
                    NavigationLink (destination: PuppetsView(child:child)) {
                        Text(child.name)
                    }
                }
                .onDelete(perform: deleteItem)
            }
            Button(action: {
                self.parent.add(child: Child(name: "Test"))
            }) {
                Text("Add")
            }
            .padding(.bottom, 15)
        }
        .navigationBarTitle(Text("Children"))
    }

    private func deleteItem(at indexSet: IndexSet) {
        let children = Array(indexSet).map { self.parent.children[$0]}
        for child in children {
            self.parent.remove(child: child)
        }
    }
}

struct PuppetsView: View {
    @ObservedObject var child: Child
    var body: some View {
        VStack {
            List {
                ForEach (child.puppets, id: \.self) { puppet in
                    Text(puppet.name)
                }
                .onDelete(perform: deleteItem)
            }
            Button(action: {
                self.child.add(puppet:Puppet(name: "Test"))
            })
            {
                Text("Add")
            }
            .padding(.bottom, 15)
        }
        .navigationBarTitle(Text("Puppets"))
    }

    func deleteItem(at indexSet: IndexSet) {
        let puppets = Array(indexSet).map { self.child.puppets[$0] }
        for puppet in puppets {
            self.child.remove(puppet:puppet)
        }
    }
}


问:
Configuration to get the images from the apache
I have multiple Tomcat servers. In each tomcat I am loading all images. I want to move the images from Tomcat to Apache and access the images from there.

My question is: is there any configuration to get the images in a Java web application from Apache instead of Tomcat?

答:
Hide your tomcat servers behind an apache server and then you can do something like this:

```<code><VirtualHost www.example.com:80>
    ServerName      www.example.com
    DocumentRoot    /var/www/html
    ProxyPass       /img    !
    ProxyPass       /       ajp://localhost:1234/
</VirtualHost>
</code>```

Apache will serve /img from /var/www/html/img and other requests will be sent to tomcat. This configuration needs mod_proxy_ajp apache module to be active. Tomcat must listen to AJP requests on the given port, use:

```<code><Connector port="1234" protocol="AJP/1.3" redirectPort="8443" address="127.0.0.1" URIEncoding="UTF-8" />
</code>```

And configure tomcat to serve www.example.com or the default virtual host.

```<code><Host
    name="www.example.com"
    appBase="/path/to/tomcat/apps/www.example.com"
    unpackWARs="true"
    autoDeploy="true"
    xmlValidation="false"
    xmlNamespaceAware="false"
/>
</code>```

or

```<code><Host
    name="localhost"
    appBase="/path/to/tomcat/apps/www.example.com"
    unpackWARs="true"
    autoDeploy="true"
    xmlValidation="false"
    xmlNamespaceAware="false"
/>
</code>```

Deploy your webapp to /path/to/tomcat/apps/www.example.com/ as ROOT.war, this should be enough to have the whole setup up and running.

ContentLicense: CC BY-SA 2.5

Body:
Hide your tomcat servers behind an apache server and then you can do something like this:

<VirtualHost www.example.com:80>
    ServerName      www.example.com
    DocumentRoot    /var/www/html
    ProxyPass       /img    !
    ProxyPass       /       ajp://localhost:1234/
</VirtualHost>

Apache will serve /img from /var/www/html/img and other requests will be sent to tomcat. This configuration needs mod_proxy_ajp apache module to be active. Tomcat must listen to AJP requests on the given port, use:

<Connector port="1234" protocol="AJP/1.3" redirectPort="8443" address="127.0.0.1" URIEncoding="UTF-8" />

And configure tomcat to serve www.example.com or the default virtual host.

<Host
    name="www.example.com"
    appBase="/path/to/tomcat/apps/www.example.com"
    unpackWARs="true"
    autoDeploy="true"
    xmlValidation="false"
    xmlNamespaceAware="false"
/>

or

<Host
    name="localhost"
    appBase="/path/to/tomcat/apps/www.example.com"
    unpackWARs="true"
    autoDeploy="true"
    xmlValidation="false"
    xmlNamespaceAware="false"
/>

Deploy your webapp to /path/to/tomcat/apps/www.example.com/ as ROOT.war, this should be enough to have the whole setup up and running.


问:
How to evaluate the code provided by user?
I need to process some user-provided code on the server using PHP. The code is about to cover some very basic programming capabilities, for example: variables, literals, (preferably) functions, and some associated operations.

An option is to use the dangerous function of eval(). For my specific case, it's overwhelmingly & redundantly full featured, apart from its security issues and performance bottlenecks. Sanitizing the tokens using token_get_all() protects against Murphy, not Machiavelli! Regardless of its downsides, it's truly capable of what I'm tiring to achieve.

I've also checked the Symphony's ExpressionLanguage; it has some shortcomings:

it cannot detect the "variables" on its own (they should be introduced and known beforehand)

it lacks basic variable functionalities (only initializes them: no assignment functionality)

it's designed only for "one liner" expressions

Alas! a more sophisticated ExpressionLanguage would've sufficed.

I'm looking for something that allows some very basic "programming" capability to the users. Is there such a thing, if so, what is it? (even though it's written in another language, but is utilizable somehow on a server.)
If such a thing is not around, then how should I treat the eval() to not to drawn me?! Or, as a last-resort, how may I design a such a simple programming capability? (Please elaborate on the matters :)

As per comments below, here is a list of "programming" features the code syntax needs to support. It would've sufficed if the followings were supported in addition to what the ExpressionLanguage systax provides:

The sequence flow: executing the instruction one after another (contrary to the "one liner" nature of the ExpressionLanguage)

Local variable declaration (and their detections afterwards, of course)

Variable assignments from expressions (any composition of literals, function invocations, operators)

Passing variables to functions

Flow control constructs: at least a conditional construct (e.g: if) and a repetition construct (e.g: for loop)

答:
Maybe can you take a look on Docker. For example you can copy user code into a file on your server (without execute it) and then run it inside a container. This will allow you to :

run code into a specific dedicated container which can be destroyed after script execution

run code using different version of PHP

Some example :

```<code>docker run -v "$PWD":/usr/src -w /usr/src --rm php:7.4.5 php ./myScript.php
</code>```

This will execute file myScript.php into a new container based on php 7.4.5, once done container will be deleted.

Same thing using another PHP version :

```<code>docker run -v "$PWD":/usr/src -w /usr/src --rm php:5.6 php ./myScript.php
</code>```

Usefull links :

https://docs.docker.com/engine/reference/commandline/run/

https://hub.docker.com/_/php/?tab=description

Edit regarding performances :

Obviously running code using a container will be longer than running code directly from PHP.

For example, we can test it running the following code :

```<code><?php

function reverseArray(array $array): array {
    for ($i = 0; $i < count($array) / 2; $i++) {
        $tmp = $array[$i];
        $array[$i] = $array[count($array) -1 - $i];
        $array[count($array) - 1 - $i] = $tmp;
    }
    return $array;
}

$tabToReverse = [5, 8, 95, 10, 6, 17, 42, 20];
echo 'Reversed array : '."\n";
echo  implode(' ', reverseArray($tabToReverse));
</code>```

Same code with a syntax error :

```<code><?php

// syntax error
function reverseArray($array: array): array {
    for ($i = 0; $i < count($array) / 2; $i++) {
        $tmp = $array[$i];
        $array[$i] = $array[count($array) -1 - $i];
        $array[count($array) - 1 - $i] = $tmp;
    }
    return $array;
}

$tabToReverse = [5, 8, 95, 10, 6, 17, 42, 20];
echo 'Reversed array : '."\n";
echo  implode(' ', reverseArray($tabToReverse));
</code>```

The following PHP code will compare both executions (plus one with some syntax error):

```<code><?php

/**
 * Run code using eval
 */
$start = microtime(true);
$code = str_replace('<?php', '', file_get_contents('./reverseArray.php'));
echo eval($code)."\n";
$end = microtime(true);
$duration = $end - $start;
echo "Duration using eval $duration\n";

/**
 * Run code using container
 */
$start = microtime(true);
$cmd = 'docker run -v "$PWD":/usr/src -w /usr/src --rm php:7.4.5 php ./reverseArray.php';
exec($cmd, $result);
echo implode("\n", $result)."\n";
$end = microtime(true);
$duration = $end - $start;
echo "Duration using container $duration\n";

/**
 * Run code using container with an error
 */
$start = microtime(true);
$cmd = 'docker run -v "$PWD":/usr/src -w /usr/src --rm php:7.4.5 php ./reverseArrayWithError.php';
exec($cmd, $resultWithError);
echo implode("\n", $resultWithError)."\n";
$end = microtime(true);
$duration = $end - $start;
echo "Duration using container $duration\n";
</code>```

The result on my laptop are :

```<code>php ./runCode.php
Reversed array :
20 42 17 6 10 95 8 5
Duration using eval 0.00031089782714844
Reversed array :
20 42 17 6 10 95 8 5
Duration using container 0.79519391059875

Parse error: syntax error, unexpected ':', expecting ')' in /usr/src/reverseArrayWithError.php on line 3
Duration using container 0.81346988677979
</code>```

As you can see running up the container took time. But the code has been executed in a specific area.

In all cases, the frontend part will be the same, it will use some Ajax query in order to POST data on the server, wait for result and display it.

Note 1 : even if code is executed in a specific container it must be sanitized before, as user input should never be trusted.

Note 2 : using this architecture require to manage running containers in order to prevent overload. What happend if 10 000 users submit there code at the same time ? But I think this is another topic.

Body:
Maybe can you take a look on Docker. For example you can copy user code into a file on your server (without execute it) and then run it inside a container. This will allow you to :

run code into a specific dedicated container which can be destroyed after script execution

run code using different version of PHP

Some example :

docker run -v "$PWD":/usr/src -w /usr/src --rm php:7.4.5 php ./myScript.php

This will execute file myScript.php into a new container based on php 7.4.5, once done container will be deleted.

Same thing using another PHP version :

docker run -v "$PWD":/usr/src -w /usr/src --rm php:5.6 php ./myScript.php

Usefull links :

https://docs.docker.com/engine/reference/commandline/run/

https://hub.docker.com/_/php/?tab=description

Edit regarding performances :

Obviously running code using a container will be longer than running code directly from PHP.

For example, we can test it running the following code :

<?php

function reverseArray(array $array): array {
    for ($i = 0; $i < count($array) / 2; $i++) {
        $tmp = $array[$i];
        $array[$i] = $array[count($array) -1 - $i];
        $array[count($array) - 1 - $i] = $tmp;
    }
    return $array;
}

$tabToReverse = [5, 8, 95, 10, 6, 17, 42, 20];
echo 'Reversed array : '."\n";
echo  implode(' ', reverseArray($tabToReverse));

Same code with a syntax error :

<?php

// syntax error
function reverseArray($array: array): array {
    for ($i = 0; $i < count($array) / 2; $i++) {
        $tmp = $array[$i];
        $array[$i] = $array[count($array) -1 - $i];
        $array[count($array) - 1 - $i] = $tmp;
    }
    return $array;
}

$tabToReverse = [5, 8, 95, 10, 6, 17, 42, 20];
echo 'Reversed array : '."\n";
echo  implode(' ', reverseArray($tabToReverse));

The following PHP code will compare both executions (plus one with some syntax error):

<?php

/**
 * Run code using eval
 */
$start = microtime(true);
$code = str_replace('<?php', '', file_get_contents('./reverseArray.php'));
echo eval($code)."\n";
$end = microtime(true);
$duration = $end - $start;
echo "Duration using eval $duration\n";

/**
 * Run code using container
 */
$start = microtime(true);
$cmd = 'docker run -v "$PWD":/usr/src -w /usr/src --rm php:7.4.5 php ./reverseArray.php';
exec($cmd, $result);
echo implode("\n", $result)."\n";
$end = microtime(true);
$duration = $end - $start;
echo "Duration using container $duration\n";

/**
 * Run code using container with an error
 */
$start = microtime(true);
$cmd = 'docker run -v "$PWD":/usr/src -w /usr/src --rm php:7.4.5 php ./reverseArrayWithError.php';
exec($cmd, $resultWithError);
echo implode("\n", $resultWithError)."\n";
$end = microtime(true);
$duration = $end - $start;
echo "Duration using container $duration\n";

The result on my laptop are :

php ./runCode.php
Reversed array :
20 42 17 6 10 95 8 5
Duration using eval 0.00031089782714844
Reversed array :
20 42 17 6 10 95 8 5
Duration using container 0.79519391059875

Parse error: syntax error, unexpected ':', expecting ')' in /usr/src/reverseArrayWithError.php on line 3
Duration using container 0.81346988677979

As you can see running up the container took time. But the code has been executed in a specific area.

In all cases, the frontend part will be the same, it will use some Ajax query in order to POST data on the server, wait for result and display it.

Note 1 : even if code is executed in a specific container it must be sanitized before, as user input should never be trusted.

Note 2 : using this architecture require to manage running containers in order to prevent overload. What happend if 10 000 users submit there code at the same time ? But I think this is another topic.