问:
Wait for FragmentTransaction animation to finish
I have an Activity with an EditText and a Button. As soon as there is a number entered in the EditText and the Button is clicked, a Fragment (that covers up the whole screen) is being shown for two seconds, and then removed. Both Transactions have showCustomAnimations() called. In code, after I call commit() on the remove FragmentTransaction, the soft keyboard is shown via showSoftInput().

The problem I face: While the remove animation is running and the Fragment already slid out of the screen by 80%, the softkeyboard pops up. Now if you quickly enter a number and press the button, the app crashes, because the previous animation still was running.

I already saw several answers, but I found them to not be sufficient or working. Any call for commitNow() or executePendingTransitions() doesn't help, as the Transaction is committed, the problem is, that the animation is still running afterwards. The method getVisibleUserHint()to check whether an Activity is visible is deprecated.

Code:

```<code>TrueFragment trueFragment = new TrueFragment();

fabNext.setOnClickListener(new View.OnClickListener() {  //fabNext is my button
        @Override
        public void onClick(View v) {

            fabNext.setEnabled(false);  //blocking button to avoid clicking (... further code for this...)
            inputManager.hideSoftInputFromWindow(constraintLayoutCalculating.getWindowToken(), 0);  //hide Keyboard

            final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();  //FragmentTransaction to show the Fragment
            transaction.setCustomAnimations(R.animator.slide_in, 0);
            transaction.add(R.id.constraintLayoutCalculating, trueFragment);
            transaction.commitAllowingStateLoss();
            getSupportFragmentManager().executePendingTransactions();

            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    FragmentTransaction transaction2 = getSupportFragmentManager().beginTransaction();  //FragmentTransaction to remove the Fragment
                    transaction2.setCustomAnimations(0, R.animator.slide_out);
                    transaction2.remove(trueFragment);
                    transaction2.commitAllowingStateLoss();
                    editText.setText(null);  //reset EditText
                    editText.requestFocus();
                    textInputLayout.setError(null);
                    inputManager.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);  //show Keyboard
                    fabNext.setEnabled(true);  //reenable button at the end - Problem: Button made clickable again, even if the remove FragmentTransaction animation hasn't finished

               }
         }, 1000);
}
</code>```

This is the crash I am getting. A search on StackOverflow showed me that it has to do with starting a FragmentTransaction while another still isn't finished.

```<code> --------- beginning of crash
2020-02-17 10:27:29.787 23467-23467/my.top.secretpreciousname E/AndroidRuntime: FATAL EXCEPTION: main
    my.top.secretpreciousname, PID: 23467
    java.lang.IllegalStateException: Restarter must be created only during owner's initialization stage
        at androidx.savedstate.SavedStateRegistryController.performRestore(SavedStateRegistryController.java:58)
        at androidx.fragment.app.Fragment.performCreate(Fragment.java:2585)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:838)
        at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
        at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
        at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
        at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
        at androidx.fragment.app.FragmentManagerImpl.executePendingTransactions(FragmentManagerImpl.java:183)
        at my.top.secretpreciousname.CalculatingActivity$1.onClick(CalculatingActivity.java:254)
        at android.view.View.performClick(View.java:7339)
        at my.top.secretpreciousname.CalculatingActivity$2.onEditorAction(CalculatingActivity.java:320)
        at android.widget.TextView.doKeyDown(TextView.java:8617)
        at android.widget.TextView.onKeyDown(TextView.java:8486)
        at android.view.KeyEvent.dispatch(KeyEvent.java:3359)
        at android.view.View.dispatchKeyEvent(View.java:13312)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1912)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1912)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1912)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1912)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1912)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1912)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1912)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1912)
</code>```

Is there nice solution for this? Thanks in advance for any help.

答:
It turns out that I have to add the line

```<code>transaction2.addToBackStack(null);
</code>```

to the animated FragmentTransaction to achieve that it won't crash when a new Transaction is triggered before the previous one has finished its animation.
Still not sure if this can be considered as a valid solution, as actually I don't want backstack functionality with these Fragments, so I have to temporarily block the back button or flush the Backstack after every Transaction.

Body:
I have an Activity with an EditText and a Button. As soon as there is a number entered in the EditText and the Button is clicked, a Fragment (that covers up the whole screen) is being shown for two seconds, and then removed. Both Transactions have showCustomAnimations() called. In code, after I call commit() on the remove FragmentTransaction, the soft keyboard is shown via showSoftInput().

The problem I face: While the remove animation is running and the Fragment already slid out of the screen by 80%, the softkeyboard pops up. Now if you quickly enter a number and press the button, the app crashes, because the previous animation still was running.

I already saw several answers, but I found them to not be sufficient or working. Any call for commitNow() or executePendingTransitions() doesn't help, as the Transaction is committed, the problem is, that the animation is still running afterwards. The method getVisibleUserHint()to check whether an Activity is visible is deprecated.

Code:

TrueFragment trueFragment = new TrueFragment();

fabNext.setOnClickListener(new View.OnClickListener() {  //fabNext is my button
        @Override
        public void onClick(View v) {

            fabNext.setEnabled(false);  //blocking button to avoid clicking (... further code for this...)
            inputManager.hideSoftInputFromWindow(constraintLayoutCalculating.getWindowToken(), 0);  //hide Keyboard

            final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();  //FragmentTransaction to show the Fragment
            transaction.setCustomAnimations(R.animator.slide_in, 0);
            transaction.add(R.id.constraintLayoutCalculating, trueFragment);
            transaction.commitAllowingStateLoss();
            getSupportFragmentManager().executePendingTransactions();

            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    FragmentTransaction transaction2 = getSupportFragmentManager().beginTransaction();  //FragmentTransaction to remove the Fragment
                    transaction2.setCustomAnimations(0, R.animator.slide_out);
                    transaction2.remove(trueFragment);
                    transaction2.commitAllowingStateLoss();
                    editText.setText(null);  //reset EditText
                    editText.requestFocus();
                    textInputLayout.setError(null);
                    inputManager.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);  //show Keyboard
                    fabNext.setEnabled(true);  //reenable button at the end - Problem: Button made clickable again, even if the remove FragmentTransaction animation hasn't finished

               }
         }, 1000);
}

This is the crash I am getting. A search on StackOverflow showed me that it has to do with starting a FragmentTransaction while another still isn't finished.

 --------- beginning of crash
2020-02-17 10:27:29.787 23467-23467/my.top.secretpreciousname E/AndroidRuntime: FATAL EXCEPTION: main
    my.top.secretpreciousname, PID: 23467
    java.lang.IllegalStateException: Restarter must be created only during owner's initialization stage
        at androidx.savedstate.SavedStateRegistryController.performRestore(SavedStateRegistryController.java:58)
        at androidx.fragment.app.Fragment.performCreate(Fragment.java:2585)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:838)
        at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
        at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
        at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
        at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
        at androidx.fragment.app.FragmentManagerImpl.executePendingTransactions(FragmentManagerImpl.java:183)
        at my.top.secretpreciousname.CalculatingActivity$1.onClick(CalculatingActivity.java:254)
        at android.view.View.performClick(View.java:7339)
        at my.top.secretpreciousname.CalculatingActivity$2.onEditorAction(CalculatingActivity.java:320)
        at android.widget.TextView.doKeyDown(TextView.java:8617)
        at android.widget.TextView.onKeyDown(TextView.java:8486)
        at android.view.KeyEvent.dispatch(KeyEvent.java:3359)
        at android.view.View.dispatchKeyEvent(View.java:13312)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1912)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1912)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1912)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1912)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1912)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1912)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1912)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1912)

Is there nice solution for this? Thanks in advance for any help.

Body:
It turns out that I have to add the line

transaction2.addToBackStack(null);

to the animated FragmentTransaction to achieve that it won't crash when a new Transaction is triggered before the previous one has finished its animation.
Still not sure if this can be considered as a valid solution, as actually I don't want backstack functionality with these Fragments, so I have to temporarily block the back button or flush the Backstack after every Transaction.


来源: stackexchange

问:
Setting default "View" in AppScript
I have a Google sheet that by default does not show protected ranges.
The user needs to know which range is protected - he can do that by going to Menu->View-> Check "protected ranges".

Is it possible to set the "protected ranges" option to check by default?

答: Unfortunately, at this time Google Apps Script does not have a method for achiving this. If you wish you could make a feature request for a method to perform this HERE.</p>

ContentLicense: CC BY-SA 4.0

Title: Setting default "View" in AppScript


问:
In React, On clicking browser back button I should click one DOM ele(for instance, button) and should be in the same component
```<code>window.addEventListener('beforeunload', () => {
      document.getElementById('sample-button').click()
    })
</code>```

which event listener should be added?

答:
if you are using class component like </p>

```<code>class pp extends React.Component {

  //This method is called when a component is being removed from the DOM:
  componentWillUnmount()
  {
     document.getElementById('sample-button').click()
  }

  render(){
    return ...
}

}
</code>```

Body:
window.addEventListener('beforeunload', () => {
      document.getElementById('sample-button').click()
    })

which event listener should be added?

Body:
if you are using class component like

class pp extends React.Component {

  //This method is called when a component is being removed from the DOM:
  componentWillUnmount()
  {
     document.getElementById('sample-button').click()
  }

  render(){
    return ...
}

}


问:
TCL Expect kills child of child process
I have an expect script like this

```<code>#!/usr/bin/expect -f
set timeout 30
log_user 0

set PASSWORD $::env(PASSWORD)
set USERNAME $::env(USERNAME)
set TOKEN $::env(TOKEN)

puts stderr "Generating OTP"
spawn oathtool --totp $TOKEN
expect -re \\d+
set otp $expect_out(0,string)

puts stderr "Connecting to VPN server"
spawn -ignore HUP env openconnect -b https://vpn
expect "GROUP:"
send "Tech\n"
expect "Username:"
send "$USERNAME\n"
expect "Password:"
send "$PASSWORD\n"
expect "Password:"
send "$otp\n"
expect EOF
</code>```

This simple script provides user and password to openconnect to make a new VPN connection in background, but it wont work because the children spawned processes are killed by expect. As you may know, expect will send SIGHUP signal before finish, I was trying to workaround it but even when I put the -ignore HUP flag, it is killing the underlying process, I would like to end my script but the underlying openconnect in background survive.

Do you know what is lacking here?

Take into account that openconnect -b will spawn other PID by its own.

答:
After spending too much time on this, I solved it by adding

```<code>expect -timeout -1 -ex "Client killed"
</code>```

and calling script with &

```<code>./vpn.exp &
</code>```

ContentLicense: CC BY-SA 3.0

Title: TCL Expect kills child of child process

Body:
I have an expect script like this

#!/usr/bin/expect -f
set timeout 30
log_user 0

set PASSWORD $::env(PASSWORD)
set USERNAME $::env(USERNAME)
set TOKEN $::env(TOKEN)

puts stderr "Generating OTP"
spawn oathtool --totp $TOKEN
expect -re \\d+
set otp $expect_out(0,string)

puts stderr "Connecting to VPN server"
spawn -ignore HUP env openconnect -b https://vpn
expect "GROUP:"
send "Tech\n"
expect "Username:"
send "$USERNAME\n"
expect "Password:"
send "$PASSWORD\n"
expect "Password:"
send "$otp\n"
expect EOF

This simple script provides user and password to openconnect to make a new VPN connection in background, but it wont work because the children spawned processes are killed by expect. As you may know, expect will send SIGHUP signal before finish, I was trying to workaround it but even when I put the -ignore HUP flag, it is killing the underlying process, I would like to end my script but the underlying openconnect in background survive.

Do you know what is lacking here?

Take into account that openconnect -b will spawn other PID by its own.

Body:
After spending too much time on this, I solved it by adding

expect -timeout -1 -ex "Client killed"

and calling script with &

./vpn.exp &


问:
How to generate a @CreatedDate LocalDateTime as Timestamp?
I'm using spring-jpa to persist a LocalDateTime created_at with @CreatedDate.

```<code>@CreatedDate
private LocalDateTime created_at;
</code>```

Problem: this auto-generates a column with datetime(6) mysql column type.

Question: how can I change this to TIMESTAMP type? I tried @Temporal(TIMESTAMP) but which is not allowed on LocalDateTime.

Is it possible at all?

答:
You can do one thing Generate the current time according to your required form Using Java there is method called DateTimeFormatter.
 let me explain through Code:-

LocalDate localDate = LocalDate.now();

DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");

String Date = dtf.format(localDate);

and then after assign this Date to your field . It will work Fine.

Body:
I'm using spring-jpa to persist a LocalDateTime created_at with @CreatedDate.

@CreatedDate
private LocalDateTime created_at;

Problem: this auto-generates a column with datetime(6) mysql column type.

Question: how can I change this to TIMESTAMP type? I tried @Temporal(TIMESTAMP) but which is not allowed on LocalDateTime.

Is it possible at all?


问:
Kubernetes Ingress difference of path/backend specification
What's the difference between these two specs in my ingress resource. Do they perform the same thing? When do I use which type?

```<code>spec:
  rules:
  - host: {{ .Values.Subdomain }}{{ .Values.Domain }}
    http:
      paths:
        - path: /api
          backend:
            serviceName: {{ .Values.ServiceName }}
            servicePort: 80
</code>```

And:

```<code>spec:
  rules:
  - host: {{ .Values.Subdomain }}{{ .Values.Domain }}
    http:
      paths:
      - backend:
          serviceName: {{ .Values.ServiceName }}
          servicePort: 80
        path: /api
</code>```

答: These two specifications are the same in YAML - the order of items is not relevant.</p>

Body:
What's the difference between these two specs in my ingress resource. Do they perform the same thing? When do I use which type?

spec:
  rules:
  - host: {{ .Values.Subdomain }}{{ .Values.Domain }}
    http:
      paths:
        - path: /api
          backend:
            serviceName: {{ .Values.ServiceName }}
            servicePort: 80

And:

spec:
  rules:
  - host: {{ .Values.Subdomain }}{{ .Values.Domain }}
    http:
      paths:
      - backend:
          serviceName: {{ .Values.ServiceName }}
          servicePort: 80
        path: /api


问:
Django Blog App urls functionality
I am trying to integrate the following blog APP https://github.com/nathanborror/django-basic-apps ,so in my main urls.py i have included the blog urls as (r'^blog/',include('basic.blog.urls')),  Now my question is that now when i point my browser to the blog APP http://127.0.0.1/blog/ i get a message as "Post archive",How to proceed from here i.e, how to post blog and retrieve the same.What is the url to be used..The following is the blog urls

```<code>from django.conf.urls.defaults import *

urlpatterns = patterns('basic.blog.views',
url(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{1,2})/(?P<slug>[-\w]+)/$',
    view='post_detail',
    name='blog_detail'
),
url(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{1,2})/$',
    view='post_archive_day',
    name='blog_archive_day'
),
url(r'^(?P<year>\d{4})/(?P<month>\w{3})/$',
    view='post_archive_month',
    name='blog_archive_month'
),
url(r'^(?P<year>\d{4})/$',
    view='post_archive_year',
    name='blog_archive_year'
),
url(r'^categories/(?P<slug>[-\w]+)/$',
    view='category_detail',
    name='blog_category_detail'
),
url (r'^categories/$',
    view='category_list',
    name='blog_category_list'
),
url(r'^tags/(?P<slug>[-\w]+)/$',
    view='tag_detail',
    name='blog_tag_detail'
),
url (r'^search/$',
    view='search',
    name='blog_search'
),
url(r'^page/(?P<page>\d+)/$',
    view='post_list',
    name='blog_index_paginated'
),
url(r'^$',
    view='post_list',
   name='blog_index'
),
)
</code>```

答:
I've used and customized the basic blog application

The creation can be done through the Admin interface, the models are already registered with the admin interface

You just need to provide a good layout and some cool stylesheets for your front end to get started

Title: Django Blog App urls functionality

Body:
I am trying to integrate the following blog APP https://github.com/nathanborror/django-basic-apps ,so in my main urls.py i have included the blog urls as (r'^blog/',include('basic.blog.urls')),  Now my question is that now when i point my browser to the blog APP http://127.0.0.1/blog/ i get a message as "Post archive",How to proceed from here i.e, how to post blog and retrieve the same.What is the url to be used..The following is the blog urls

from django.conf.urls.defaults import *

urlpatterns = patterns('basic.blog.views',
url(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{1,2})/(?P<slug>[-\w]+)/$',
    view='post_detail',
    name='blog_detail'
),
url(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{1,2})/$',
    view='post_archive_day',
    name='blog_archive_day'
),
url(r'^(?P<year>\d{4})/(?P<month>\w{3})/$',
    view='post_archive_month',
    name='blog_archive_month'
),
url(r'^(?P<year>\d{4})/$',
    view='post_archive_year',
    name='blog_archive_year'
),
url(r'^categories/(?P<slug>[-\w]+)/$',
    view='category_detail',
    name='blog_category_detail'
),
url (r'^categories/$',
    view='category_list',
    name='blog_category_list'
),
url(r'^tags/(?P<slug>[-\w]+)/$',
    view='tag_detail',
    name='blog_tag_detail'
),
url (r'^search/$',
    view='search',
    name='blog_search'
),
url(r'^page/(?P<page>\d+)/$',
    view='post_list',
    name='blog_index_paginated'
),
url(r'^$',
    view='post_list',
   name='blog_index'
),
)


问:
How can I add an empty row in a for loop based on a previous for loop?
I'm trying to make a comparison report that displays sales for two time periods, in this scenario i've selected 1-31 October and 1-30th November. I am loading the data from the same Json file but as two seperate queries, the first uses the October period and the second uses the November period.

This is the code I have currently:

```<code>// October 1-31
<div class="col-6" *ngFor="let periods of reportData">
    <div *ngFor="let reportVal of periods.groupedTransactions">
        <div class="row" *ngIf="reportData.length > 0">
            <div class="col-12">
                <h6>Customer: {{reportVal.name}}</h6>
            </div>
            <div class="col">
                <h6>Total Sales: {{reportVal.totalSales | number}}</h6>
            </div>
        </div>
    </div>
</div>
// November 1-30
<div class="col-6" *ngFor="let comPeriods of comReportData">
    <div *ngFor="let reportVal of comPeriods.groupedTransactions">
        <div class="row" *ngIf="comReportData.length > 0">
            <div class="col-12">
                <h6>Customer: {{reportVal.name}}</h6>
            </div>
            <div class="col">
                <h6>Total Sales: {{reportVal.totalSales | number}}</h6>
            </div>
        </div>
    </div>
</div>
</code>```

And this is the result:

Is there a way to add a function that will add an empty row in the November if there is no sales from that customer? I want to have all the Customers vertically aligned.

Because the periods for loop is based on the selected dates, putting the columns in the same loop will only get data from one date.

If anyone can help me out or tell me where to look to solve this it would be greatly appreciated!

答:
Regardless of your approach, your primary loop should be over the set of customers that are in all periods.

I would create a de-normalised view model that combines customers and reports. Your final view model structure would probably look something like this in spirit:

```<code>periods: [
  {
    name: 'October 2019'
    customers: [
      {
        name: 'John',
        totalSales: 100
      },
      ...
    ]
  }
]
</code>```

The complexity is in how you build it. Something like

```<code>periods.forEach(period => {
  const periodViewModel = {};
  this.viewModel.periods.push(periodViewModel);

  customers.forEach(customer => {
    const customerViewModel = {
      name: customer.name,
      totalSales: this.getSales(customer, period)
    };

    periodViewModel.customers.push(customerViewModel);
  });
});
</code>```

Where this.getSales(customer, period) is some way of getting the sales data for a given customer and period - probably a local variable. You may want to optimise your sales data for retrieval by customer / period, depending on how many periods / customers you have.

And then it becomes pretty trivial to bind this view model to your HTML. Let your typescript take care of the complicated model, and keep your UI simple.

Body:
I'm trying to make a comparison report that displays sales for two time periods, in this scenario i've selected 1-31 October and 1-30th November. I am loading the data from the same Json file but as two seperate queries, the first uses the October period and the second uses the November period.

This is the code I have currently:

// October 1-31

 0">

Customer: {{reportVal.name}}

Total Sales: {{reportVal.totalSales | number}}

// November 1-30

 0">

Customer: {{reportVal.name}}

Total Sales: {{reportVal.totalSales | number}}

And this is the result:

Is there a way to add a function that will add an empty row in the November if there is no sales from that customer? I want to have all the Customers vertically aligned.

Because the periods for loop is based on the selected dates, putting the columns in the same loop will only get data from one date.

If anyone can help me out or tell me where to look to solve this it would be greatly appreciated!

Body:
Regardless of your approach, your primary loop should be over the set of customers that are in all periods.

I would create a de-normalised view model that combines customers and reports. Your final view model structure would probably look something like this in spirit:

periods: [
  {
    name: 'October 2019'
    customers: [
      {
        name: 'John',
        totalSales: 100
      },
      ...
    ]
  }
]

The complexity is in how you build it. Something like

periods.forEach(period => {
  const periodViewModel = {};
  this.viewModel.periods.push(periodViewModel);

  customers.forEach(customer => {
    const customerViewModel = {
      name: customer.name,
      totalSales: this.getSales(customer, period)
    };

    periodViewModel.customers.push(customerViewModel);
  });
});

Where this.getSales(customer, period) is some way of getting the sales data for a given customer and period - probably a local variable. You may want to optimise your sales data for retrieval by customer / period, depending on how many periods / customers you have.

And then it becomes pretty trivial to bind this view model to your HTML. Let your typescript take care of the complicated model, and keep your UI simple.


问:
Use column if it exists, another if doesn't in SQL Server
I have a number of SQL Server databases (different versions from 2012 to 2019). The schema in each one is very similar but not exactly the same.  For example, there's table ORDERS, which has about 50 columns - and one column is called differently in two different databases:

in DB1: select p_user from orders

in DB2: select userpk from orders

Note that I showed two databases above, but there are actually more than 20 - some are DB1 type, the others are DB2 type

I can't do much about these differences - they are historic - and changing the schema to match is not an option.

I want to be able to run the same SQL statement against all of these databases at once.  I'd like to write the query in such a way that it would use one column if it exists and another if it doesn't.  For example:

```<code>select
    case
        when COL_LENGTH('orders', 'p_user') IS NOT NULL
    then
        orders.p_user
    else
        orders.userpk
    end
from orders
</code>```

This unfortunately doesn't work, as SQL server seems to try to evaluate both results regardless of whether the condition is true or false.  The same thing happens if I use IIF function.

If I simply run

```<code>select
    case
        when COL_LENGTH('orders', 'p_user') IS NOT NULL
    then
        'orders.p_user'
    else
        'orders.userpk'
    end
</code>```

then I do get the correct string, which means my condition is correct.

How can I formulate the SQL statement to use one or the other column based on whether the first one exists?

答:
If you can't change anything then your best (and maybe only) option is to use dynamic SQL. A query will only compile if all parts can be resolved at compile time (before anything runs) - which is why e.g. this will not compile:

```<code>IF COL_LENGTH('orders', 'p_user') IS NOT NULL THEN
    select p_user from orders
ELSE
    select userpk as p_user from orders
END
</code>```

But this will work:

```<code>DECLARE @SQL NVARCHAR(MAX)

IF COL_LENGTH('orders', 'p_user') IS NOT NULL THEN
    SET @SQL = 'select p_user from orders'
ELSE
    SET @SQL = 'select userpk as p_user from orders'
END

EXEC (@SQL)
</code>```

Body:
I have a number of SQL Server databases (different versions from 2012 to 2019). The schema in each one is very similar but not exactly the same.  For example, there's table ORDERS, which has about 50 columns - and one column is called differently in two different databases:

in DB1: select p_user from orders

in DB2: select userpk from orders

Note that I showed two databases above, but there are actually more than 20 - some are DB1 type, the others are DB2 type

I can't do much about these differences - they are historic - and changing the schema to match is not an option.

I want to be able to run the same SQL statement against all of these databases at once.  I'd like to write the query in such a way that it would use one column if it exists and another if it doesn't.  For example:

select
    case
        when COL_LENGTH('orders', 'p_user') IS NOT NULL
    then
        orders.p_user
    else
        orders.userpk
    end
from orders

This unfortunately doesn't work, as SQL server seems to try to evaluate both results regardless of whether the condition is true or false.  The same thing happens if I use IIF function.

If I simply run

select
    case
        when COL_LENGTH('orders', 'p_user') IS NOT NULL
    then
        'orders.p_user'
    else
        'orders.userpk'
    end

then I do get the correct string, which means my condition is correct.

How can I formulate the SQL statement to use one or the other column based on whether the first one exists?

Body:
If you can't change anything then your best (and maybe only) option is to use dynamic SQL. A query will only compile if all parts can be resolved at compile time (before anything runs) - which is why e.g. this will not compile:

IF COL_LENGTH('orders', 'p_user') IS NOT NULL THEN
    select p_user from orders
ELSE
    select userpk as p_user from orders
END

But this will work:

DECLARE @SQL NVARCHAR(MAX)

IF COL_LENGTH('orders', 'p_user') IS NOT NULL THEN
    SET @SQL = 'select p_user from orders'
ELSE
    SET @SQL = 'select userpk as p_user from orders'
END

EXEC (@SQL)


问:
parent form closing invoke child form which has background worker in it
I try to achieve this:
i have the main form, when user click the red cross on the top right to exit the application, it popup a progress bar form indicating the application is updating/saving information. After the background worker in the progress bar form finishes, it closes the progress bar form and close the main form as well.
the problem i have is, it closes the main from first without even running the background worker. how to fix this? i tried to use e.cancel= true it just gave my dead loop.

here is my main form:

```<code> private static void mainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
 UpdatingForm pbar = new UpdatingForm ();

            pbar.Show();
}
</code>```

in my updatingform:

```<code>public UpdatingForm()
        {
            InitializeComponent();

            bgWorker.RunWorkerAsync();
        }

    private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
            {
    ....
    }

private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

            this.Close();
            // Application.Exit();
        }
</code>```

答:
Maybe this code works.test it

```<code> private static void mainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
 UpdatingForm pbar = new UpdatingForm ();

            pbar.Show();
while (pbar.Created)
{
Application.DoEvents()
}
}
</code>```

or

```<code> private static void mainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
 UpdatingForm pbar = new UpdatingForm ();

            pbar.Show();
while (! pbar.IsDisposed)
{
Application.DoEvents()
}
}
</code>```

Body:
I try to achieve this:
i have the main form, when user click the red cross on the top right to exit the application, it popup a progress bar form indicating the application is updating/saving information. After the background worker in the progress bar form finishes, it closes the progress bar form and close the main form as well.
the problem i have is, it closes the main from first without even running the background worker. how to fix this? i tried to use e.cancel= true it just gave my dead loop.

here is my main form:

 private static void mainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
 UpdatingForm pbar = new UpdatingForm ();

            pbar.Show();
}

in my updatingform:

public UpdatingForm()
        {
            InitializeComponent();

            bgWorker.RunWorkerAsync();
        }

    private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
            {
    ....
    }

private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

            this.Close();
            // Application.Exit();
        }

Body:
Maybe this code works.test it

 private static void mainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
 UpdatingForm pbar = new UpdatingForm ();

            pbar.Show();
while (pbar.Created)
{
Application.DoEvents()
}
}

or

 private static void mainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
 UpdatingForm pbar = new UpdatingForm ();

            pbar.Show();
while (! pbar.IsDisposed)
{
Application.DoEvents()
}
}


问:
Converting React to React Native
I have a React App that I need to convert to React Native. I do not have a lot of experience on web development, so i might be missing something essential here. The problem I have is that when I open the app in the emulator I only see a white page that says "Home" on top. This what i have translated of the code so far.

index.js

```<code>import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);
</code>```

App.js

```<code>import React from 'react';
import Routes from './src/core/Routes';
import configureStore from './src/services/store';
import {Provider} from 'react-redux';
import {View} from 'react-native';
import {createMuiTheme, MuiThemeProvider} from '@material-ui/core';
import {
    font_family_default,
    font_family_secondary,
    font_size_md,
    font_size_sm,
    font_weight_bold,
    font_weight_normal,
    font_weight_semi_bold,
} from './src/assets/style/variables';
import {rem} from './src/assets/style/functions';
import colors from './src/assets/style/colors';

const theme = createMuiTheme({
    typography: {
        fontFamily: font_family_default,
        fontSize: 16,
        fontWeightLight: font_weight_normal,
        fontWeightRegular: font_weight_semi_bold,
        fontWeightMedium: font_weight_bold,
    },
    overrides: {
        MuiMenuItem: {
            root: {
                fontSize: font_size_sm,
                fontFamily: font_family_secondary,
                fontWeight: font_weight_semi_bold,
                minHeight: rem(40),
            },
        },
        MuiMenu: {
            paper: {
                boxShadow: '0px 12px 56px -8px rgba(0,0,0,0.2)',
                borderRadius: `${rem(3)}`,
            },
        },
        MuiExpansionPanelSummary: {
            root: {
                padding: `0px ${rem(16)}`,
            },
            content: {
                margin: `${rem(8)} 0px `,
            },
        },
        MuiInputBase: {
            root: {
                fontSize: font_size_md,
            },
        },
        MuiPickersToolbar: {
            toolbar: {
                backgroundColor: colors.grey.primary,
            },
        },
        MuiPickersDay: {
            daySelected: {
                backgroundColor: colors.yellow.dark2,
                '&:hover': {
                    backgroundColor: colors.yellow.dark2,
                },
            },
        },

        MuiPickersClockNumber: {
            clockNumberSelected: {backgroundColor: colors.yellow.dark2},
        },

        MuiPickersClock: {
            pin: {backgroundColor: colors.yellow.dark2},
        },
        MuiPickersClockPointer: {
            pointer: {backgroundColor: colors.yellow.dark2},
            thumb: {border: `14px solid ${colors.yellow.dark2}`},
        },
    },
});

const store = configureStore();

const App: () => React$Node = () => {
    return (
        <Provider store={store}>
            <MuiThemeProvider theme={theme}>
                <View style={{flex: 1}}>
                    <Routes/>
                </View>
            </MuiThemeProvider>
        </Provider>
    );
};

export default App;
</code>```

Routes.js

```<code>import React from 'react';
import {Router, Scene} from 'react-native-router-flux';
import Login from '../pages/login';

const Routes = () => (
    <Router>
        <Scene key="root">
            <Scene key="home" component={Login} title="Home" initial={true}/>
        </Scene>
    </Router>
);

export default Routes;
</code>```

/src/page/login/index.js

```<code>import React, {useState} from 'react';
import styled from 'styled-components/native';
import Input from '../../shared/components/Input';
import Button from '../../shared/components/Button';
import {connect} from 'react-redux';
import {APP_ROUTES} from '../../core/global-constants';
import {Link, Redirect} from 'react-router-native';

import Logo from '../../assets/img/log.svg';
import colors from '../../assets/style/colors';
import {rem} from '../../assets/style/functions';
import {device, font_size_md, font_size_xxl, font_weight_normal} from '../../assets/style/variables';
import {login} from '../../services/actions/authenticationActions';
import useForm from '../../shared/hooks/useForm';
import validate from './loginFormValidations';

const theme = {
    backgroundColor: colors.white.light1,
};

function Login(props) {
    const {values, handleChange, handleSubmit, errors} = useForm(login, validate);
    const [redirect, setRedirect] = useState(false);
    const [errorLogin, setErrorLogin] = useState(false);

    function login() {
        if (Object.keys(errors).length === 0) {
            props.login(values).then(
                res => {
                    setRedirect(true);
                },
                err => {
                    errors.login = props.errorMessage
                        ? `${props.errorMessage},  please try again`
                        : `No active account found with the given credentials,  please try again`;
                    setErrorLogin(true);
                },
            );
        }
    }

    if (redirect) {
        return <Redirect to={APP_ROUTES.timeTracker}/>;
    }
    return (
        <Style.Section>
            <Style.Img src={Logo} alt="toki timer logo"/>
            <Style.Hero>
                <Style.Title>Welcome back!</Style.Title>
                <Style.Subtitle>Log in to continue</Style.Subtitle>
            </Style.Hero>
            <Style.Form onSubmit={handleSubmit}>
                <Style.FormGroup>
                    <Input
                        id="username"
                        name="username"
                        placeholder="Username"
                        backgroundColor={theme}
                        onChange={handleChange}
                        value={values.username || ''}
                        hasError={errors.username}
                    />
                    {errors.username && <Style.ErrorMessage>{errors.username}</Style.ErrorMessage>}
                </Style.FormGroup>

                <Style.FormGroup>
                    <Input
                        id="password"
                        name="password"
                        type="password"
                        placeholder="Password"
                        backgroundColor={theme}
                        onChange={handleChange}
                        value={values.password || ''}
                        hasError={errors.password}
                    />
                    {errors.password && <Style.ErrorMessage>{errors.password}</Style.ErrorMessage>}
                    {errorLogin && <Style.ErrorMessage>{errors.login}</Style.ErrorMessage>}
                </Style.FormGroup>
                <Button name="Login" type="submit"/>
            </Style.Form>
            <Style.Hero>
                <Style.BottomLinks>
                    <Style.Link to={APP_ROUTES.forgotPassword}>Forgot your password?</Style.Link>
                </Style.BottomLinks>
            </Style.Hero>
        </Style.Section>
    );
}

const mapStateToProps = state => {
    return {
        loading: state.authorization.loading,
        isAuthenticated: state.authorization.isAuthenticated,
        loginSuccess: state.authorization.loginSuccess,
        loginError: state.authorization.loginError,
        errorMessage: state.authorization.errorMessage,
        isAdmin: state.authorization.userInSession.isAdmin,
    };
};
const mapDispatchToProps = {login};

export default connect(
    mapStateToProps,
    mapDispatchToProps,
)(Login);

const Style = {};

Style.Section = styled.SectionList`
  background-color: ${colors.grey.primary};
  min-height: 100%;
  margin: 0px auto;
  display: flex;
  flex-direction: column;
`;
Style.Form = styled.View`
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 0 35%;
  margin-bottom: ${rem(40)};

  @media ${device.mobileS} {
    padding: 0 5%;
  }

  @media ${device.mobileL} {
    padding: 0 15%;
  }

  @media ${device.laptop} {
    padding: 0 35%;
  }
`;

Style.Hero = styled.View`
  display: flex;
  flex-direction: column;
  margin-bottom: ${rem(70)};
  align-items: center;
`;
Style.Title = styled.Text`
  color: ${colors.white.primary};
  font-size: ${font_size_xxl};
  font-weight: ${font_weight_normal};
  margin: 0;
`;
Style.Subtitle = styled(Style.Title)`
  font-size: ${font_size_md};
`;
Style.Img = styled.Image`
  margin-bottom: ${rem(60)};
  margin-top: ${rem(60)};
`;
Style.BottomLinks = styled.Text`
  color: ${colors.white.primary};
  margin-top: ${rem(10)};
`;

Style.Link = styled(Link)`
  color: ${colors.yellow.primary};

  &:hover {
    text-decoration: underline;
  }
`;
Style.FormGroup = styled.View`
  margin-bottom: ${rem(45)};
`;
Style.ErrorMessage = styled.Text`
  font-size: ${font_size_md};
  color: ${colors.red.primary};
`;
</code>```

What I don't seem to understand after reading documentation is how routing works, for example, using react, my Routes.js looks like this:

```<code>import React from 'react'
import { Switch, Route } from 'react-router-dom'

import { APP_ROUTES } from './global-constants'
import Login from '../pages/login'
import Dashboard from '../pages/dashboard'
import TimeTracker from '../pages/time-tracker'
import SignUp from '../pages/signUp'
import PrivateRoute from '../shared/components/PrivateRoute'
import UserList from '../pages/user-list'
import DepartmentsList from '../pages/departments-list'
import Reports from '../pages/reports'
import UserProfile from '../pages/user-profile'
import ForgotPassword from '../pages/forgot-password'
import NotFound from '../shared/components/NotFound'

const Routes = () => (
  <main>
    <Switch>
      <Route exact path={[APP_ROUTES.home, APP_ROUTES.login]} component={Login} />
      <Route exact path={APP_ROUTES.signUp} component={SignUp} />
      <Route exact path={APP_ROUTES.forgotPassword} component={ForgotPassword} />
      <PrivateRoute
        exact
        path={[APP_ROUTES.dashboard, APP_ROUTES.dashboardDeparment]}
        component={Dashboard}
      />
      <PrivateRoute exact path={APP_ROUTES.timeTracker} component={TimeTracker} />
      <PrivateRoute exact path={APP_ROUTES.usersList} component={UserList} />
      <PrivateRoute exact path={APP_ROUTES.departments} component={DepartmentsList} />
      <PrivateRoute exact path={APP_ROUTES.reports} component={Reports} />
      <PrivateRoute exact path={APP_ROUTES.userDetails} component={UserProfile} />
      <PrivateRoute component={NotFound} />
    </Switch>
  </main>
)

export default Routes
</code>```

I made the changes to the routes file since I've read that react-router-dom does not work in native. My main purpose is to re-use as much code as possible, but if I can't, what do I need to change for the page to actually show in the emulator?

答:
If you want to move your App from React Web application to React Native App, then you can reuse your functionality, Components, lifecycle methods, setState, props, but you have to write your return (render) method code in respective to React Native, because in React Web application the HTML code also works fine but in mobile app, you need to add <View> to design your UI similar to
.

For Mobile App, we also need to handle gestures as onPress instead of onClick. And instead of Routing, you need to add Navigator Stack Navigator, Drawer Navigator, Tab Navigator according to your requirements.

Please refer to React Native Documentation and for navigation
 React Navigation.

Title: Converting React to React Native

Body:
I have a React App that I need to convert to React Native. I do not have a lot of experience on web development, so i might be missing something essential here. The problem I have is that when I open the app in the emulator I only see a white page that says "Home" on top. This what i have translated of the code so far.

index.js

import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);

App.js

import React from 'react';
import Routes from './src/core/Routes';
import configureStore from './src/services/store';
import {Provider} from 'react-redux';
import {View} from 'react-native';
import {createMuiTheme, MuiThemeProvider} from '@material-ui/core';
import {
    font_family_default,
    font_family_secondary,
    font_size_md,
    font_size_sm,
    font_weight_bold,
    font_weight_normal,
    font_weight_semi_bold,
} from './src/assets/style/variables';
import {rem} from './src/assets/style/functions';
import colors from './src/assets/style/colors';

const theme = createMuiTheme({
    typography: {
        fontFamily: font_family_default,
        fontSize: 16,
        fontWeightLight: font_weight_normal,
        fontWeightRegular: font_weight_semi_bold,
        fontWeightMedium: font_weight_bold,
    },
    overrides: {
        MuiMenuItem: {
            root: {
                fontSize: font_size_sm,
                fontFamily: font_family_secondary,
                fontWeight: font_weight_semi_bold,
                minHeight: rem(40),
            },
        },
        MuiMenu: {
            paper: {
                boxShadow: '0px 12px 56px -8px rgba(0,0,0,0.2)',
                borderRadius: `${rem(3)}`,
            },
        },
        MuiExpansionPanelSummary: {
            root: {
                padding: `0px ${rem(16)}`,
            },
            content: {
                margin: `${rem(8)} 0px `,
            },
        },
        MuiInputBase: {
            root: {
                fontSize: font_size_md,
            },
        },
        MuiPickersToolbar: {
            toolbar: {
                backgroundColor: colors.grey.primary,
            },
        },
        MuiPickersDay: {
            daySelected: {
                backgroundColor: colors.yellow.dark2,
                '&:hover': {
                    backgroundColor: colors.yellow.dark2,
                },
            },
        },

        MuiPickersClockNumber: {
            clockNumberSelected: {backgroundColor: colors.yellow.dark2},
        },

        MuiPickersClock: {
            pin: {backgroundColor: colors.yellow.dark2},
        },
        MuiPickersClockPointer: {
            pointer: {backgroundColor: colors.yellow.dark2},
            thumb: {border: `14px solid ${colors.yellow.dark2}`},
        },
    },
});

const store = configureStore();

const App: () => React$Node = () => {
    return (
        <Provider store={store}>
            <MuiThemeProvider theme={theme}>
                <View style={{flex: 1}}>
                    <Routes/>
                </View>
            </MuiThemeProvider>
        </Provider>
    );
};

export default App;

Routes.js

import React from 'react';
import {Router, Scene} from 'react-native-router-flux';
import Login from '../pages/login';

const Routes = () => (
    <Router>
        <Scene key="root">
            <Scene key="home" component={Login} title="Home" initial={true}/>
        </Scene>
    </Router>
);

export default Routes;

/src/page/login/index.js

import React, {useState} from 'react';
import styled from 'styled-components/native';
import Input from '../../shared/components/Input';
import Button from '../../shared/components/Button';
import {connect} from 'react-redux';
import {APP_ROUTES} from '../../core/global-constants';
import {Link, Redirect} from 'react-router-native';

import Logo from '../../assets/img/log.svg';
import colors from '../../assets/style/colors';
import {rem} from '../../assets/style/functions';
import {device, font_size_md, font_size_xxl, font_weight_normal} from '../../assets/style/variables';
import {login} from '../../services/actions/authenticationActions';
import useForm from '../../shared/hooks/useForm';
import validate from './loginFormValidations';

const theme = {
    backgroundColor: colors.white.light1,
};

function Login(props) {
    const {values, handleChange, handleSubmit, errors} = useForm(login, validate);
    const [redirect, setRedirect] = useState(false);
    const [errorLogin, setErrorLogin] = useState(false);

    function login() {
        if (Object.keys(errors).length === 0) {
            props.login(values).then(
                res => {
                    setRedirect(true);
                },
                err => {
                    errors.login = props.errorMessage
                        ? `${props.errorMessage},  please try again`
                        : `No active account found with the given credentials,  please try again`;
                    setErrorLogin(true);
                },
            );
        }
    }

    if (redirect) {
        return <Redirect to={APP_ROUTES.timeTracker}/>;
    }
    return (

            </Style.Hero>
            }
                </Style.FormGroup>

                }
                    {errorLogin && }
                </Style.FormGroup>
                <Button name="Login" type="submit"/>
            </Style.Form>

                </Style.BottomLinks>
            </Style.Hero>
        </Style.Section>
    );
}

const mapStateToProps = state => {
    return {
        loading: state.authorization.loading,
        isAuthenticated: state.authorization.isAuthenticated,
        loginSuccess: state.authorization.loginSuccess,
        loginError: state.authorization.loginError,
        errorMessage: state.authorization.errorMessage,
        isAdmin: state.authorization.userInSession.isAdmin,
    };
};
const mapDispatchToProps = {login};

export default connect(
    mapStateToProps,
    mapDispatchToProps,
)(Login);

const Style = {};

Style.Section = styled.SectionList`
  background-color: ${colors.grey.primary};
  min-height: 100%;
  margin: 0px auto;
  display: flex;
  flex-direction: column;
`;
Style.Form = styled.View`
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 0 35%;
  margin-bottom: ${rem(40)};

  @media ${device.mobileS} {
    padding: 0 5%;
  }

  @media ${device.mobileL} {
    padding: 0 15%;
  }

  @media ${device.laptop} {
    padding: 0 35%;
  }
`;

Style.Hero = styled.View`
  display: flex;
  flex-direction: column;
  margin-bottom: ${rem(70)};
  align-items: center;
`;
Style.Title = styled.Text`
  color: ${colors.white.primary};
  font-size: ${font_size_xxl};
  font-weight: ${font_weight_normal};
  margin: 0;
`;
Style.Subtitle = styled(Style.Title)`
  font-size: ${font_size_md};
`;
Style.Img = styled.Image`
  margin-bottom: ${rem(60)};
  margin-top: ${rem(60)};
`;
Style.BottomLinks = styled.Text`
  color: ${colors.white.primary};
  margin-top: ${rem(10)};
`;

Style.Link = styled(Link)`
  color: ${colors.yellow.primary};

  &:hover {
    text-decoration: underline;
  }
`;
Style.FormGroup = styled.View`
  margin-bottom: ${rem(45)};
`;
Style.ErrorMessage = styled.Text`
  font-size: ${font_size_md};
  color: ${colors.red.primary};
`;

What I don't seem to understand after reading documentation is how routing works, for example, using react, my Routes.js looks like this:

import React from 'react'
import { Switch, Route } from 'react-router-dom'

import { APP_ROUTES } from './global-constants'
import Login from '../pages/login'
import Dashboard from '../pages/dashboard'
import TimeTracker from '../pages/time-tracker'
import SignUp from '../pages/signUp'
import PrivateRoute from '../shared/components/PrivateRoute'
import UserList from '../pages/user-list'
import DepartmentsList from '../pages/departments-list'
import Reports from '../pages/reports'
import UserProfile from '../pages/user-profile'
import ForgotPassword from '../pages/forgot-password'
import NotFound from '../shared/components/NotFound'

const Routes = () => (

    <Switch>
      <Route exact path={[APP_ROUTES.home, APP_ROUTES.login]} component={Login} />
      <Route exact path={APP_ROUTES.signUp} component={SignUp} />
      <Route exact path={APP_ROUTES.forgotPassword} component={ForgotPassword} />
      <PrivateRoute
        exact
        path={[APP_ROUTES.dashboard, APP_ROUTES.dashboardDeparment]}
        component={Dashboard}
      />
      <PrivateRoute exact path={APP_ROUTES.timeTracker} component={TimeTracker} />
      <PrivateRoute exact path={APP_ROUTES.usersList} component={UserList} />
      <PrivateRoute exact path={APP_ROUTES.departments} component={DepartmentsList} />
      <PrivateRoute exact path={APP_ROUTES.reports} component={Reports} />
      <PrivateRoute exact path={APP_ROUTES.userDetails} component={UserProfile} />
      <PrivateRoute component={NotFound} />
    </Switch>

)

export default Routes

I made the changes to the routes file since I've read that react-router-dom does not work in native. My main purpose is to re-use as much code as possible, but if I can't, what do I need to change for the page to actually show in the emulator?

Body:
If you want to move your App from React Web application to React Native App, then you can reuse your functionality, Components, lifecycle methods, setState, props, but you have to write your return (render) method code in respective to React Native, because in React Web application the HTML code also works fine but in mobile app, you need to add <View> to design your UI similar to <div>.

For Mobile App, we also need to handle gestures as onPress instead of onClick. And instead of Routing, you need to add Navigator Stack Navigator, Drawer Navigator, Tab Navigator according to your requirements.

Please refer to React Native Documentation and for navigation
 React Navigation.


问:
Why can't I use ~0 to initialize signed char?
I wrote like this:

```<code>#include <stdio.h>
#include <limits.h>

main()
{
    signed char i = ~0;
    printf("%zu\n", i);
    return 0;
}
</code>```

But the result is 4294967295 instead of -1. Why does this happen?

答:
When you use a signed char value in an expression, it is automatically converted to int. Then, when you print a signed int using a format specifier %zu, which is for formatting an unsigned size_t, you get erroneous results because of the mismatch.

To print a signed char correctly, using %hhd.

Additionally, you should understand that while a signed char value of −1 might be represented with the eight bits 11111111 (in eight-bit two’s complement), when it is converted to int, the result is the 32 bits 11111111111111111111111111111111 (which represents −1 using 32-bit two’s complement). When those bits are interpreted as a 32-bit unsigned integer, the result is 4294967295. That explains why “4294967295” may be printed rather than the “255” that would result from interpreting the eight-bit 11111111 as an unsigned integer.

Body:
I wrote like this:

#include <stdio.h>
#include <limits.h>

main()
{
    signed char i = ~0;
    printf("%zu\n", i);
    return 0;
}

But the result is 4294967295 instead of -1. Why does this happen?


问:
Text element in animated SVG moves in stuttering motion
Basic geometrical SVG elements can be positioned at fractions of a pixel, but apparently not so text elements as the example script demonstrates. While the motion of the rect element is smooth, the text element's motion is more like stuttering, probably because the position is rounded to the next full pixel so the text does not appear blurry due to anti-aliasing issues or so. But in this context of moving text this rounding does not make sense but causes the stuttering motion. This is just a guess, maybe I am wrong.

Does anyone have a solution how to make the motion of the text element as smooth as the rect element's? Thank you.

  <svg width="800" height="800">
    <rect x='0' y='0' width='250' height='50' fill='none' stroke='black' stroke-width='4' />
    <text x='0' y='0' fill='black' font-size='40' font-weight='bold' text-anchor='middle'>Hello, world!</text>
  </svg>

```

答:
Since this behaviour only occurs when the text's baseline is parallel to the pixel grid, or in other words: exactly horizontal, the issue can be worked around by rotating the text by a tiny fraction hardly visible to the eye but big enough to escape the pixel grid, like so (not too elegant, more a hack, but works for me):

  <svg width="800" height="800">
    <rect x='0' y='0' width='250' height='50' fill='none' stroke='black' stroke-width='4' />
    <text x='0' y='0' fill='black' font-size='40' font-weight='bold' text-anchor='middle'>Hello, world!</text>
  </svg>

```

Body:
Since this behaviour only occurs when the text's baseline is parallel to the pixel grid, or in other words: exactly horizontal, the issue can be worked around by rotating the text by a tiny fraction hardly visible to the eye but big enough to escape the pixel grid, like so (not too elegant, more a hack, but works for me):

<html>
  <svg width="800" height="800">
    <rect x='0' y='0' width='250' height='50' fill='none' stroke='black' stroke-width='4' />
    <text x='0' y='0' fill='black' font-size='40' font-weight='bold' text-anchor='middle'>Hello, world!</text>
  </svg>
  <script>
    function moveElements() {
      document.getElementsByTagName("rect")[0].setAttribute("x", p);
      document.getElementsByTagName("rect")[0].setAttribute("y", p);
      document.getElementsByTagName("text")[0].setAttribute("x", p + 125);
      document.getElementsByTagName("text")[0].setAttribute("y", p + 38);
      document.getElementsByTagName("text")[0].setAttribute("transform", "rotate(.05 " + (p + 125) + " " + (p + 25) + ")");
      p += .1;
    }
    p = 0;
    setInterval(moveElements, 20);
  </script>
</html>


问:
strange output when returning the argument list
Code

```<code>def removeEven(List):
    for x in List:
        if x % 2 == 0:
            List.remove(x)
    return List

print(removeEven([18, 106, -158, -124, 199, -28, -68, -91, 46, -190, 63, -30, 142, -36, -162, -121, 14, -192, -143, -57, -59, -129, -146, -76, -186, -84, 70, 19, -13, -12, -5, 179, -191, -43, 160, -156, 105, 104, 93, -188, -184, -197, -136, -35, 16]))
</code>```

Output

```<code>[106, -124, 199, -68, -91, -190, 63, 142, -162, -121, -192, -143, -57, -59, -129, -76, -84, 19, -13, -5, 179, -191, -43, -156, 105, 93, -184, -197, -35]
</code>```

Code

```<code>def removeEven(List):
    result = []
    for x in List:
        if x % 2 != 0:
            result.append(x)
    return result
</code>```

Output

```<code>[199, -91, 63, -121, -143, -57, -59, -129, 19, -13, -5, 179, -191, -43, 105, 93, -197, -35]
</code>```

I came across this strange behavior. I am writing a simple function to remove even numbers from a list but when I modify the list that is passed as an argument and return it I get a weird output. Does anyone know what the reason is?

Please note i am not looking for answer to this problem it is easy to google but just explanation about why the output is different when i don't create a new list and return it.

答:
One Liner in Python using list comprehension:

```<code>[x for x in li if x % 2 != 0]
</code>```

strange output when returning the argument list

You are not permitted to remove elements from the list while iterating over it using a for loop. The best way to do this involves making a new list - either iterate over a copy, or construct a list with only the elements you want and assign it back to the same variable.

As we know, every item in a list lives at its own unique index; which are in order, starting from 0. If we remove an item, any item with an index greater than the one we've removed has now been shifted down.

And here's why that matters:

```<code>foo = ['a', 'b', 'c', 'd']
for index in range(len(foo)):
    del foo[index]
</code>```

In this loop, we're removing all the elements, so we should end up with foo == [], right? This is not the case. In our first trip through the loop, we remove the item at index 0, and the item at index 1 becomes the item at index 0. Our next time through the loop, we remove the item at index 1 which was previously the item at index 2.

See this to learn more on How to remove elements while iterating over a list. See this to learn more on How to remove elements while reverse iterating a list.

Body:
Code

def removeEven(List):
    for x in List:
        if x % 2 == 0:
            List.remove(x)
    return List

print(removeEven([18, 106, -158, -124, 199, -28, -68, -91, 46, -190, 63, -30, 142, -36, -162, -121, 14, -192, -143, -57, -59, -129, -146, -76, -186, -84, 70, 19, -13, -12, -5, 179, -191, -43, 160, -156, 105, 104, 93, -188, -184, -197, -136, -35, 16]))

Output

[106, -124, 199, -68, -91, -190, 63, 142, -162, -121, -192, -143, -57, -59, -129, -76, -84, 19, -13, -5, 179, -191, -43, -156, 105, 93, -184, -197, -35]

Code

def removeEven(List):
    result = []
    for x in List:
        if x % 2 != 0:
            result.append(x)
    return result

Output

[199, -91, 63, -121, -143, -57, -59, -129, 19, -13, -5, 179, -191, -43, 105, 93, -197, -35]

I came across this strange behavior. I am writing a simple function to remove even numbers from a list but when I modify the list that is passed as an argument and return it I get a weird output. Does anyone know what the reason is?

Please note i am not looking for answer to this problem it is easy to google but just explanation about why the output is different when i don't create a new list and return it.

Body:
One Liner in Python using list comprehension:

[x for x in li if x % 2 != 0]

strange output when returning the argument list

You are not permitted to remove elements from the list while iterating over it using a for loop. The best way to do this involves making a new list - either iterate over a copy, or construct a list with only the elements you want and assign it back to the same variable.

As we know, every item in a list lives at its own unique index; which are in order, starting from 0. If we remove an item, any item with an index greater than the one we've removed has now been shifted down.

And here's why that matters:

foo = ['a', 'b', 'c', 'd']
for index in range(len(foo)):
    del foo[index]

In this loop, we're removing all the elements, so we should end up with foo == [], right? This is not the case. In our first trip through the loop, we remove the item at index 0, and the item at index 1 becomes the item at index 0. Our next time through the loop, we remove the item at index 1 which was previously the item at index 2.

See this to learn more on How to remove elements while iterating over a list. See this to learn more on How to remove elements while reverse iterating a list.


问:
I want to access UserQus.append(msg) and BotAns.append(res) out of send() method in python
1.This is my code here you can see the send() method. I want to use UserQus and BotAns out of send method in on_closing() method for sore in firebase database, I can't do it so, please give me solution for it.</p>

```<code># Creating GUI with tkinter
import tkinter
from tkinter import *

base = Tk()
# from firebase import firebase
UserQus = []
BotAns = []

# This method is for tkinter button
def send():
    msg = EntryBox.get("1.0", 'end-1c').strip()
    EntryBox.delete("0.0", END)

    if msg != '':
        ChatLog.config(state=NORMAL)
        ChatLog.insert(END, "You: " + msg + '\n\n')
        ChatLog.config(foreground="#442265", font=("Verdana", 14))

        res = chatbot_response(msg)
        ChatLog.insert(END, "Bot: " + res + '\n\n')

        ChatLog.config(state=DISABLED)
        ChatLog.yview(END)
# here msg an res are append in UserQus and BotAns
    UserQus.append(msg)
    BotAns.append(res)

def on_closing():
    from firebase import firebase
    firebase = firebase.FirebaseApplication('https://fir-demopython.firebaseio.com/', None)
# here UserQus and BotAns are sore in data variable for define in firebase.post() # that store in database
    data = {'You': UserQus, 'Bot': BotAns}
    res = firebase.post('fir-demopython/DemoTbl', data)
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        base.destroy()
</code>```

答:
Quite simply: you are defining the on_closing() function within the send() function. This means that 1/ it's created anew each time send is called, and 2/ it's only visible within the send function (it's a local variable).

Just move your on_closing() definition outside the send() function (and move your imports at the top level too), and the problem is solved:

```<code># imports should NOT be in functions
from firebase import firebase

def send():
    msg = EntryBox.get("1.0", 'end-1c').strip()
    EntryBox.delete("0.0", END)
    if msg != '':
        ChatLog.config(state=NORMAL)
        ChatLog.insert(END, "You: " + msg + '\n\n')
        ChatLog.config(foreground="#442265", font=("Verdana", 12))

        res = chatbot_response(msg)
        ChatLog.insert(END, "Bot: " + res + '\n\n')

        ChatLog.config(state=DISABLED)
        ChatLog.yview(END)
    UserQus.append(msg)
    BotAns.append(res)

# and this should not be defined within the `send()` function, of course
def on_closing():
    firebase = firebase.FirebaseApplication('https://fir-demopython.firebaseio.com/', None)
    data = {'You': UserQus, 'Bot': BotAns}
    res = firebase.post('fir-demopython/DemoTbl', data)
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        base.destroy()
</code>```

Body:
1.This is my code here you can see the send() method. I want to use UserQus and BotAns out of send method in on_closing() method for sore in firebase database, I can't do it so, please give me solution for it.

# Creating GUI with tkinter
import tkinter
from tkinter import *

base = Tk()
# from firebase import firebase
UserQus = []
BotAns = []

# This method is for tkinter button
def send():
    msg = EntryBox.get("1.0", 'end-1c').strip()
    EntryBox.delete("0.0", END)

    if msg != '':
        ChatLog.config(state=NORMAL)
        ChatLog.insert(END, "You: " + msg + '\n\n')
        ChatLog.config(foreground="#442265", font=("Verdana", 14))

        res = chatbot_response(msg)
        ChatLog.insert(END, "Bot: " + res + '\n\n')

        ChatLog.config(state=DISABLED)
        ChatLog.yview(END)
# here msg an res are append in UserQus and BotAns
    UserQus.append(msg)
    BotAns.append(res)

def on_closing():
    from firebase import firebase
    firebase = firebase.FirebaseApplication('https://fir-demopython.firebaseio.com/', None)
# here UserQus and BotAns are sore in data variable for define in firebase.post() # that store in database
    data = {'You': UserQus, 'Bot': BotAns}
    res = firebase.post('fir-demopython/DemoTbl', data)
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        base.destroy()

Body:
Quite simply: you are defining the on_closing() function within the send() function. This means that 1/ it's created anew each time send is called, and 2/ it's only visible within the send function (it's a local variable).

Just move your on_closing() definition outside the send() function (and move your imports at the top level too), and the problem is solved:

# imports should NOT be in functions
from firebase import firebase

def send():
    msg = EntryBox.get("1.0", 'end-1c').strip()
    EntryBox.delete("0.0", END)
    if msg != '':
        ChatLog.config(state=NORMAL)
        ChatLog.insert(END, "You: " + msg + '\n\n')
        ChatLog.config(foreground="#442265", font=("Verdana", 12))

        res = chatbot_response(msg)
        ChatLog.insert(END, "Bot: " + res + '\n\n')

        ChatLog.config(state=DISABLED)
        ChatLog.yview(END)
    UserQus.append(msg)
    BotAns.append(res)

# and this should not be defined within the `send()` function, of course
def on_closing():
    firebase = firebase.FirebaseApplication('https://fir-demopython.firebaseio.com/', None)
    data = {'You': UserQus, 'Bot': BotAns}
    res = firebase.post('fir-demopython/DemoTbl', data)
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        base.destroy()


问:
Passing variable from type std::function fails although the caller expect the exact same type
for some reason I cannot pass value to method with the exact type.

But if I cast the variable I wish to pass using decltype of itself, it somehow works (?)
Perhaps anybody know what's the reason.

Also, When I pass the lambda block to std::function it doesn't require any casting, although they're not exactly the same.

the following example demonstrate my findings :

```<code>#include <functional>

class A {
public:
    A(std::function<void(std::string&, int)> &&f): _f(f) { }

    std::function<void(std::string&,int)> _f;
};

class B : public A {
public:
    //B(std::function<void(std::string&, int)> &&f) : A(f) { } --> fail on casting error, why ?
    B(std::function<void(std::string&, int)> &&f) : A((decltype(f)) f) { }
};

class C {
public:
    C(std::function<void(std::string&,int)> f) {
        //b = new B(f); --> this one trigger casting error, why ?
        b = new B((decltype(f)) f);
    }
    B *b;
};

int main(int argc, const char * argv[]) {
    // this works for some reason, even though C c'tor expect std::function ... why ?
    C c([=](std::string&a, int b) {
        printf("%s %d\n", a.c_str(), b);
    });
}

</code>```

答:
The problem is that the A's and B's constructors expect an rvalue reference, while you're passing an lvalue. Let's consider B's constructor:

```<code>B(std::function<void(std::string&, int)> &&f) : A((decltype(f)) f) { }
</code>```

Since the argument f is declared as an rvalue reference, it can only bind to an rvalue on the caller side. In other words, passing an lvalue as the argument to the constructor is illegal.

However, this argument in the context of the function body (including the constructor's initializer list) f is an lvalue. Which means it cannot be passed to A's constructor (which also expects an rvalue) directly. What you're doing by the (decltype(f)) cast is casting f to rvalue reference. The more conventional way of doing this is using std::move:

```<code>B(std::function<void(std::string&, int)> &&f) : A(std::move(f)) { }
</code>```

By calling std::move you cast the f lvalue to an rvalue reference without copying.

In other places, you have the same problem - you're trying to pass an lvalue as an rvalue argument. Use std::move to fix that as well.

Now, to this part:

```<code>// this works for some reason, even though C c'tor expect std::function ... why ?
C c([=](std::string&a, int b) {
    printf("%s %d\n", a.c_str(), b);
});
</code>```

This works because std::function has an implicit converting constructor from a function object, which a lambda function is. This code implicitly constructs a temporary std::function<void(std::string&, int)> object, which copies the lambda to its internal storage. That temporary is then passed to C's constructor (assuming that copy elision takes place, otherwise a copy of that temporary is passed to the constructor).

Body:
for some reason I cannot pass value to method with the exact type.

But if I cast the variable I wish to pass using decltype of itself, it somehow works (?)
Perhaps anybody know what's the reason.

Also, When I pass the lambda block to std::function it doesn't require any casting, although they're not exactly the same.

the following example demonstrate my findings :

#include <functional>

class A {
public:
    A(std::function<void(std::string&, int)> &&f): _f(f) { }

    std::function<void(std::string&,int)> _f;
};

class B : public A {
public:
    //B(std::function<void(std::string&, int)> &&f) : A(f) { } --> fail on casting error, why ?
    B(std::function<void(std::string&, int)> &&f) : A((decltype(f)) f) { }
};

class C {
public:
    C(std::function<void(std::string&,int)> f) {
        //b = new B(f); --> this one trigger casting error, why ?
        b = new B((decltype(f)) f);
    }
    B *b;
};

int main(int argc, const char * argv[]) {
    // this works for some reason, even though C c'tor expect std::function ... why ?
    C c([=](std::string&a, int b) {
        printf("%s %d\n", a.c_str(), b);
    });
}

Body:
The problem is that the A's and B's constructors expect an rvalue reference, while you're passing an lvalue. Let's consider B's constructor:

B(std::function<void(std::string&, int)> &&f) : A((decltype(f)) f) { }

Since the argument f is declared as an rvalue reference, it can only bind to an rvalue on the caller side. In other words, passing an lvalue as the argument to the constructor is illegal.

However, this argument in the context of the function body (including the constructor's initializer list) f is an lvalue. Which means it cannot be passed to A's constructor (which also expects an rvalue) directly. What you're doing by the (decltype(f)) cast is casting f to rvalue reference. The more conventional way of doing this is using std::move:

B(std::function<void(std::string&, int)> &&f) : A(std::move(f)) { }

By calling std::move you cast the f lvalue to an rvalue reference without copying.

In other places, you have the same problem - you're trying to pass an lvalue as an rvalue argument. Use std::move to fix that as well.

Now, to this part:

// this works for some reason, even though C c'tor expect std::function ... why ?
C c([=](std::string&a, int b) {
    printf("%s %d\n", a.c_str(), b);
});

This works because std::function has an implicit converting constructor from a function object, which a lambda function is. This code implicitly constructs a temporary std::function<void(std::string&, int)> object, which copies the lambda to its internal storage. That temporary is then passed to C's constructor (assuming that copy elision takes place, otherwise a copy of that temporary is passed to the constructor).


问:
WinSock2 send returns SOCKET_ERROR after 6 loops iterations... Why?
After 6 iterations, the send returns -1 aka SOCKET_ERROR. I tried adding a sleep function so it would wait a second before looping through again, but that made it so that it would only iterate 2 times. What is causing this error?</p>

```<code>#pragma comment(lib, "ws2_32.lib")

    #include <iostream>
    #include <windows.h>
        void main ()
    {
        int reqVersion = 2;

        WSADATA wsaData;

        if (WSAStartup(MAKEWORD(reqVersion,0), &wsaData)==0)
    {
        // Check if major version is at least reqVersion
        if (LOBYTE(wsaData.wVersion) >= reqVersion)
        {
            SOCKADDR_IN addr;
            int addrlen = sizeof(addr);

            SOCKET sListen;
            SOCKET sConnect;

            sConnect = socket(AF_INET, SOCK_STREAM, NULL);

            addr.sin_addr.s_addr = inet_addr("192.168.0.7");
            addr.sin_family = AF_INET;
            addr.sin_port = htons(1234);

            if(connect(sConnect, (SOCKADDR*)&addr, sizeof(addr)) == 0)
            {
                char message[10] = "Hellooooo";
                for(int i = 0; i <50; i++)
                {
                    int sendOutcome = send(sConnect, message, sizeof(message), 0);
                    if(sendOutcome == SOCKET_ERROR)
                    {
                        std::cout << "Socket Error..." << std::endl;
                    }
                    else
                    {
                        std::cout << "SENT..." << std::endl;
                    }
                    Sleep(1000);
                }
            }
            else
            {
                std::cout << "Not Connected..." << std::endl;
            }

        }
        else
        {
            std::cout << "Required version not available..." << std::endl;
        }

        // Cleanup winsock
        if (WSACleanup()!=0)
        {
            std::cout << "Cleanup failed..." << std::endl;
        }
    }
    else
    {
        std::cout << "Startup failed..." << std::endl;
    }
        system("PAUSE");
    }
</code>```

答:
It's always useful to obtain the actual error, as sarnold's comment suggested.

In general, socket's code that checks for errors will have a call to WSAGetLastError() after the code that detects the issue by checking for a SOCKET_ERROR return value.

The error code that you get from WSAGetLastError() is important and you can usually reason about the problem once you know what it means.

You can display the text of this error code using FormatMessage() or you can look it up by hand in the WinError.h header.

In this case, 10053 is WSAECONNABORTED for which the error text says "An established connection was aborted by the software in your host machine."

So, I would assume that the server that you are connecting to is aborting the connection for some reason. Without seeing the server source code it's hard to know why that might be.

Body:
After 6 iterations, the send returns -1 aka SOCKET_ERROR. I tried adding a sleep function so it would wait a second before looping through again, but that made it so that it would only iterate 2 times. What is causing this error?

#pragma comment(lib, "ws2_32.lib")

    #include <iostream>
    #include <windows.h>
        void main ()
    {
        int reqVersion = 2;

        WSADATA wsaData;

        if (WSAStartup(MAKEWORD(reqVersion,0), &wsaData)==0)
    {
        // Check if major version is at least reqVersion
        if (LOBYTE(wsaData.wVersion) >= reqVersion)
        {
            SOCKADDR_IN addr;
            int addrlen = sizeof(addr);

            SOCKET sListen;
            SOCKET sConnect;

            sConnect = socket(AF_INET, SOCK_STREAM, NULL);

            addr.sin_addr.s_addr = inet_addr("192.168.0.7");
            addr.sin_family = AF_INET;
            addr.sin_port = htons(1234);

            if(connect(sConnect, (SOCKADDR*)&addr, sizeof(addr)) == 0)
            {
                char message[10] = "Hellooooo";
                for(int i = 0; i <50; i++)
                {
                    int sendOutcome = send(sConnect, message, sizeof(message), 0);
                    if(sendOutcome == SOCKET_ERROR)
                    {
                        std::cout << "Socket Error..." << std::endl;
                    }
                    else
                    {
                        std::cout << "SENT..." << std::endl;
                    }
                    Sleep(1000);
                }
            }
            else
            {
                std::cout << "Not Connected..." << std::endl;
            }

        }
        else
        {
            std::cout << "Required version not available..." << std::endl;
        }

        // Cleanup winsock
        if (WSACleanup()!=0)
        {
            std::cout << "Cleanup failed..." << std::endl;
        }
    }
    else
    {
        std::cout << "Startup failed..." << std::endl;
    }
        system("PAUSE");
    }


问:
Use Environment Variables within a Traefik dynamic configuration
I am trying to build a Traefik dynamic configuration that has a rule for "Host(app.localhost)" in development but uses "Host(realname.com)" in production. I'm also using Docker but I don't think that is relevant to my question. My question is: is there an idiomatic way to use environment variables in my dynamic configuration?

The docs mention Go templates but I don't understand it beyond that. It's really lacking. I've also considered something like envsubst but was hoping to not have to install another tool.

I'm using Traefik 2.0+. Also, I must use the File Provider as I'm using a self-signed cert locally for TLS. From Traefik's documentation:

In the above example, we've used the file provider to handle these definitions. It is the only available method to configure the certificates (as well as the options and the stores). However, in Kubernetes, the certificates can and must be provided by secrets.

答:
Using traefik v2.0+ docker image, you can simply use docker-compose and define your environment variables in .env file. Then use labels like this below example.

Example

Uses File provider to add self-signed TLS certificates for localhost using traefik CLI command:

--providers.file.filename=/etc/traefik/certs.toml

.env file in local:

```<code># Environment variables for docker-compose.yml
LOG_LEVEL=DEBUG
NETWORK=net

## dashboard configs
DASHBOARD_HOST=app.localhost
CONFIG_PATH=./config
CERT_PATH=./certs
</code>```

.env file in production:

```<code># Environment variables for docker-compose.yml
# LOG_LEVEL=INFO
LOG_LEVEL=ERROR
NETWORK=net

## dashboard configs
DASHBOARD_HOST=realname.com
CONFIG_PATH=./config
CERT_PATH=./certs
</code>```

docker-compose.yml:

version: "3.5"

services:
  traefik:
    # Setting container_name disables running multinple instances of this service
    container_name: traefik
    image: traefik:v2.1
    command:
      - --entrypoints.web.address=:80
      - --entrypoints.websecure.address=:443
      - --log.level=${LOG_LEVEL}
      - --providers.docker
      - --providers.docker.exposedbydefault=false
      - --providers.file.filename=/etc/traefik/certs.toml
      - --api
    ports:
      - "80:80"
      - "443:443"
    networks:
      - net
    volumes:
      - "${CERT_PATH}:/certs"
      - "${CONFIG_PATH}:/etc/traefik"
      - "/var/run/docker.sock:/var/run/docker.sock:ro"
    labels:
      # set this lebel to `false` and the rest is history
      traefik.enable: true
      # middleware redirect
      traefik.http.middlewares.redirect-to-https.redirectscheme.scheme: https

      # redirection HTTP to HTTPS
      traefik.http.routers.http_catchall.rule: hostregexp(`{host:.+}`)
      traefik.http.routers.http_catchall.entrypoints: web
      traefik.http.routers.http_catchall.middlewares: redirect-to-https

      # dashboard
      traefik.http.routers.traefik.rule: Host(`${DASHBOARD_HOST}`)
      traefik.http.routers.traefik.entrypoints: websecure
      traefik.http.routers.traefik.service: api@internal
      traefik.http.routers.traefik.tls: true

networks:
  net:
    external: false
    name: ${NETWORK}
```

<h3><strong>config/certs.toml:</strong></h3>

<pre class="lang-toml prettyprint-override"><code>[tls.stores.default.defaultCertificate]
  certFile = "/certs/cert.crt"
  keyFile = "/certs/cert.key"

</code>```

certs/cert.crt:

```<code>-----BEGIN CERTIFICATE-----
<THE CERTIFICATE STRING>
-----END CERTIFICATE-----
</code>```

certs/cert.key:

```<code>-----BEGIN RSA PRIVATE KEY-----
<THE RSA PRIVATE KEY STRING>
-----END RSA PRIVATE KEY-----
</code>```

docker-compose will replace all the variables like ${DASHBOARD_HOST} with the values defined in .env file.

Then, you can validate your config using: docker-compose config

Run using: docker-compose up -d

-d flag is for detached mode, runs containers in the background

Source Files:
You can refer to this repository on github to find an elaborate version of this example, on how to setup traefik v2 using docker-compose for self-signed or to automatically acquire Let's Encrypt wildcard certificates.

Body:
Using traefik v2.0+ docker image, you can simply use docker-compose and define your environment variables in .env file. Then use labels like this below example.

Example

Uses File provider to add self-signed TLS certificates for localhost using traefik CLI command:

--providers.file.filename=/etc/traefik/certs.toml

.env file in local:

# Environment variables for docker-compose.yml
LOG_LEVEL=DEBUG
NETWORK=net

## dashboard configs
DASHBOARD_HOST=app.localhost
CONFIG_PATH=./config
CERT_PATH=./certs

.env file in production:

# Environment variables for docker-compose.yml
# LOG_LEVEL=INFO
LOG_LEVEL=ERROR
NETWORK=net

## dashboard configs
DASHBOARD_HOST=realname.com
CONFIG_PATH=./config
CERT_PATH=./certs

docker-compose.yml:

version: "3.5"

services:
  traefik:
    # Setting container_name disables running multinple instances of this service
    container_name: traefik
    image: traefik:v2.1
    command:
      - --entrypoints.web.address=:80
      - --entrypoints.websecure.address=:443
      - --log.level=${LOG_LEVEL}
      - --providers.docker
      - --providers.docker.exposedbydefault=false
      - --providers.file.filename=/etc/traefik/certs.toml
      - --api
    ports:
      - "80:80"
      - "443:443"
    networks:
      - net
    volumes:
      - "${CERT_PATH}:/certs"
      - "${CONFIG_PATH}:/etc/traefik"
      - "/var/run/docker.sock:/var/run/docker.sock:ro"
    labels:
      # set this lebel to `false` and the rest is history
      traefik.enable: true
      # middleware redirect
      traefik.http.middlewares.redirect-to-https.redirectscheme.scheme: https

      # redirection HTTP to HTTPS
      traefik.http.routers.http_catchall.rule: hostregexp(`{host:.+}`)
      traefik.http.routers.http_catchall.entrypoints: web
      traefik.http.routers.http_catchall.middlewares: redirect-to-https

      # dashboard
      traefik.http.routers.traefik.rule: Host(`${DASHBOARD_HOST}`)
      traefik.http.routers.traefik.entrypoints: websecure
      traefik.http.routers.traefik.service: api@internal
      traefik.http.routers.traefik.tls: true

networks:
  net:
    external: false
    name: ${NETWORK}

config/certs.toml:

[tls.stores.default.defaultCertificate]
  certFile = "/certs/cert.crt"
  keyFile = "/certs/cert.key"

certs/cert.crt:

-----BEGIN CERTIFICATE-----
<THE CERTIFICATE STRING>
-----END CERTIFICATE-----

certs/cert.key:

-----BEGIN RSA PRIVATE KEY-----
<THE RSA PRIVATE KEY STRING>
-----END RSA PRIVATE KEY-----

docker-compose will replace all the variables like ${DASHBOARD_HOST} with the values defined in .env file.

Then, you can validate your config using: docker-compose config

Run using: docker-compose up -d

-d flag is for detached mode, runs containers in the background

Source Files:
You can refer to this repository on github to find an elaborate version of this example, on how to setup traefik v2 using docker-compose for self-signed or to automatically acquire Let's Encrypt wildcard certificates.


问:
Using `when` should return different values
I am writing a unit test where I am mocking the init function from the class I want to test.

I have two context variables which use same configuration value but how can I mock in a way that both context variables have a different context value. As of now they both have same context.

```<code>class StandardRendererUtility @Inject constructor(app: App, private val rendererLocale: String) {

private val rendererLocaleContext: Context //has rendererLocaleContext
private val defaultLocaleContext: Context //has rendererLocaleContext

init {
    val configuration = Configuration(app.getApplicationContext().getResources().getConfiguration())
    configuration.setLocale(Locale(rendererLocale))
    rendererLocaleContext = app.getApplicationContext().createConfigurationContext(configuration)
    configuration.setLocale(Locale(DEFAULT_LOCALE))
    defaultLocaleContext = app.getApplicationContext().createConfigurationContext(configuration)
}

}
</code>```

My test function

```<code>@RunWith(MockitoJUnitRunner::class)
class StandardRendererUtilityTest {
    private lateinit var standardRendererUtility: StandardRendererUtility

    @Mock
    private lateinit var app: App
    @Mock
    private lateinit var context: Context
    @Mock
    private lateinit var configuration: Configuration
    @Mock
    private lateinit var rendererLocaleContext: Context
    @Mock
    private lateinit var defaultLocaleContext: Context
    @Mock
    private lateinit var resources: Resources
    @Mock
    private lateinit var rendererLocaleResources: Resources
    @Mock
    private lateinit var defaultLocaleResources: Resources

@Before
fun setup(){
    MockitoAnnotations.initMocks(this)
    `when`(app.getApplicationContext()).thenReturn(context)
    `when`(context.getResources()).thenReturn(resources)
    `when`(resources.getConfiguration()).thenReturn(configuration)
    `when`(context.createConfigurationContext(ArgumentMatchers.any())).thenReturn(rendererLocaleContext)
//AT THIS POINT I THINK SHOULD BE CORRECTED. HOW CAN I RETURN defaultLocaleContext AS WELL
    standardRendererUtility = StandardRendererUtility(app, "fr")

}

}
</code>```

答:
according to the API you have two options:

chain the thenReturn() method calls (which I'd prefer for readaility):

```<code>when(context.createConfigurationContext(ArgumentMatchers.any()))
      .thenReturn(rendererLocaleContext)
      .thenReturn(defaultLocaleContext);
</code>```

provide the objects to return as varags to thenReturn()

```<code>when(context.createConfigurationContext(ArgumentMatchers.any()))
      .thenReturn(rendererLocaleContext, defaultLocaleContext);
</code>```

Body:
I am writing a unit test where I am mocking the init function from the class I want to test.

I have two context variables which use same configuration value but how can I mock in a way that both context variables have a different context value. As of now they both have same context.

class StandardRendererUtility @Inject constructor(app: App, private val rendererLocale: String) {

private val rendererLocaleContext: Context //has rendererLocaleContext
private val defaultLocaleContext: Context //has rendererLocaleContext

init {
    val configuration = Configuration(app.getApplicationContext().getResources().getConfiguration())
    configuration.setLocale(Locale(rendererLocale))
    rendererLocaleContext = app.getApplicationContext().createConfigurationContext(configuration)
    configuration.setLocale(Locale(DEFAULT_LOCALE))
    defaultLocaleContext = app.getApplicationContext().createConfigurationContext(configuration)
}

}

My test function

@RunWith(MockitoJUnitRunner::class)
class StandardRendererUtilityTest {
    private lateinit var standardRendererUtility: StandardRendererUtility

    @Mock
    private lateinit var app: App
    @Mock
    private lateinit var context: Context
    @Mock
    private lateinit var configuration: Configuration
    @Mock
    private lateinit var rendererLocaleContext: Context
    @Mock
    private lateinit var defaultLocaleContext: Context
    @Mock
    private lateinit var resources: Resources
    @Mock
    private lateinit var rendererLocaleResources: Resources
    @Mock
    private lateinit var defaultLocaleResources: Resources

@Before
fun setup(){
    MockitoAnnotations.initMocks(this)
    `when`(app.getApplicationContext()).thenReturn(context)
    `when`(context.getResources()).thenReturn(resources)
    `when`(resources.getConfiguration()).thenReturn(configuration)
    `when`(context.createConfigurationContext(ArgumentMatchers.any())).thenReturn(rendererLocaleContext)
//AT THIS POINT I THINK SHOULD BE CORRECTED. HOW CAN I RETURN defaultLocaleContext AS WELL
    standardRendererUtility = StandardRendererUtility(app, "fr")

}

}

Body:
according to the API you have two options:

chain the thenReturn() method calls (which I'd prefer for readaility):

when(context.createConfigurationContext(ArgumentMatchers.any()))
      .thenReturn(rendererLocaleContext)
      .thenReturn(defaultLocaleContext);

provide the objects to return as varags to thenReturn()

when(context.createConfigurationContext(ArgumentMatchers.any()))
      .thenReturn(rendererLocaleContext, defaultLocaleContext);


问:
Getting the average of each 2 elements on a list
I have a list of numbers. (I will give an example down below.) I wanted to understand how to sum 1st and 3rd element, 3rd and 4th element and divide by them half. Homever each time I change the values with a loop for example, the new i value takes place for the considered loop so, all my values get messed up. I am leaving the code I have tried down below for this to work.

```<code>for i in liste6:
    liste6[i]=((liste6[i]+liste6[i+2])/2)
</code>```

Also this doesn't work on float values the values I have are 10.0 not floats entirely but floats by concept.

What I have:

```<code>[10.0, 10.0, 40.0, 40.0, 60.0, 10.0, 90.0, 40.0]
</code>```

Desired:

```<code>[25.0, 25.0, 75.0, 25.0]
</code>```

Note: The list is changing but this is the main issue.

Edit: I am sorry, I didn't clarify how you got the second list from the first one.
For each 4 elements I want to get the average of the 1st and the 3rd elements for in this case 10 and 40, 10 and 40. On the other 4 element set (the average of 60,90 and 10 and 40.

I am very sorry for the bad explanation .
Have a great day

答:
You are using a for-each loop in the way you'd use a for loop, it's either

```<code>for item in lst:
    # item: item
</code>```

or

```<code>for i in range(len(lst)):
    # item: lst[i]
</code>```

For this purpose I think a for loop would be more appropriate, but going through the whole range of indexes will result in out of bounds errors, so the right code would look something like this:

```<code>output = []
for i in range(len(lst)-1):
    output.append((lst[i] + lst[i + 1])/2)
</code>```

This way you would get a list filled with the averages in the output variable.

Body:
I have a list of numbers. (I will give an example down below.) I wanted to understand how to sum 1st and 3rd element, 3rd and 4th element and divide by them half. Homever each time I change the values with a loop for example, the new i value takes place for the considered loop so, all my values get messed up. I am leaving the code I have tried down below for this to work.

for i in liste6:
    liste6[i]=((liste6[i]+liste6[i+2])/2)

Also this doesn't work on float values the values I have are 10.0 not floats entirely but floats by concept.

What I have:

[10.0, 10.0, 40.0, 40.0, 60.0, 10.0, 90.0, 40.0]

Desired:

[25.0, 25.0, 75.0, 25.0]

Note: The list is changing but this is the main issue.

Edit: I am sorry, I didn't clarify how you got the second list from the first one.
For each 4 elements I want to get the average of the 1st and the 3rd elements for in this case 10 and 40, 10 and 40. On the other 4 element set (the average of 60,90 and 10 and 40.

I am very sorry for the bad explanation .
Have a great day

Body:
You are using a for-each loop in the way you'd use a for loop, it's either

for item in lst:
    # item: item

or

for i in range(len(lst)):
    # item: lst[i]

For this purpose I think a for loop would be more appropriate, but going through the whole range of indexes will result in out of bounds errors, so the right code would look something like this:

output = []
for i in range(len(lst)-1):
    output.append((lst[i] + lst[i + 1])/2)

This way you would get a list filled with the averages in the output variable.