问:
Trying to solve model using pyomo and bonmin. Model not passed to solver correctly
I wish to use Pyomo and Bonmin in an operations research seminar concerning the "Extended Supporting Hyperplane Algorithm" from Kronqvist. I wish to use bonmin to compare the performance of the algorithm. First I want to test, whether Bonmin is installed correctly and it is working in together with pyomo, so I modeled an example from the paper mentioned above. It is a convex problem, so bonmin should be able to solve it.

My OS is Windows 7, so I installed Bonmin using Cygwin and added it to my PATh. I did not notice any error message during the installation. For Programming I am using Anaconda with Jupyter Notebook.

I am currently reading through the pyomos documentation, but did not have any luck so far.

```<code>from pyomo.environ import *
import numpy
import scipy

# Konkretes Optimierungsproblem

model = ConcreteModel(name = "Example 1")

model.x1 = Var(bounds=(1,20), within=Reals)
model.x2 = Var(bounds=(1,20), within=Integers)

model.obj = Objective(expr=(-1)*model.x1-model.x2)

model.g1 = Constraint(expr=0.15*((model.x1 - 8)**2)+0.1*((model.x2 - 6)**2)+0.025*exp(model.x1)*((model.x2)**(-2))-5<=0)
model.g2 = Constraint(expr=(model.x1)**(-1) + (model.x2)**(-1) - (model.x1)**(-0.5) * (model.x2) ** (-0.5)+4<=0)
model.l1 = Constraint(expr=2 * (model.x1) - 3 * (model.x2) -2<=0)

#Just some output to analze the generated model

print(model)
dir(model)
print(model.g2.expr)
model.x1 = 5
print(value(model.x1))

opt = SolverFactory('bonmin')
#opt.options['bonmin.algorithm'] = 'Bonmin'
print('using Bonmin')
# Set Options for solver.
opt.options['bonmin.solution_limit'] = '1'
opt.options['bonmin.time_limit'] = 1800
results = opt.solve(model)
results.write()
</code>```

These are the results:

```<code>using Bonmin
WARNING: Loading a SolverResults object with a warning status into
    model=Example 1;
        message from solver=bonmin\x3a Infeasible problem
# ==========================================================
# = Solver Results                                         =
# ==========================================================
# ----------------------------------------------------------
#   Problem Information
# ----------------------------------------------------------
Problem:
- Lower bound: -inf
  Upper bound: inf
  Number of objectives: 1
  Number of constraints: 0
  Number of variables: 0
  Sense: unknown
# ----------------------------------------------------------
#   Solver Information
# ----------------------------------------------------------
Solver:
- Status: warning
  Message: bonmin\x3a Infeasible problem
  Termination condition: infeasible
  Id: 220
  Error rc: 0
  Time: 0.16000056266784668
# ----------------------------------------------------------
#   Solution Information
# ----------------------------------------------------------
Solution:
- number of solutions: 0
  number of solutions displayed: 0
</code>```

As you can see, the model ist not transferred to the solver correctly, since according to the solver the problem has neither constraints nor variables.

Could the problem be the warning stauts of the Solver meaning it is not installed correctly or is this due to the problem being infeasible?

Edit: As suggested by Bethany Nicholson in the comments, I added the option tee=tree in the code, which lead to the following output

```<code>using Bonmin
Bonmin 1.8.7 using Cbc 2.10.0 and Ipopt 3.12.12
bonmin: bonmin.solution_limit=1
bonmin.time_limit=1800
bonmin.solution_limit=1
bonmin.time_limit=1800

******************************************************************************
This program contains Ipopt, a library for large-scale nonlinear optimization.
 Ipopt is released as open source code under the Eclipse Public License (EPL).
         For more information visit http://projects.coin-or.org/Ipopt
******************************************************************************

NLP0012I
              Num      Status      Obj             It       time                 Location
NLP0014I             1      INFEAS 4.0986776       27 0.031
NLP0014I             2      INFEAS 4.0986776       27 0.015
Cbc0006I The LP relaxation is infeasible or too expensive

    "Finished"
WARNING: Loading a SolverResults object with a warning status into
    model=Example 1;
        message from solver=bonmin\x3a Infeasible problem
# ==========================================================
# = Solver Results                                         =
# ==========================================================
# ----------------------------------------------------------
#   Problem Information
# ----------------------------------------------------------
Problem:
- Lower bound: -inf
  Upper bound: inf
  Number of objectives: 1
  Number of constraints: 0
  Number of variables: 0
  Sense: unknown
# ----------------------------------------------------------
#   Solver Information
# ----------------------------------------------------------
Solver:
- Status: warning
  Message: bonmin\x3a Infeasible problem
  Termination condition: infeasible
  Id: 220
  Error rc: 0
  Time: 0.23000025749206543
# ----------------------------------------------------------
#   Solution Information
# ----------------------------------------------------------
Solution:
- number of solutions: 0
  number of solutions displayed: 0
</code>```

Edit 2: I have tried other simple problems. While the problem is solved correctly (x1=4, x2=2, minvalue=-10) by Bonmin, its output states that the problems passed to the solver has no constraints, when it clearly has five (even though four might be interpreted as bounds). Furthermore, the output still appears a little strange to me. Why does it state "number of solutions = 0"? (I am still not through with the complete documentation of pyomo, maybe I just have to set additional parameters)
Here is the linear problem:

```<code>from pyomo.environ import *
import numpy
import scipy

model = ConcreteModel(name = "Linear problem")

model.x1 = Var(domain = Reals)
model.x2 = Var(domain = Reals)

model.obj = Objective(expr=-1*(2*model.x1+model.x2))

model.l1 = Constraint(expr=model.x1>=0)
model.l2 = Constraint(expr=model.x2>=0)
model.l3 = Constraint(expr=model.x1<=4)
model.l4 = Constraint(expr=model.x2<=4)
model.l5 = Constraint(expr=model.x1+model.x2<=6)
model.pprint()
2 Var Declarations
    x1 : Size=1, Index=None
        Key  : Lower : Value : Upper : Fixed : Stale : Domain
        None :  None :  None :  None : False :  True :  Reals
    x2 : Size=1, Index=None
        Key  : Lower : Value : Upper : Fixed : Stale : Domain
        None :  None :  None :  None : False :  True :  Reals

1 Objective Declarations
    obj : Size=1, Index=None, Active=True
        Key  : Active : Sense    : Expression
        None :   True : minimize : - (2*x1 + x2)

5 Constraint Declarations
    l1 : Size=1, Index=None, Active=True
        Key  : Lower : Body : Upper : Active
        None :   0.0 :   x1 :  +Inf :   True
    l2 : Size=1, Index=None, Active=True
        Key  : Lower : Body : Upper : Active
        None :   0.0 :   x2 :  +Inf :   True
    l3 : Size=1, Index=None, Active=True
        Key  : Lower : Body : Upper : Active
        None :  -Inf :   x1 :   4.0 :   True
    l4 : Size=1, Index=None, Active=True
        Key  : Lower : Body : Upper : Active
        None :  -Inf :   x2 :   4.0 :   True
    l5 : Size=1, Index=None, Active=True
        Key  : Lower : Body    : Upper : Active
        None :  -Inf : x1 + x2 :   6.0 :   True

8 Declarations: x1 x2 obj l1 l2 l3 l4 l5

opt = SolverFactory('bonmin')
opt.options['bonmin.solution_limit'] = '1'
opt.options['bonmin.time_limit'] = 1800
results = opt.solve(model, tee = True)
results.write()

Bonmin 1.8.7 using Cbc 2.10.0 and Ipopt 3.12.12
bonmin: bonmin.solution_limit=1
bonmin.time_limit=1800
bonmin.solution_limit=1
bonmin.time_limit=1800

Cbc3007W No integer variables - nothing to do

******************************************************************************
This program contains Ipopt, a library for large-scale nonlinear optimization.
 Ipopt is released as open source code under the Eclipse Public License (EPL).
         For more information visit http://projects.coin-or.org/Ipopt
******************************************************************************

NLP0012I
              Num      Status      Obj             It       time                 Location
NLP0014I             1         OPT -10        4 0
Cbc3007W No integer variables - nothing to do

    "Finished"
# ==========================================================
# = Solver Results                                         =
# ==========================================================
# ----------------------------------------------------------
#   Problem Information
# ----------------------------------------------------------
Problem:
- Lower bound: -inf
  Upper bound: inf
  Number of objectives: 1
  Number of constraints: 0
  Number of variables: 2
  Sense: unknown
# ----------------------------------------------------------
#   Solver Information
# ----------------------------------------------------------
Solver:
- Status: ok
  Message: bonmin\x3a Optimal
  Termination condition: optimal
  Id: 3
  Error rc: 0
  Time: 0.20000028610229492
# ----------------------------------------------------------
#   Solution Information
# ----------------------------------------------------------
Solution:
- number of solutions: 0
  number of solutions displayed: 0
</code>```

I am sorry if I appear to be spamming my post with code. Just thought it would be helpful, since I think this indicated that the problem lies with the solver rather than the modelling with pyomo.

答:
I had a meeting with my tutor yesterday. I actually overlooked an error in the model, which made it infeasible. Bonmin solves the problem correctly, but the output still looks strange (e.g. model possesses no constraints). He does understand the somewhat strange output of the solver either, however, he said I should not concern myself with it any further.

I deeply apologize for doing such a stupid mistake. Hopefully no one spent much time thinking on this question (except me of course).

Body:
I wish to use Pyomo and Bonmin in an operations research seminar concerning the "Extended Supporting Hyperplane Algorithm" from Kronqvist. I wish to use bonmin to compare the performance of the algorithm. First I want to test, whether Bonmin is installed correctly and it is working in together with pyomo, so I modeled an example from the paper mentioned above. It is a convex problem, so bonmin should be able to solve it.

My OS is Windows 7, so I installed Bonmin using Cygwin and added it to my PATh. I did not notice any error message during the installation. For Programming I am using Anaconda with Jupyter Notebook.

I am currently reading through the pyomos documentation, but did not have any luck so far.

from pyomo.environ import *
import numpy
import scipy

# Konkretes Optimierungsproblem

model = ConcreteModel(name = "Example 1")

model.x1 = Var(bounds=(1,20), within=Reals)
model.x2 = Var(bounds=(1,20), within=Integers)

model.obj = Objective(expr=(-1)*model.x1-model.x2)

model.g1 = Constraint(expr=0.15*((model.x1 - 8)**2)+0.1*((model.x2 - 6)**2)+0.025*exp(model.x1)*((model.x2)**(-2))-5<=0)
model.g2 = Constraint(expr=(model.x1)**(-1) + (model.x2)**(-1) - (model.x1)**(-0.5) * (model.x2) ** (-0.5)+4<=0)
model.l1 = Constraint(expr=2 * (model.x1) - 3 * (model.x2) -2<=0)

#Just some output to analze the generated model

print(model)
dir(model)
print(model.g2.expr)
model.x1 = 5
print(value(model.x1))

opt = SolverFactory('bonmin')
#opt.options['bonmin.algorithm'] = 'Bonmin'
print('using Bonmin')
# Set Options for solver.
opt.options['bonmin.solution_limit'] = '1'
opt.options['bonmin.time_limit'] = 1800
results = opt.solve(model)
results.write()

These are the results:

using Bonmin
WARNING: Loading a SolverResults object with a warning status into
    model=Example 1;
        message from solver=bonmin\x3a Infeasible problem
# ==========================================================
# = Solver Results                                         =
# ==========================================================
# ----------------------------------------------------------
#   Problem Information
# ----------------------------------------------------------
Problem:
- Lower bound: -inf
  Upper bound: inf
  Number of objectives: 1
  Number of constraints: 0
  Number of variables: 0
  Sense: unknown
# ----------------------------------------------------------
#   Solver Information
# ----------------------------------------------------------
Solver:
- Status: warning
  Message: bonmin\x3a Infeasible problem
  Termination condition: infeasible
  Id: 220
  Error rc: 0
  Time: 0.16000056266784668
# ----------------------------------------------------------
#   Solution Information
# ----------------------------------------------------------
Solution:
- number of solutions: 0
  number of solutions displayed: 0

As you can see, the model ist not transferred to the solver correctly, since according to the solver the problem has neither constraints nor variables.

Could the problem be the warning stauts of the Solver meaning it is not installed correctly or is this due to the problem being infeasible?

Edit: As suggested by Bethany Nicholson in the comments, I added the option tee=tree in the code, which lead to the following output

using Bonmin
Bonmin 1.8.7 using Cbc 2.10.0 and Ipopt 3.12.12
bonmin: bonmin.solution_limit=1
bonmin.time_limit=1800
bonmin.solution_limit=1
bonmin.time_limit=1800

******************************************************************************
This program contains Ipopt, a library for large-scale nonlinear optimization.
 Ipopt is released as open source code under the Eclipse Public License (EPL).
         For more information visit http://projects.coin-or.org/Ipopt
******************************************************************************

NLP0012I
              Num      Status      Obj             It       time                 Location
NLP0014I             1      INFEAS 4.0986776       27 0.031
NLP0014I             2      INFEAS 4.0986776       27 0.015
Cbc0006I The LP relaxation is infeasible or too expensive

    "Finished"
WARNING: Loading a SolverResults object with a warning status into
    model=Example 1;
        message from solver=bonmin\x3a Infeasible problem
# ==========================================================
# = Solver Results                                         =
# ==========================================================
# ----------------------------------------------------------
#   Problem Information
# ----------------------------------------------------------
Problem:
- Lower bound: -inf
  Upper bound: inf
  Number of objectives: 1
  Number of constraints: 0
  Number of variables: 0
  Sense: unknown
# ----------------------------------------------------------
#   Solver Information
# ----------------------------------------------------------
Solver:
- Status: warning
  Message: bonmin\x3a Infeasible problem
  Termination condition: infeasible
  Id: 220
  Error rc: 0
  Time: 0.23000025749206543
# ----------------------------------------------------------
#   Solution Information
# ----------------------------------------------------------
Solution:
- number of solutions: 0
  number of solutions displayed: 0

Edit 2: I have tried other simple problems. While the problem is solved correctly (x1=4, x2=2, minvalue=-10) by Bonmin, its output states that the problems passed to the solver has no constraints, when it clearly has five (even though four might be interpreted as bounds). Furthermore, the output still appears a little strange to me. Why does it state "number of solutions = 0"? (I am still not through with the complete documentation of pyomo, maybe I just have to set additional parameters)
Here is the linear problem:

from pyomo.environ import *
import numpy
import scipy

model = ConcreteModel(name = "Linear problem")

model.x1 = Var(domain = Reals)
model.x2 = Var(domain = Reals)

model.obj = Objective(expr=-1*(2*model.x1+model.x2))

model.l1 = Constraint(expr=model.x1>=0)
model.l2 = Constraint(expr=model.x2>=0)
model.l3 = Constraint(expr=model.x1<=4)
model.l4 = Constraint(expr=model.x2<=4)
model.l5 = Constraint(expr=model.x1+model.x2<=6)
model.pprint()
2 Var Declarations
    x1 : Size=1, Index=None
        Key  : Lower : Value : Upper : Fixed : Stale : Domain
        None :  None :  None :  None : False :  True :  Reals
    x2 : Size=1, Index=None
        Key  : Lower : Value : Upper : Fixed : Stale : Domain
        None :  None :  None :  None : False :  True :  Reals

1 Objective Declarations
    obj : Size=1, Index=None, Active=True
        Key  : Active : Sense    : Expression
        None :   True : minimize : - (2*x1 + x2)

5 Constraint Declarations
    l1 : Size=1, Index=None, Active=True
        Key  : Lower : Body : Upper : Active
        None :   0.0 :   x1 :  +Inf :   True
    l2 : Size=1, Index=None, Active=True
        Key  : Lower : Body : Upper : Active
        None :   0.0 :   x2 :  +Inf :   True
    l3 : Size=1, Index=None, Active=True
        Key  : Lower : Body : Upper : Active
        None :  -Inf :   x1 :   4.0 :   True
    l4 : Size=1, Index=None, Active=True
        Key  : Lower : Body : Upper : Active
        None :  -Inf :   x2 :   4.0 :   True
    l5 : Size=1, Index=None, Active=True
        Key  : Lower : Body    : Upper : Active
        None :  -Inf : x1 + x2 :   6.0 :   True

8 Declarations: x1 x2 obj l1 l2 l3 l4 l5

opt = SolverFactory('bonmin')
opt.options['bonmin.solution_limit'] = '1'
opt.options['bonmin.time_limit'] = 1800
results = opt.solve(model, tee = True)
results.write()

Bonmin 1.8.7 using Cbc 2.10.0 and Ipopt 3.12.12
bonmin: bonmin.solution_limit=1
bonmin.time_limit=1800
bonmin.solution_limit=1
bonmin.time_limit=1800

Cbc3007W No integer variables - nothing to do

******************************************************************************
This program contains Ipopt, a library for large-scale nonlinear optimization.
 Ipopt is released as open source code under the Eclipse Public License (EPL).
         For more information visit http://projects.coin-or.org/Ipopt
******************************************************************************

NLP0012I
              Num      Status      Obj             It       time                 Location
NLP0014I             1         OPT -10        4 0
Cbc3007W No integer variables - nothing to do

    "Finished"
# ==========================================================
# = Solver Results                                         =
# ==========================================================
# ----------------------------------------------------------
#   Problem Information
# ----------------------------------------------------------
Problem:
- Lower bound: -inf
  Upper bound: inf
  Number of objectives: 1
  Number of constraints: 0
  Number of variables: 2
  Sense: unknown
# ----------------------------------------------------------
#   Solver Information
# ----------------------------------------------------------
Solver:
- Status: ok
  Message: bonmin\x3a Optimal
  Termination condition: optimal
  Id: 3
  Error rc: 0
  Time: 0.20000028610229492
# ----------------------------------------------------------
#   Solution Information
# ----------------------------------------------------------
Solution:
- number of solutions: 0
  number of solutions displayed: 0

I am sorry if I appear to be spamming my post with code. Just thought it would be helpful, since I think this indicated that the problem lies with the solver rather than the modelling with pyomo.


来源: stackexchange

问:
How to extract text following a keyword in UNIX
I have a text file (file.txt) that contains a wall of results (no newlines, whitespaces etc) that I received from an external source.  From this file, I need to find all mentions of the word serId, and then print out the alpha-numeric sequence following it.  The alpha-numeric sequence is of any length but will end with the character ,.  How can I extract these alpha-numeric sequences?

I've tried finding scripts/code using sed / awk but the results seem to revolve around a known sequence to find, rather than an unknown sequence.

For example, I would like to extract 28655784-EE from the following sample text:

```<code>{"preRollbackCheckResults":[],"patchingHistory":[{"backupStatus":"Available","rollbackStatus":"Available","additionalNote":"Patching CDS as planned","appliedBy":"xxrbsgCDS02services","appliedDate":"2019-01-18T12:45:33.926+0000","totalTime":"29 min, 47 sec","serId":"28655784-EE","patchDescription":"DB 18.4.0.0.0 Oct 2018 PSU
</code>```

答:
grep -o is a really easy solution for this:

I've created a file, containing following lines:

```<code>serId12345
serIdABCde123;
Ser_idblabla;
</code>```

The first line does not end with a semi-colon, the third line starts with the wrong word, so only the second line is correct.

I've launched following command: grep -o "serId[0-9a-zA-Z]*;" testtttt.txt, with following result:

```<code>serIdABCde123;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a text file (file.txt) that contains a wall of results (no newlines, whitespaces etc) that I received from an external source.  From this file, I need to find all mentions of the word serId, and then print out the alpha-numeric sequence following it.  The alpha-numeric sequence is of any length but will end with the character ,.  How can I extract these alpha-numeric sequences?

I've tried finding scripts/code using sed / awk but the results seem to revolve around a known sequence to find, rather than an unknown sequence.

For example, I would like to extract 28655784-EE from the following sample text:

{"preRollbackCheckResults":[],"patchingHistory":[{"backupStatus":"Available","rollbackStatus":"Available","additionalNote":"Patching CDS as planned","appliedBy":"xxrbsgCDS02services","appliedDate":"2019-01-18T12:45:33.926+0000","totalTime":"29 min, 47 sec","serId":"28655784-EE","patchDescription":"DB 18.4.0.0.0 Oct 2018 PSU

Body:
grep -o is a really easy solution for this:

I've created a file, containing following lines:

serId12345
serIdABCde123;
Ser_idblabla;

The first line does not end with a semi-colon, the third line starts with the wrong word, so only the second line is correct.

I've launched following command: grep -o "serId[0-9a-zA-Z]*;" testtttt.txt, with following result:

serIdABCde123;


问:
redirectmatch changes post to get
I have two separated vhost. On the www. one, I have instaled this only line on .htaccess

```<code>redirectMatch 301 ^(.*)$ http://d_blur_blur_s.com$1
</code>```

All works as expected except that in the case where the POST is converted to GET.

Please notice that the post has parametres as a get  (i didn't do it, and I won't change it) i am just trying to avoid duplicated content. I am showing firebug trace.

I expect to have the POST redirected on the main domain with redirectmatch or other trick.

Update

I have half of the internal links on the site written with www and the other half without it. So I need to keep both public but not duplicated. I need the GETs forwarded as GETs and the POSTs frowarded as POSTs. the problem is big, I have 12000 pages indexed, and lot of forms. So I am first searching for a generic solution without changing code.  I full control de server.

Thanks a lot

答: In HTTP 1.1, statusCode (307) indicates that the request should be repeated using the same method and post data.  Change the redirect type to fix it.

ContentLicense: CC BY-SA 3.0

Title: redirectmatch changes post to get

Body:
I have two separated vhost. On the www. one, I have instaled this only line on .htaccess

redirectMatch 301 ^(.*)$ http://d_blur_blur_s.com$1

All works as expected except that in the case where the POST is converted to GET.

Please notice that the post has parametres as a get  (i didn't do it, and I won't change it) i am just trying to avoid duplicated content. I am showing firebug trace.

I expect to have the POST redirected on the main domain with redirectmatch or other trick.

Update

I have half of the internal links on the site written with www and the other half without it. So I need to keep both public but not duplicated. I need the GETs forwarded as GETs and the POSTs frowarded as POSTs. the problem is big, I have 12000 pages indexed, and lot of forms. So I am first searching for a generic solution without changing code.  I full control de server.

Thanks a lot


问:
Spinner entries bindingadapter room livedata not working
I am working on room livedata databinding concept. I am setting list to spinner using custom binding adapter. But i am getting null livedata while retrieving from room firsttime.

code:

```<code>     @Query("select * from Student")
        LiveData<List<Student>> getAllItems();

        @BindingAdapter({"bind:entries"})
            public static void customSpinnerBinding(AppCompatSpinner appCompatSpinner,LiveData<List<Student>> listLiveData){
                if(listLiveData != null && listLiveData.getValue().size() > 0){
                    ArrayAdapter<Student> spinnerArrayAdapter = new ArrayAdapter<Student>
                            (appCompatSpinner.getContext(), android.R.layout.simple_spinner_item,
                                    listLiveData.getValue()); //selected item will look like a spinner set from XML
                    spinnerArrayAdapter.setDropDownViewResource(android.R.layout
                            .simple_spinner_dropdown_item);
                    appCompatSpinner.setAdapter(spinnerArrayAdapter);
                }
            }

        public LiveData<List<Student>> getListLiveData() {
            if(listLiveData == null){
               listLiveData = studentDB.studentDao().getAllItems();
            }
            return listLiveData;
        }

        <android.support.v7.widget.AppCompatSpinner
                    android:id="@+id/spinner"
                    android:layout_width="0dp"
                    bind:entries="@{viewmodel.listLiveData}"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="16dp"
                    android:layout_marginLeft="16dp"
                    android:layout_marginTop="16dp"
                    android:layout_marginEnd="16dp"
                    android:layout_marginRight="16dp"
                    android:layout_marginBottom="16dp"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

but if i observe livedata in activity this is working

  mainViewModel.getListLiveData().observe(this, new Observer<List<Student>>() {
           @Override
           public void onChanged(@Nullable List<Student> students) {
               if(students.size() > 0){
                   ArrayAdapter<Student> spinnerArrayAdapter = new ArrayAdapter<Student>
                    (MainActivity.this, android.R.layout.simple_spinner_item,
                            students); //selected item will look like a spinner set from XML
            spinnerArrayAdapter.setDropDownViewResource(android.R.layout
                    .simple_spinner_dropdown_item);
            activityMainBinding.appbar.contentid.spinner.setAdapter(spinnerArrayAdapter);
               }
           }
       });
</code>```

答:
Try</p>

```<code>listLiveData = StudentDB.getAppDatabase(application).studentDao().getAllItems();
return listLiveData;
</code>```

Body:
I am working on room livedata databinding concept. I am setting list to spinner using custom binding adapter. But i am getting null livedata while retrieving from room firsttime.

code:

     @Query("select * from Student")
        LiveData<List<Student>> getAllItems();

        @BindingAdapter({"bind:entries"})
            public static void customSpinnerBinding(AppCompatSpinner appCompatSpinner,LiveData<List<Student>> listLiveData){
                if(listLiveData != null && listLiveData.getValue().size() > 0){
                    ArrayAdapter<Student> spinnerArrayAdapter = new ArrayAdapter<Student>
                            (appCompatSpinner.getContext(), android.R.layout.simple_spinner_item,
                                    listLiveData.getValue()); //selected item will look like a spinner set from XML
                    spinnerArrayAdapter.setDropDownViewResource(android.R.layout
                            .simple_spinner_dropdown_item);
                    appCompatSpinner.setAdapter(spinnerArrayAdapter);
                }
            }

        public LiveData<List<Student>> getListLiveData() {
            if(listLiveData == null){
               listLiveData = studentDB.studentDao().getAllItems();
            }
            return listLiveData;
        }

        <android.support.v7.widget.AppCompatSpinner
                    android:id="@+id/spinner"
                    android:layout_width="0dp"
                    bind:entries="@{viewmodel.listLiveData}"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="16dp"
                    android:layout_marginLeft="16dp"
                    android:layout_marginTop="16dp"
                    android:layout_marginEnd="16dp"
                    android:layout_marginRight="16dp"
                    android:layout_marginBottom="16dp"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

but if i observe livedata in activity this is working

  mainViewModel.getListLiveData().observe(this, new Observer<List<Student>>() {
           @Override
           public void onChanged(@Nullable List<Student> students) {
               if(students.size() > 0){
                   ArrayAdapter<Student> spinnerArrayAdapter = new ArrayAdapter<Student>
                    (MainActivity.this, android.R.layout.simple_spinner_item,
                            students); //selected item will look like a spinner set from XML
            spinnerArrayAdapter.setDropDownViewResource(android.R.layout
                    .simple_spinner_dropdown_item);
            activityMainBinding.appbar.contentid.spinner.setAdapter(spinnerArrayAdapter);
               }
           }
       });

Body:
Try

listLiveData = StudentDB.getAppDatabase(application).studentDao().getAllItems();
return listLiveData;


问:
Dashboard desktop lay-out responsive?
Building icCube dashboards for different devices is handled via lay-outs. This works nice. But when it comes to desktop dashboards, there is a wide range of screen-sizes and resolutions and you can make only one desktop lay-out.

For example, I've a 15" laptop for on the read that is connected to a 27" monitor on my workbench if I'm in the office. On my monitor I've far more space to have more widgets then on my laptop screen. It would be nice to create separate lay-out for different screen-sizes / screen-resolutions or make a responsive dashboard.

I'm curious if there is a solutions to handle different screen-sizes / screen-resolutions.

答:
Simple dashboard grid layout

```<code><div class="grid-container">
  <header class="header"></header>
  <aside class="sidenav"></aside>
  <main class="main"></main>
  <footer class="footer"></footer>
</div>
</code>```

Need to apply CSS

```<code>/* Simple dashboard grid CSS */

/* Assign grid instructions to our parent grid container */
.grid-container {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-rows: 50px 1fr 50px;
  grid-template-areas:
    "sidenav header"
    "sidenav main"
    "sidenav footer";
  height: 100vh;
}

/* Give every child element its grid name */
.header {
  grid-area: header;
  background-color: #648ca6;
}

.sidenav {
  grid-area: sidenav;
  background-color: #394263;
}

.main {
  grid-area: main;
  background-color: #8fd4d9;
}

.footer {
  grid-area: footer;
  background-color: #648ca6;
}
</code>```

Create the styles and structure for our header and footer elements; grid-area declared previously

```<code><style>
  .header, .footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 16px;
    background-color: #648ca6;
  }
</style>

<header class="header">
  <div class="header__search">Search...</div>
  <div class="header__avatar">Your face</div>
</header>

<footer class="footer">
  <div class="footer__copyright">© 2019</div>
  <div class="footer__signature">Sample</div>
</footer>
</code>```

Title: Dashboard desktop lay-out responsive?

Body:
Simple dashboard grid layout

<div class="grid-container">
  <header class="header"></header>
  <aside class="sidenav"></aside>
  <main class="main"></main>
  <footer class="footer"></footer>
</div>

Need to apply CSS

/* Simple dashboard grid CSS */

/* Assign grid instructions to our parent grid container */
.grid-container {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-rows: 50px 1fr 50px;
  grid-template-areas:
    "sidenav header"
    "sidenav main"
    "sidenav footer";
  height: 100vh;
}

/* Give every child element its grid name */
.header {
  grid-area: header;
  background-color: #648ca6;
}

.sidenav {
  grid-area: sidenav;
  background-color: #394263;
}

.main {
  grid-area: main;
  background-color: #8fd4d9;
}

.footer {
  grid-area: footer;
  background-color: #648ca6;
}

Create the styles and structure for our header and footer elements; grid-area declared previously

<style>
  .header, .footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 16px;
    background-color: #648ca6;
  }
</style>

<header class="header">
  <div class="header__search">Search...</div>
  <div class="header__avatar">Your face</div>
</header>

<footer class="footer">
  <div class="footer__copyright">&copy; 2019</div>
  <div class="footer__signature">Sample</div>
</footer>


问:
Mongo-Express: failed to connect to server [mongo:27017] on first connect
I'm trying to run the simplest container of mongo and mongo-express using docker-compose. I have faced with many errors that will be explained later on.

I have tried the following docker-compose configurations:

1.

```<code>version: '2'
services:
    mongo:
        image: mongo:latest
    mongo-express:
        image: mongo-express:latest
        ports:
            - 8082:8081
</code>```

2.

```<code>version: '2'

services:
  mongo:
    image: mongo:latest
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: root
    ports:
      - 27017:27017
    volumes:
      - db-data:/data/db
      - mongo-config:/data/configdb

  mongo-express:
    image: mongo-express
    restart: always
    ports:
      - 8081:8081
volumes:
  db-data:
  mongo-config:
</code>```

and etc. But all of them have the following common error whenever I execute docker-compose -f docker-compose.yml up:

```<code>mongo-express_1  | Mongo Express server listening at http://0.0.0.0:8081
mongo-express_1  | Server is open to allow connections from anyone (0.0.0.0)
mongo-express_1  | basicAuth credentials are "admin:pass", it is recommended you change this in your config.js!
mongo-express_1  |
mongo-express_1  | /node_modules/mongodb/lib/server.js:265
mongo-express_1  |         process.nextTick(function() { throw err; })
mongo-express_1  |                                       ^
mongo-express_1  | MongoError: failed to connect to server [mongo:27017] on first connect
mongo-express_1  |     at Pool.<anonymous> (/node_modules/mongodb-core/lib/topologies/server.js:326:35)
mongo-express_1  |     at emitOne (events.js:116:13)
mongo-express_1  |     at Pool.emit (events.js:211:7)
mongo-express_1  |     at Connection.<anonymous> (/node_modules/mongodb-core/lib/connection/pool.js:270:12)
mongo-express_1  |     at Object.onceWrapper (events.js:317:30)
mongo-express_1  |     at emitTwo (events.js:126:13)
mongo-express_1  |     at Connection.emit (events.js:214:7)
mongo-express_1  |     at Socket.<anonymous> (/node_modules/mongodb-core/lib/connection/connection.js:175:49)
mongo-express_1  |     at Object.onceWrapper (events.js:315:30)
mongo-express_1  |     at emitOne (events.js:116:13)
</code>```

I have searched this issue all over the internet and github repositories and tried the other solutions, but none of them worked appropriately.

link1 | link2 | link3 | link4 | etc.

答:
First I have run docker stop $(docker ps -a -q) and then changed the docker-compose.yml file to the following content:

```<code>version: '2'
services:
  mongo:
    image: mongo:3.4
    container_name: mongo
    ports:
      - '27017:27017'
    volumes:
      - '/data/configdb:/data/configdb'
      - '/data/db:/data/db'
  mongo-express:
    image: mongo-express:0.49.0
    container_name: mongo_express
    depends_on:
      - 'mongo'
    ports:
      - '5050:8081'
    environment:
      - 'ME_CONFIG_OPTIONS_EDITORTHEME=ambiance'
</code>```

Body:
I'm trying to run the simplest container of mongo and mongo-express using docker-compose. I have faced with many errors that will be explained later on.

I have tried the following docker-compose configurations:

1.

version: '2'
services:
    mongo:
        image: mongo:latest
    mongo-express:
        image: mongo-express:latest
        ports:
            - 8082:8081

2.

version: '2'

services:
  mongo:
    image: mongo:latest
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: root
    ports:
      - 27017:27017
    volumes:
      - db-data:/data/db
      - mongo-config:/data/configdb

  mongo-express:
    image: mongo-express
    restart: always
    ports:
      - 8081:8081
volumes:
  db-data:
  mongo-config:

and etc. But all of them have the following common error whenever I execute docker-compose -f docker-compose.yml up:

mongo-express_1  | Mongo Express server listening at http://0.0.0.0:8081
mongo-express_1  | Server is open to allow connections from anyone (0.0.0.0)
mongo-express_1  | basicAuth credentials are "admin:pass", it is recommended you change this in your config.js!
mongo-express_1  |
mongo-express_1  | /node_modules/mongodb/lib/server.js:265
mongo-express_1  |         process.nextTick(function() { throw err; })
mongo-express_1  |                                       ^
mongo-express_1  | MongoError: failed to connect to server [mongo:27017] on first connect
mongo-express_1  |     at Pool.<anonymous> (/node_modules/mongodb-core/lib/topologies/server.js:326:35)
mongo-express_1  |     at emitOne (events.js:116:13)
mongo-express_1  |     at Pool.emit (events.js:211:7)
mongo-express_1  |     at Connection.<anonymous> (/node_modules/mongodb-core/lib/connection/pool.js:270:12)
mongo-express_1  |     at Object.onceWrapper (events.js:317:30)
mongo-express_1  |     at emitTwo (events.js:126:13)
mongo-express_1  |     at Connection.emit (events.js:214:7)
mongo-express_1  |     at Socket.<anonymous> (/node_modules/mongodb-core/lib/connection/connection.js:175:49)
mongo-express_1  |     at Object.onceWrapper (events.js:315:30)
mongo-express_1  |     at emitOne (events.js:116:13)

I have searched this issue all over the internet and github repositories and tried the other solutions, but none of them worked appropriately.

link1 | link2 | link3 | link4 | etc.

Body:
First I have run docker stop $(docker ps -a -q) and then changed the docker-compose.yml file to the following content:

version: '2'
services:
  mongo:
    image: mongo:3.4
    container_name: mongo
    ports:
      - '27017:27017'
    volumes:
      - '/data/configdb:/data/configdb'
      - '/data/db:/data/db'
  mongo-express:
    image: mongo-express:0.49.0
    container_name: mongo_express
    depends_on:
      - 'mongo'
    ports:
      - '5050:8081'
    environment:
      - 'ME_CONFIG_OPTIONS_EDITORTHEME=ambiance'


问:
overloading constructors with friend classes
I have a class that uses either a static list (firstFriend in the example) or a dynamic list (secondFriend in the example) for initialization. The list functionality I didn't want to write for the example because it is not important. The key problem is that the firstFriend and the secondFriend are, well, friends. The code of the constructors of the class "target" is the same: if I overload the constructors I'm duplicating exactly the same code. I cannot template the constructors because it doesn't work.

Here's the example (NOTE: the firstFriend and secondFriend may look the same, but they are NOT the same in the ACTUAL code, this is just a heavily reduced model, the differences between their attributes and functionality does not make any differrence in the "target" class constructor because the parts of the public interface is used from both classes that are exactly the same):

```<code>template <class T>
class firstFriend
{
    public:
    firstFriend() {};

    firstFriend(const T& t) {};

    private:
    T tAttribute;
};

template <class T>
class secondFriend
{
    public:

    secondFriend() {};

    secondFriend(T t) : tAttribute(t) {};

    friend class firstFriend<T>;

    private:

        T tAttribute;
};

class target
{
    public:
    target(const firstFriend<int>&)
    {
        // Some nice initialization of the TargetData.
    }
    target(const secondFriend<int>&)
    {
        // Exactly the same initialization as above.
        // To the single character.
    };
    private:
    firstFriend<int> TargetData;
};
</code>```

Question: how do I overload constructors without writing (copy/paste-ing) the same code twice? I have tried templating the constructors, but it didn't work. Implicit cast maybe? What would be the most efficient way (the firstFriend and secondFriend are HUGE lists of data). Thanks in advance!

答:
If both constructors have exactly same code, then you can write a constructor template as:

```<code>template<class FriendType >
target(const FriendType &)
{
    // Some nice initialization of the TargetData.
}
</code>```

If there is a little difference, but most of the code is same, then you can write an init template function, and call it from both constructors as:

```<code>  target(const firstFriend<int>& arg)
  {
     init(arg);
     //other code
  }
  target(const secondFriend<int>& arg)
  {
     init(arg);
     //other code
  }
private:
  template<class FriendType >
  void init(const FriendType &)
  {
     //common code
  }
</code>```

Body:
I have a class that uses either a static list (firstFriend in the example) or a dynamic list (secondFriend in the example) for initialization. The list functionality I didn't want to write for the example because it is not important. The key problem is that the firstFriend and the secondFriend are, well, friends. The code of the constructors of the class "target" is the same: if I overload the constructors I'm duplicating exactly the same code. I cannot template the constructors because it doesn't work.

Here's the example (NOTE: the firstFriend and secondFriend may look the same, but they are NOT the same in the ACTUAL code, this is just a heavily reduced model, the differences between their attributes and functionality does not make any differrence in the "target" class constructor because the parts of the public interface is used from both classes that are exactly the same):

template <class T>
class firstFriend
{
    public:
    firstFriend() {};

    firstFriend(const T& t) {};

    private:
    T tAttribute;
};

template <class T>
class secondFriend
{
    public:

    secondFriend() {};

    secondFriend(T t) : tAttribute(t) {};

    friend class firstFriend<T>;

    private:

        T tAttribute;
};

class target
{
    public:
    target(const firstFriend<int>&)
    {
        // Some nice initialization of the TargetData.
    }
    target(const secondFriend<int>&)
    {
        // Exactly the same initialization as above.
        // To the single character.
    };
    private:
    firstFriend<int> TargetData;
};

Question: how do I overload constructors without writing (copy/paste-ing) the same code twice? I have tried templating the constructors, but it didn't work. Implicit cast maybe? What would be the most efficient way (the firstFriend and secondFriend are HUGE lists of data). Thanks in advance!

Body:
If both constructors have exactly same code, then you can write a constructor template as:

template<class FriendType >
target(const FriendType &)
{
    // Some nice initialization of the TargetData.
}

If there is a little difference, but most of the code is same, then you can write an init template function, and call it from both constructors as:

  target(const firstFriend<int>& arg)
  {
     init(arg);
     //other code
  }
  target(const secondFriend<int>& arg)
  {
     init(arg);
     //other code
  }
private:
  template<class FriendType >
  void init(const FriendType &)
  {
     //common code
  }


问:
Can any one explain me how the size get allocated in the following case?
I got confused with the size allocation with my gcc compiler, can any one help me how the size get allocated for the following code.

```<code>struct node
{
 int data;
 struct node *next;
};
</code>```

sizeof(struct node) it gives an output as 16.

```<code>struct node
{
 int data;
};
</code>```

sizeof(struct node) it gives an output as 4.

```<code>struct node
{
struct node *next;
};
</code>```

sizeof(struct node) it gives an output as 8.

```<code>struct node
{
int data;
struct node *next;
}*link;
</code>```

sizeof(link) is always 8, even if i add few more elements to structure.

答:
sizeof return size in bytes

int have 32 bits = 4 bytes

Any pointer char*, struct any* has const sizeof depends memory structure, in your case is 8.

Because of memory alligment your first example has sizeof = 16, more here: https://en.wikipedia.org/wiki/Data_structure_alignment , you can add #pragma pack(1) and see diffrents, should be 4 + 8 = 12

Body:
I got confused with the size allocation with my gcc compiler, can any one help me how the size get allocated for the following code.

struct node
{
 int data;
 struct node *next;
};

sizeof(struct node) it gives an output as 16.

struct node
{
 int data;
};

sizeof(struct node) it gives an output as 4.

struct node
{
struct node *next;
};

sizeof(struct node) it gives an output as 8.

struct node
{
int data;
struct node *next;
}*link;

sizeof(link) is always 8, even if i add few more elements to structure.


问:
Delegate methods in child class sometimes not called with Swift 5 compiler
EDIT: As sunshinejr pointed out here, this has been fixed and will be released together with the next Xcode/Swift version.

I've seen a lot of weird behaviour after updating Xcode 10.1 to Xcode 10.2, both with Swift 4 and Swift 5 codebases.

One of the problems is that on one ViewController the ScrollView delegate methods are no longer called. The simplified view hierarchy is as follows:

```<code>| ScrollView (ParentScrollView)
| -- Stack View
| ---- ScrollView (ChildScrollView)
| ---- ScrollView (ChildScrollView)
| ---- ScrollView (ChildScrollView)
</code>```

It acts as a view with several pages: ParentScrollView can be scrolled horizontally, the ChildScrollViews vertically.

The ViewController is the delegate of all Scrollviews (set in Storyboard), but the delegate methods (like scrollViewDidEndDecelerating) are not called when scrolling any of the views (ParentScrollView or ChildScrollView). The base class of ViewController conforms to UIScrollViewDelegate.

I have tried setting the delegates in code, other than that I have no idea what I could be doing wrong. The conversion did not change any code in the class, but everything worked well before updating. I also couldn't find any changes to gestures, delegates or ScrollViews in general in the Swift 5 Release Notes.

This seems to be a bug with the Swift 5 compiler. Additionally, sometimes it does work, sometimes it doesn't - all without changing any code or project settings.

Why does this no longer work? Has anyone else experienced similar behaviour?

答:
As Jan pointed out, this is a Swift 5 regression. This is tracked on Swift's JIRA as well as on radar (rdar://problem/49482328). This is also already fixed (PR here) but we need to wait for the next Xcode/Swift release.

Edit: As of Xcode 10.3, we observed that the bug is fixed, but we are still monitoring if it is fixed for good.

Body:
EDIT: As sunshinejr pointed out here, this has been fixed and will be released together with the next Xcode/Swift version.

I've seen a lot of weird behaviour after updating Xcode 10.1 to Xcode 10.2, both with Swift 4 and Swift 5 codebases.

One of the problems is that on one ViewController the ScrollView delegate methods are no longer called. The simplified view hierarchy is as follows:

| ScrollView (ParentScrollView)
| -- Stack View
| ---- ScrollView (ChildScrollView)
| ---- ScrollView (ChildScrollView)
| ---- ScrollView (ChildScrollView)

It acts as a view with several pages: ParentScrollView can be scrolled horizontally, the ChildScrollViews vertically.

The ViewController is the delegate of all Scrollviews (set in Storyboard), but the delegate methods (like scrollViewDidEndDecelerating) are not called when scrolling any of the views (ParentScrollView or ChildScrollView). The base class of ViewController conforms to UIScrollViewDelegate.

I have tried setting the delegates in code, other than that I have no idea what I could be doing wrong. The conversion did not change any code in the class, but everything worked well before updating. I also couldn't find any changes to gestures, delegates or ScrollViews in general in the Swift 5 Release Notes.

This seems to be a bug with the Swift 5 compiler. Additionally, sometimes it does work, sometimes it doesn't - all without changing any code or project settings.

Why does this no longer work? Has anyone else experienced similar behaviour?


问:
Xamarin.Forms Missing 120x120 While Uploading To Asset Store
Using Visual Studio Community 2019 for Mac and trying to build my Xamarin Forms app for App Store,

Build and Runs pretty fine BUT, it gives me this error while i try to upload to App Store,

ERROR: ERROR ITMS-90022: "Missing required icon file. The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format for iOS versions >= 7.0."

I tried every single solution with this google search: Xamarin iOS ITMS-90022 site: forums.xamarin.com

I Tried naming all my Icons according to Apple Developer Docs here: developer.apple.com/library/archive/qa/qa1686/_index.html

But Visual Studio converts naming to AppIcon-60x60@2x.png when i check the resulting ipa file.

Can someone please point me to right direction because honestly, it is driving me mad.

Thank you.

I Tried all things here: Xamarin iOS ITMS-90022 site:forums.xamarin.com
Here: Xamarin iOS ITMS-90022 site:stackoverflow.com

Expected: Upload without a problem.
Result: ERROR ITMS-90022: "Missing required icon file. The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format for iOS versions >= 7.0."

答:
you should check the info.plist. </p>

```<code><key>CFBundleIconFiles</key>
<array>
    <string>AppIcon-120.png</string>
</array>
</code>```

Body:
you should check the info.plist.

<key>CFBundleIconFiles</key>
<array>
    <string>AppIcon-120.png</string>
</array>


问:
Copying data from multiple columns of source hive table to single column of target hive table in different rows
I have a requirement of copying data from one Hive source table to other target table. Below is source table structure with sample data:

```<code>source_table
Userid  Name    Phone1   Phone2  Phone3  Address1   Address2    Address3
123     Jitu    123456   987654  111111  DELHI      GURGAON     NOIDA
234     Mark    123456   987654  111111  UK         USA         IND
</code>```

While copying data from source to target, my requirement is to have Phone1, Phone2, Phone3 along with corresponding Address1, Address2 and Address3
columns in a single column in target table. Below is how data should look like in target table:

```<code>Target_table
Userid  Name    Phone_no    Address
123     Jitu    123456      DELHI
123     Jitu    987654      GURGAON
123     Jitu    111111      NOIDA
234     Mark    123456      UK
234     Mark    987654      USA
234     Mark    111111      IND
</code>```

I know simplest way to do this would be doing multiple inserts into target table for each Phone and address column from source table
using either hive query language or spark dataframes.

Is there any other efficient method I can use to achieve this.

答:
Original dataframe can be selected several times, for each column index, and then selected dataframes combined into one by "union":

```<code>val df = Seq(
  (123, "Jitu", "123456", "987654", "111111", "DELHI", "GURGAON", "NOIDA"),
  (234, "Mark", "123456", "987654", "111111", "UK", "USA", "IND")
).toDF(
  "Userid", "Name", "Phone1", "Phone2", "Phone3", "Address1", "Address2", "Address3"
)

val columnIndexes = Seq(1, 2, 3)
val onlyOneIndexDfs = columnIndexes.map(idx =>
  df.select(
    $"Userid",
    $"Name",
    col(s"Phone$idx").alias("Phone_no"),
    col(s"Address$idx").alias("Address")))

val result = onlyOneIndexDfs.reduce(_ union _)
</code>```

Output:

```<code>+------+----+--------+-------+
|Userid|Name|Phone_no|Address|
+------+----+--------+-------+
|123   |Jitu|123456  |DELHI  |
|123   |Jitu|111111  |NOIDA  |
|123   |Jitu|987654  |GURGAON|
|234   |Mark|123456  |UK     |
|234   |Mark|987654  |USA    |
|234   |Mark|111111  |IND    |
+------+----+--------+-------+
</code>```

Body:
I have a requirement of copying data from one Hive source table to other target table. Below is source table structure with sample data:

source_table
Userid  Name    Phone1   Phone2  Phone3  Address1   Address2    Address3
123     Jitu    123456   987654  111111  DELHI      GURGAON     NOIDA
234     Mark    123456   987654  111111  UK         USA         IND

While copying data from source to target, my requirement is to have Phone1, Phone2, Phone3 along with corresponding Address1, Address2 and Address3
columns in a single column in target table. Below is how data should look like in target table:

Target_table
Userid  Name    Phone_no    Address
123     Jitu    123456      DELHI
123     Jitu    987654      GURGAON
123     Jitu    111111      NOIDA
234     Mark    123456      UK
234     Mark    987654      USA
234     Mark    111111      IND

I know simplest way to do this would be doing multiple inserts into target table for each Phone and address column from source table
using either hive query language or spark dataframes.

Is there any other efficient method I can use to achieve this.

Body:
Original dataframe can be selected several times, for each column index, and then selected dataframes combined into one by "union":

val df = Seq(
  (123, "Jitu", "123456", "987654", "111111", "DELHI", "GURGAON", "NOIDA"),
  (234, "Mark", "123456", "987654", "111111", "UK", "USA", "IND")
).toDF(
  "Userid", "Name", "Phone1", "Phone2", "Phone3", "Address1", "Address2", "Address3"
)

val columnIndexes = Seq(1, 2, 3)
val onlyOneIndexDfs = columnIndexes.map(idx =>
  df.select(
    $"Userid",
    $"Name",
    col(s"Phone$idx").alias("Phone_no"),
    col(s"Address$idx").alias("Address")))

val result = onlyOneIndexDfs.reduce(_ union _)

Output:

+------+----+--------+-------+
|Userid|Name|Phone_no|Address|
+------+----+--------+-------+
|123   |Jitu|123456  |DELHI  |
|123   |Jitu|111111  |NOIDA  |
|123   |Jitu|987654  |GURGAON|
|234   |Mark|123456  |UK     |
|234   |Mark|987654  |USA    |
|234   |Mark|111111  |IND    |
+------+----+--------+-------+


问:
How to set a timeout for a popup?
I created a popup that appears when I click a button, but to make it disappear I have to click again.
Is there a way to set a timer and make it disappear?

This is the code:

// When the user clicks on div, open the popup
function myFunction() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.popuptext {
  display: none;
}
.popuptext.show {
  display: block;
}</code>```

Click me to toggle the popup!
  A Simple Popup!

```

答:
I would use setTimeout:

function myFunction(el) {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
  setTimeout(() => {
    popup.classList.remove("show");
  }, 10000)
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  display: none;
}

.show {
  display: block !important;
}</code>```

<button onclick="myFunction()">Show div below</button>

No longer hidden
```

Title: How to set a timeout for a popup?

Body:
I created a popup that appears when I click a button, but to make it disappear I have to click again.
Is there a way to set a timer and make it disappear?

This is the code:

// When the user clicks on div, open the popup
function myFunction() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
}

.popuptext {
  display: none;
}
.popuptext.show {
  display: block;
}

Click me to toggle the popup!
  A Simple Popup!

Body:
I would use setTimeout:

function myFunction(el) {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
  setTimeout(() => {
    popup.classList.remove("show");
  }, 10000)
}

div {
  display: none;
}

.show {
  display: block !important;
}

<button onclick="myFunction()">Show div below</button>
<br/>
<div id="myPopup">No longer hidden</div>


问:
dyld: Library not loaded; llbuild image not found
I used swift package init --type executable.

I have already tried setting xcode command line tools on path.

Following error occurs:

dyld: Library not loaded: @rpath/llbuild.framework/Versions/A/llbuild
  Referenced from:
  /Library/Developer/CommandLineTools/usr/bin/swift-package   Reason:
  image not found

答:
I have faced the similar issue.
Basically the framework or library is not properly linked in the project.

If you are doing drag and drop of framework in xcode project then you will have to link it in embed frameworks as well.
(Basically you will have to drag and drop the framework in embed frameworks section)

See the below image.


问:
How to reload the components in Vaadin after click internationalization Button?
I use Internationalization I18N in Vaadin. I have a Internationalization class with the method getText.

```<code>public static String getText(String key) {
        String returnValue = "";
        String value = "";
        String space = " ";
        Locale locale = new Locale("de", "DE");
        try {
            // session specific locale stored in attribute "locale"
            // if you want add a new language then add a new else if with the
            // new Locale like ("fr", "FR").
            if (VaadinServletService.getCurrentRequest() != null) {
                if ((Locale) VaadinServletService.getCurrentServletRequest().getSession().getAttribute("locale") != null) {
                    if (VaadinServletService.getCurrentServletRequest().getSession().getAttribute("locale").toString().equals("en_EN")) {
                        locale = new Locale("en", "US");
                    } else if (VaadinServletService.getCurrentServletRequest().getSession().getAttribute("locale").toString().equals("de_DE")) {
                        locale = new Locale("de", "DE");
                    }
                }
            }
            ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale);
            value = bundle.getString(key);
            returnValue = new String(value.getBytes("ISO-8859-1"), "UTF-8");
        } catch (MissingResourceException e) {
            // Missing key
            try {
                // return the Key
                String keyString = key.replace("_", space);
                returnValue = new String(keyString.getBytes("ISO-8859-1"), "UTF-8");
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return returnValue + space;
    }
</code>```

I can call this Method from everywhere to use this getText() method.
My Components they get a internationalization text by call this method like this:
label.setCaption(Internationalization.getText("Willkommen"));

I have now two Buttons "DE" and "EN" for the languages german and english. In the ClickListener of this Buttons i set the new Locale like this:

```<code>    btnLanguageDE.addClickListener(e -> {
VaadinServletService.getCurrentServletRequest().getSession().setAttribute("locale", new Locale("de", "DE"));
        });
</code>```

```<code>btnLanguageEN.addClickListener(e -> {
VaadinServletService.getCurrentServletRequest().getSession().setAttribute("locale", new Locale("en", "EN"));
logger.debug("Internationalization change to: EN");
        });
</code>```

The Problem is, if i click on the Button they set the local but didn't reload the components on the page. It changes only if i reload the page manually.
I tried to call this UI.getCurrent().getPage().getLocation(); but no effects.

How can i reload the components with the actual locale ?

答:
you should have a look at the I18N Tutorials. You can find them here: Vaadin Tutorials - I18N

Cheers Sven

Body:
I use Internationalization I18N in Vaadin. I have a Internationalization class with the method getText.

public static String getText(String key) {
        String returnValue = "";
        String value = "";
        String space = " ";
        Locale locale = new Locale("de", "DE");
        try {
            // session specific locale stored in attribute "locale"
            // if you want add a new language then add a new else if with the
            // new Locale like ("fr", "FR").
            if (VaadinServletService.getCurrentRequest() != null) {
                if ((Locale) VaadinServletService.getCurrentServletRequest().getSession().getAttribute("locale") != null) {
                    if (VaadinServletService.getCurrentServletRequest().getSession().getAttribute("locale").toString().equals("en_EN")) {
                        locale = new Locale("en", "US");
                    } else if (VaadinServletService.getCurrentServletRequest().getSession().getAttribute("locale").toString().equals("de_DE")) {
                        locale = new Locale("de", "DE");
                    }
                }
            }
            ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale);
            value = bundle.getString(key);
            returnValue = new String(value.getBytes("ISO-8859-1"), "UTF-8");
        } catch (MissingResourceException e) {
            // Missing key
            try {
                // return the Key
                String keyString = key.replace("_", space);
                returnValue = new String(keyString.getBytes("ISO-8859-1"), "UTF-8");
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return returnValue + space;
    }

I can call this Method from everywhere to use this getText() method.
My Components they get a internationalization text by call this method like this:
label.setCaption(Internationalization.getText("Willkommen"));

I have now two Buttons "DE" and "EN" for the languages german and english. In the ClickListener of this Buttons i set the new Locale like this:

    btnLanguageDE.addClickListener(e -> {
VaadinServletService.getCurrentServletRequest().getSession().setAttribute("locale", new Locale("de", "DE"));
        });

btnLanguageEN.addClickListener(e -> {
VaadinServletService.getCurrentServletRequest().getSession().setAttribute("locale", new Locale("en", "EN"));
logger.debug("Internationalization change to: EN");
        });

The Problem is, if i click on the Button they set the local but didn't reload the components on the page. It changes only if i reload the page manually.
I tried to call this UI.getCurrent().getPage().getLocation(); but no effects.

How can i reload the components with the actual locale ?


Title: How to set a timeout for a popup?

Body:
<script>
// When the user clicks on div, open the popup
function myFunction() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");

  //Try this, setTimeout takes a callback function to be executed after an amount of time, in this case 3000 milliseconds is 3 seconds
  setTimeout(function(){
    popup.classList.toggle("show");
  },3000)
}
</script>


问:
Arithmetic Bit Shift of Double Variable Data Type in C
I am trying to arithmetic bit shift a double data type in C.  I was wondering if this is the correct way to do it:

NOTE: firdelay[ ][ ] is declared in main as
    double firdelay[8][12]

```<code>void function1(double firdelay[][12]) {
    int * shiftptr;

    // Cast address of element of 2D matrix (type double) to integer pointer
    *shiftptr = (int *) (&firdelay[0][5]);

    // Dereference integer pointer and shift right by 12 bits
    *shiftptr >>= 12;
}
</code>```

答:
There's a way to achieve this : just add your n to the exponent part of the bitwise representation of the double.
Convert your double to long using "reinterpret" or bitwise conversion (using a union for instance).. extract bits from 52 to 63 (11 bits).. then add your shift and put back the result in the exponent.
You should take into account the special values of double (+infinity, nan or zero)

```<code>double operator_shift_left(double a,int n)
{
    union
    {
        long long l;
        double d;
    } r;
    r.d=a;
    switch(r.l)
    {
        case 0x0000000000000000: // 0
        case 0x8000000000000000: // -0
        case 0x7FF0000000000000: // pos infnity
        case 0xFFF0000000000000: // neg infnity
        case 0x7FF0000000000001: // Nan
        case 0x7FF8000000000001: // Nan
        case 0x7FFFFFFFFFFFFFFF: // Nan
            return a;
    }
    int nexp=(((r.l>>52)&0x7FF)+n); // new exponent
    if (nexp<0) // underflow
    {
        r.l=r.l &  0x8000000000000000;
        // returns +/- 0
        return r.d;
    }
    if (nexp>2047) // overflow
    {
        r.l=(r.l & 0x8000000000000000)| 0x7FF0000000000000;
        // returns +/- infinity
        return r.d;
    }
    // returns the number with the new exponant

    r.l=(r.l & 0x800FFFFFFFFFFFFF)|(((long long)nexp)<<52);
    return r.d;

}
</code>```

(there's probably some x64 processor instruction that does it ?)

Body:
I am trying to arithmetic bit shift a double data type in C.  I was wondering if this is the correct way to do it:

NOTE: firdelay[ ][ ] is declared in main as
    double firdelay[8][12]

void function1(double firdelay[][12]) {
    int * shiftptr;

    // Cast address of element of 2D matrix (type double) to integer pointer
    *shiftptr = (int *) (&firdelay[0][5]);

    // Dereference integer pointer and shift right by 12 bits
    *shiftptr >>= 12;
}

Body:
There's a way to achieve this : just add your n to the exponent part of the bitwise representation of the double.
Convert your double to long using "reinterpret" or bitwise conversion (using a union for instance).. extract bits from 52 to 63 (11 bits).. then add your shift and put back the result in the exponent.
You should take into account the special values of double (+infinity, nan or zero)

double operator_shift_left(double a,int n)
{
    union
    {
        long long l;
        double d;
    } r;
    r.d=a;
    switch(r.l)
    {
        case 0x0000000000000000: // 0
        case 0x8000000000000000: // -0
        case 0x7FF0000000000000: // pos infnity
        case 0xFFF0000000000000: // neg infnity
        case 0x7FF0000000000001: // Nan
        case 0x7FF8000000000001: // Nan
        case 0x7FFFFFFFFFFFFFFF: // Nan
            return a;
    }
    int nexp=(((r.l>>52)&0x7FF)+n); // new exponent
    if (nexp<0) // underflow
    {
        r.l=r.l &  0x8000000000000000;
        // returns +/- 0
        return r.d;
    }
    if (nexp>2047) // overflow
    {
        r.l=(r.l & 0x8000000000000000)| 0x7FF0000000000000;
        // returns +/- infinity
        return r.d;
    }
    // returns the number with the new exponant

    r.l=(r.l & 0x800FFFFFFFFFFFFF)|(((long long)nexp)<<52);
    return r.d;

}

(there's probably some x64 processor instruction that does it ?)


问:
linux find regex
I'm having trouble using the regex of the find command. Probably something I don't understand about escaping on the command line.

Why are these not the same?

```<code>find -regex '.*[1234567890]'
find -regex '.*[[:digit:]]'
</code>```

Bash, Ubuntu

答:
Note that -regex depends on whole path.

```<code> -regex pattern
              File name matches regular expression pattern.
              This is a match on the whole path, not a search.
</code>```

You don't actually have to use -regex for what you are doing.

```<code>find . -iname "*[0-9]"
</code>```

Title: linux find regex

Body:
I'm having trouble using the regex of the find command. Probably something I don't understand about escaping on the command line.

Why are these not the same?

find -regex '.*[1234567890]'
find -regex '.*[[:digit:]]'

Bash, Ubuntu

Body:
Note that -regex depends on whole path.

 -regex pattern
              File name matches regular expression pattern.
              This is a match on the whole path, not a search.

You don't actually have to use -regex for what you are doing.

find . -iname "*[0-9]"


问:
Maven local repository location for Linux and Windows
I have a dual boot system with Windows and Linux. I have another partition which is visible to both Windows and Linux. I want to put my local repository there. How can I provide a path that both Linux and Windows will understand. Windows see it as d:/repository drive and Linux sees it as /media/234242342/repository. How should I configure this in pom.xml?

答:
You can run  : </p>

```<code>mvn help:evaluate -Dexpression=settings.localRepository
</code>```

<p>source </p>

Body:
You can run  :

mvn help:evaluate -Dexpression=settings.localRepository

source


问:
How can I delete user default from the app?
I have created login page. when I enter email and password returns from Json the user  ID  and then, I have saved the ID in user default to be able to use it in different pages in my app, but when I added logout button in another page.  the function of the logout button is when I press it delete id from user default and then take me to the root uiviewcontroller but when I logout and login with another account steal saving the old ID. </p>

```<code>//save id to the user default by using login button
let id = UserDefaults.standard
id.set(data.id , forKey : "ID")
id.synchronize

//using user id with this code in diferent pages
let user_id = UserDefaults.standard.integer(forKey : "ID")

//delete id from user default by using logout button
UserDefaults.standard.removeObject(forKey : "ID")
userDefaults.synchronize
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let mainScreen = UIStoryboard.init(name : "Main" , bundle : nil).instantiateViewController(withIdentifier :"BG")
appDelegate.window?.rootViewController =   mainScreen
</code>```

答:
We have two options one is set empty or any other value corresponding key, otherwise you need delete all user default value means use "removePersistentDomain" key.Example

let appDomain = Bundle.main.bundleIdentifier! UserDefaults.standard.removePersistentDomain(forName: appDomain)

Body:
I have created login page. when I enter email and password returns from Json the user  ID  and then, I have saved the ID in user default to be able to use it in different pages in my app, but when I added logout button in another page.  the function of the logout button is when I press it delete id from user default and then take me to the root uiviewcontroller but when I logout and login with another account steal saving the old ID.

//save id to the user default by using login button
let id = UserDefaults.standard
id.set(data.id , forKey : "ID")
id.synchronize

//using user id with this code in diferent pages
let user_id = UserDefaults.standard.integer(forKey : "ID")

//delete id from user default by using logout button
UserDefaults.standard.removeObject(forKey : "ID")
userDefaults.synchronize
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let mainScreen = UIStoryboard.init(name : "Main" , bundle : nil).instantiateViewController(withIdentifier :"BG")
appDelegate.window?.rootViewController =   mainScreen


问:
python function os.path.exists() retrun True when I give a bool value
I want junge a str wheather file path or not, so i use os.path.exists(), but i put a worry parameter, like this: os.path.exists(False).
then the function return True to me, why?

python3.7,centos 7

```<code>import os
print(os.path.exists(True))
print(os.path.exists(False))
print(os.path.exists(1))

>>>True
>>>True
>>>True
</code>```

I expect the output of False, cause True,False,1is not path name

答:
from the os.path.exists doc:

Changed in version 3.3: path can now be an integer: True is returned
  if it is an open file descriptor, False otherwise.

so it seems you have an open file descriptor for 0 (i.e. False) and 1 (i.e. True).

Body:
I want junge a str wheather file path or not, so i use os.path.exists(), but i put a worry parameter, like this: os.path.exists(False).
then the function return True to me, why?

python3.7,centos 7

import os
print(os.path.exists(True))
print(os.path.exists(False))
print(os.path.exists(1))

>>>True
>>>True
>>>True

I expect the output of False, cause True,False,1is not path name


问:
How to send the element object as parameter to javascript function without ID
In function ClickedRow, i want to use the "a" which is being clicked. So i want to receive it as a parameter.

```<code><td ...... >
<span class="......>
  <span onmousedown="event.cancelBubble = true">
      <a class="GridLinkRenderer" href="javascript:ClickedRow(this)"  onclicklink="javascript:ClickedRow(this)" urlText="XXXX">

<td ......
<span class="......>
  <span onmousedown="event.cancelBubble = true">
      <a class="GridLinkRenderer" href="javascript:ClickedRow(this)"  onclicklink="javascript:ClickedRow(this)" urlText="XXXXX">
</code>```

Based on clicked ....> I would like to hide/show it (or to show/hide next class= "GridLinkRenderer" in other )   by function ClickedRow(this).
How can I do it ?

I've tried to send the clicked $(row).next().eq(0).tagName and row.style.display = 'none' , it says that it is "undefined".

```<code>function ClickedRow(row){

$(row).next().eq(0).hide();
$(row).hide();

}
</code>```

答:
Instead of this, remove href and use </p>

```<code>$('#TheidOfTheA').on('click'function(){
let myAElement = $(this);
}
</code>```

Body:
In function ClickedRow, i want to use the "a" which is being clicked. So i want to receive it as a parameter.

<td ......

Based on clicked  I would like to hide/show it (or to show/hide next <a class= "GridLinkRenderer" in other )   by function ClickedRow(this).
How can I do it ?

I've tried to send the clicked $(row).next().eq(0).tagName and row.style.display = 'none' , it says that it is "undefined".

function ClickedRow(row){

$(row).next().eq(0).hide();
$(row).hide();

}

Body:
Instead of this, remove href and use

$('#TheidOfTheA').on('click'function(){
let myAElement = $(this);
}


问:
What kind of axis is git variable?
My build.sbt file looks as the following:

```<code>//Git settings
git.useGitDescribe := true
git.formattedShaVersion := git.gitHeadCommit.value map { _ =>
  git.gitCurrentTags.value.head
}

Docker / dockerAlias := DockerAlias(None, Some("zerocoder"), (packageName in Docker).value, git.gitDescribedVersion.value)

lazy val root = (project in file("."))
  .enablePlugins(DockerPlugin, JavaServerAppPackaging, GitVersioning)
  .settings(
    name := "plugger",
    libraryDependencies ++= Seq(
      "org.typelevel" %% "cats-core" % "1.6.0",
      "ch.qos.logback" % "logback-classic" % "1.2.3",
      "com.typesafe.scala-logging" %% "scala-logging" % "3.9.2",
      "com.typesafe.akka" %% "akka-slf4j" % "2.5.22",
      "io.circe" %% "circe-core" % "0.11.1",
      "io.circe" %% "circe-generic" % "0.11.1",
      "io.circe" %% "circe-parser" % "0.11.1",
      "org.scala-lang" % "scala-library" % "2.12.8",
      "com.typesafe.akka" %% "akka-actor" % "2.5.22",
      "com.typesafe.akka" %% "akka-stream" % "2.5.22",
      "com.typesafe.akka" %% "akka-http" % "10.1.8",
      "com.typesafe.akka" %% "akka-stream-kafka" % "1.0.1",
      "org.scalacheck" %% "scalacheck" % "1.14.0" % "test",
      "org.scalactic" %% "scalactic" % "3.0.6" % "test",
      "org.scalatest" %% "scalatest" % "3.0.6" % "test",
      "com.dimafeng" %% "testcontainers-scala" % "0.25.0" % "test"
    ),
    addCompilerPlugin("org.spire-math" %% "kind-projector" % "0.9.3"),
    scalacOptions ++= Seq(
      "-encoding", "UTF-8", // source files are in UTF-8
      "-deprecation", // warn about use of deprecated APIs
      "-unchecked", // warn about unchecked type parameters
      "-feature", // warn about misused language features
      "-language:higherKinds", // allow higher kinded types without `import scala.language.higherKinds`
      "-Xlint", // enable handy linter warnings
      "-Xfatal-warnings", // turn compiler warnings into errors
      "-Ypartial-unification" // allow the compiler to unify type constructors of different arities
    ),
    scalacOptions in(Compile, console) ~= {
      _.filterNot(Set("-Xlint"))
    }

  )
</code>```

As you can see, I am using GitVersioning plugin and what kind of axis scope is git variable?

Docker is a scope and the dockerAlias in the scope, that because I can write Docker / dockerAlias.

I also tried to write git / useGitDescribe but it does not work.

答:
git isn't in any of sbt's scope axes.  It's just an object that holds keys: https://github.com/sbt/sbt-git/blob/v1.0.0/src/main/scala/com/typesafe/sbt/SbtGit.scala#L212

It also, as you can see, re-scopes the majority of the keys in the ThisBuild reference scope axis.  I've only ever seen sbt-git do this, but the effect is that if you use git.baseVersion within a project's settings (i.e. .settings(..)) then it will stay defined at build-level rather than at project-level.

Title: What kind of axis is git variable?

Body:
My build.sbt file looks as the following:

//Git settings
git.useGitDescribe := true
git.formattedShaVersion := git.gitHeadCommit.value map { _ =>
  git.gitCurrentTags.value.head
}

Docker / dockerAlias := DockerAlias(None, Some("zerocoder"), (packageName in Docker).value, git.gitDescribedVersion.value)

lazy val root = (project in file("."))
  .enablePlugins(DockerPlugin, JavaServerAppPackaging, GitVersioning)
  .settings(
    name := "plugger",
    libraryDependencies ++= Seq(
      "org.typelevel" %% "cats-core" % "1.6.0",
      "ch.qos.logback" % "logback-classic" % "1.2.3",
      "com.typesafe.scala-logging" %% "scala-logging" % "3.9.2",
      "com.typesafe.akka" %% "akka-slf4j" % "2.5.22",
      "io.circe" %% "circe-core" % "0.11.1",
      "io.circe" %% "circe-generic" % "0.11.1",
      "io.circe" %% "circe-parser" % "0.11.1",
      "org.scala-lang" % "scala-library" % "2.12.8",
      "com.typesafe.akka" %% "akka-actor" % "2.5.22",
      "com.typesafe.akka" %% "akka-stream" % "2.5.22",
      "com.typesafe.akka" %% "akka-http" % "10.1.8",
      "com.typesafe.akka" %% "akka-stream-kafka" % "1.0.1",
      "org.scalacheck" %% "scalacheck" % "1.14.0" % "test",
      "org.scalactic" %% "scalactic" % "3.0.6" % "test",
      "org.scalatest" %% "scalatest" % "3.0.6" % "test",
      "com.dimafeng" %% "testcontainers-scala" % "0.25.0" % "test"
    ),
    addCompilerPlugin("org.spire-math" %% "kind-projector" % "0.9.3"),
    scalacOptions ++= Seq(
      "-encoding", "UTF-8", // source files are in UTF-8
      "-deprecation", // warn about use of deprecated APIs
      "-unchecked", // warn about unchecked type parameters
      "-feature", // warn about misused language features
      "-language:higherKinds", // allow higher kinded types without `import scala.language.higherKinds`
      "-Xlint", // enable handy linter warnings
      "-Xfatal-warnings", // turn compiler warnings into errors
      "-Ypartial-unification" // allow the compiler to unify type constructors of different arities
    ),
    scalacOptions in(Compile, console) ~= {
      _.filterNot(Set("-Xlint"))
    }

  )

As you can see, I am using GitVersioning plugin and what kind of axis scope is git variable?

Docker is a scope and the dockerAlias in the scope, that because I can write Docker / dockerAlias.

I also tried to write git / useGitDescribe but it does not work.


问:
Need some help positioning a header and sub heading
heres my code: https://codepen.io/anon/pen/dEqJLr#anon-login
heres what I'm trying to do: https://imgur.com/a/NxvyHAC
basically I want the sub header ("helpthistext") to be above my header and I'm not sure how to achieve this..

body,
html {
  font-family: 'Montserrat';
  margin: 0;
  height: 100%;
}

body {
  background-color: red;
}

.newtest {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 75%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="newtest">
  <span class="sub-head">helpthistext</span>
  <h1 class="main-head">title one & another one</h1>
</div></code>```

答:
It probably makes sense to have the .sub-head appear beneath the .main-head in the markup, even if you want to visually display it above the main heading in the browser viewport.

To achieve this, apply display: flex to .newtest and then:

give .main-head an order of 2

give .sub-head an order of 1

Working Example:

.newtest {
display: flex;
flex-wrap: wrap;
}

.main-head {
order: 2;
width: 100%;
margin-top: 0;
}

.sub-head {
width: 100%;
order: 1;
font-size: 16px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="newtest">
<h1 class="main-head">title one & another one</h1>
<div class="sub-head">helpthistext</div>
</div></code>```

Body:
heres my code: https://codepen.io/anon/pen/dEqJLr#anon-login
heres what I'm trying to do: https://imgur.com/a/NxvyHAC
basically I want the sub header ("helpthistext") to be above my header and I'm not sure how to achieve this..

body,
html {
  font-family: 'Montserrat';
  margin: 0;
  height: 100%;
}

body {
  background-color: red;
}

.newtest {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 75%;
}

  helpthistext

title one & another one

Body:
It probably makes sense to have the .sub-head appear beneath the .main-head in the markup, even if you want to visually display it above the main heading in the browser viewport.

To achieve this, apply display: flex to .newtest and then:

give .main-head an order of 2

give .sub-head an order of 1

Working Example:

.newtest {
display: flex;
flex-wrap: wrap;
}

.main-head {
order: 2;
width: 100%;
margin-top: 0;
}

.sub-head {
width: 100%;
order: 1;
font-size: 16px;
}

<div class="newtest">
<h1 class="main-head">title one &amp; another one</h1>
<div class="sub-head">helpthistext</div>
</div>


问:
Use i18n tag for translating
I have an issue with my new Vuejs project, I use vuei18n in the same way like an other project of my company, but in the new project the  tag doesn't work.
When I disable silentTranslationWarn in i18n/index.js I have this messages :

[vue-i18n] Value of key 'pages' is not a string!
[vue-i18n] Cannot translate the value of keypath 'pages'. Use the value of keypath as default

When I put my translations in i18n/fr.js like this, my translation works :

```<code>const messages = {
  pages: 'Pages',
};
</code>```

But when I want to use  tag in the component, like in the old project I have the vue-i18n warns desribed before.
I have searched in the old project all occurencies of "i18n", "local", "messages" etc... but I have exactly the same occurency in the new project, in my package.json I have same version of vue-i18n

Did I missed something ?

答:
@kalidou.diagne :

In my i18n/index.js :

```<code>import Vue from 'vue';
import VueI18n from 'vue-i18n';

import en from './en';
import fr from './fr';

Vue.use(VueI18n);
const messages = { en, fr };

export default new VueI18n({
  locale: 'fr',
  silentTranslationWarn: true,
  messages,
});
</code>```

In my main.js :

```<code>import i18n from './i18n';

...

const Mdm = Vue.component('app', App);

/* eslint-disable no-new */
new Mdm({
  el: '#app',
  i18n,
  router,
  store,
  components: { App },
  template: '<App/>',
});
</code>```

Title: Use i18n tag for translating

Body:
I have an issue with my new Vuejs project, I use vuei18n in the same way like an other project of my company, but in the new project the  tag doesn't work.
When I disable silentTranslationWarn in i18n/index.js I have this messages :

[vue-i18n] Value of key 'pages' is not a string!
[vue-i18n] Cannot translate the value of keypath 'pages'. Use the value of keypath as default

When I put my translations in i18n/fr.js like this, my translation works :

const messages = {
  pages: 'Pages',
};

But when I want to use  tag in the component, like in the old project I have the vue-i18n warns desribed before.
I have searched in the old project all occurencies of "i18n", "local", "messages" etc... but I have exactly the same occurency in the new project, in my package.json I have same version of vue-i18n

Did I missed something ?

Body:
@kalidou.diagne :

In my i18n/index.js :

import Vue from 'vue';
import VueI18n from 'vue-i18n';

import en from './en';
import fr from './fr';

Vue.use(VueI18n);
const messages = { en, fr };

export default new VueI18n({
  locale: 'fr',
  silentTranslationWarn: true,
  messages,
});

In my main.js :

import i18n from './i18n';

...

const Mdm = Vue.component('app', App);

/* eslint-disable no-new */
new Mdm({
  el: '#app',
  i18n,
  router,
  store,
  components: { App },
  template: '<App/>',
});


问:
What is the official Perl documentation on the web?
I found perldoc.pl with a high usability level being up-to-date to version 5.30.0.

Perl.org links to perldoc.perl.org which stops at version 5.26.1. But on the other hand, it links to Download (version 5.28.2) to Strawberry Perl (actually version 5.30.0) which I find very confusing.

I already know that Perl 6 is a completely different language. Is there maybe another language barrier after 5.26.*?

Background

Since I use it rarely, a program update is the starting point when I reenter Perl. And that's why I was interested in studying the delta documentation before installing, and this delta was hard to find.

答:
The site at perldoc.perl.org is the "official" one (you can tell as it's on the perl.org domain), but that site is run by someone outside of the Perl Foundation and it seems that they have been too busy to update the site recently. I believe that perldoc.pl is an alternative project that was set up when it was noticed that the older site was no longer being kept up to date.

Actually, you can always get the most up-to-date and official documents on CPAN.


问:
How to Embed and Bind JSON Data to HTML Template in Java Web Service
I am working on a Java PDF Generation micro service using spring boot. The pdf generation is meant to be a 2 stage process.

Templating - html template with some sort of expression language, which reads a json structure directly

HTML to PDF - this generates a pdf from the html produced in step 1

Note: I have some java and JavaScript (nunjucks/nodejs) solution for steps 1 and 2, but I really need a more maintainable approach as follows.

My restful endpoint will take 2 parameters an html template and a json

The json structure maps to the html template one to one and both files have been predefined to strict contract.

The service endpoint should not do any object mapping of json data to html Dom elements e.g. table, rows, etc

The endpoint only embeds the json data to the html using logic in java code

The html gets executed/rendered and reads the json directly using some sort of expression language, since it contains the json structure

The endpoint then response with an html with the dynamic data, which can be sent to the pdf generator web service endpoint

Below is a sample code:

```<code>@POST
 @Path("createPdf")
 public Response createPdf(String htmlTemplateParam, String json) {

 //Read template from endpoint param or start off with reading local html template from resource folder
String templateHtml = IOUtils.toString(getClass().getResourceAsStream(HTMLTemplateFiles.INCOMING_TEMPLATE));

RequestJson requestJson = [Prepare json before passing to HTML Template]];

if(requestJson.isContentValid()) {

    LOG.info("incoming data successfully validated");

    // TODO
    // Pass the requestJson (Endpoint Param JSON ) to templateHtml
    // Trigger the reading of the Json data and populating different HTML DOM elements using some sort of expression predefined in HTML

    // Get hold of the rendered HTML
    String resolvedHtml = [HTML with data from json param into endpoint];

    // The next bit is done
    String pdf = htmlToPdfaHandler.generatePdfFromHtml(resolvedHtml);

    javax.ws.rs.core.Response response = Response.ok().entity(Base64.decodeBase64(pdf)).build();
            }
}
</code>```

The templating stage one is where I need help.

Please, what is the best technical solution for this?

I am comfortable with Java and JavaScript framework and happy to learn any framework you suggest.

But, my main design goal is to ensure that as we have new templates and a template and data changes, a non-techie can change html/json and generate pdf.

Also, no java code changes should be required for template and data changes.

There are a few things in my head like jsonpath, thyme leaf, JavaScript, etc But, I love best practice and like to learn from someone with the real-life experience of similar use case.

After further research and first answer I am also thinking of the freemarker solution below.

But, how would I create a free marker template-data auto-magically from reading input json.i.e. without creating POJO/DTO?

Based on first answer :

```<code>     Configuration cfg = new Configuration(new Version("2.3.23"));
            cfg.setDefaultEncoding("UTF-8");

            // Loading you HTML template (via file or input stream):
            Template template = cfg.getTemplate("template.html");

  // Will this suffice for all JSON Structure, including nested deep ones

           Type mapType = new TypeToken<Map<String, Object>>(){}.getType();

    Map<String, String[]> templateData = new Gson().fromJson(json, mapType);

            try (StringWriter out = new StringWriter()) {
         // In output stream the result will be template with values from map:
                template.process(templateData, out);
                System.out.println(out.getBuffer().toString());

                out.flush();
            }
</code>```

Thanks in advance.

NOTE: Code snippets, pseudo code, references are welcomed.

答:
One of the options might be FreeMarker usage:</p>

```<code>    Configuration cfg = new Configuration(new Version("2.3.23"));
    cfg.setDefaultEncoding("UTF-8");

    // Loading you HTML template (via file or input stream):
    Template template = cfg.getTemplate("template.html");

    // You need convert json to map of parameters (key-value):
    Map<String, Object> templateData = new HashMap<>();
    templateData.put("msg", "Today is a beautiful day");

    try (StringWriter out = new StringWriter()) {
        // In output stream the result will be template with values from map:
        template.process(templateData, out);
        System.out.println(out.getBuffer().toString());

        out.flush();
    }
</code>```

Body:
I am working on a Java PDF Generation micro service using spring boot. The pdf generation is meant to be a 2 stage process.

Templating - html template with some sort of expression language, which reads a json structure directly

HTML to PDF - this generates a pdf from the html produced in step 1

Note: I have some java and JavaScript (nunjucks/nodejs) solution for steps 1 and 2, but I really need a more maintainable approach as follows.

My restful endpoint will take 2 parameters an html template and a json

The json structure maps to the html template one to one and both files have been predefined to strict contract.

The service endpoint should not do any object mapping of json data to html Dom elements e.g. table, rows, etc

The endpoint only embeds the json data to the html using logic in java code

The html gets executed/rendered and reads the json directly using some sort of expression language, since it contains the json structure

The endpoint then response with an html with the dynamic data, which can be sent to the pdf generator web service endpoint

Below is a sample code:

@POST
 @Path("createPdf")
 public Response createPdf(String htmlTemplateParam, String json) {

 //Read template from endpoint param or start off with reading local html template from resource folder
String templateHtml = IOUtils.toString(getClass().getResourceAsStream(HTMLTemplateFiles.INCOMING_TEMPLATE));

RequestJson requestJson = [Prepare json before passing to HTML Template]];

if(requestJson.isContentValid()) {

    LOG.info("incoming data successfully validated");

    // TODO
    // Pass the requestJson (Endpoint Param JSON ) to templateHtml
    // Trigger the reading of the Json data and populating different HTML DOM elements using some sort of expression predefined in HTML

    // Get hold of the rendered HTML
    String resolvedHtml = [HTML with data from json param into endpoint];

    // The next bit is done
    String pdf = htmlToPdfaHandler.generatePdfFromHtml(resolvedHtml);

    javax.ws.rs.core.Response response = Response.ok().entity(Base64.decodeBase64(pdf)).build();
            }
}

The templating stage one is where I need help.

Please, what is the best technical solution for this?

I am comfortable with Java and JavaScript framework and happy to learn any framework you suggest.

But, my main design goal is to ensure that as we have new templates and a template and data changes, a non-techie can change html/json and generate pdf.

Also, no java code changes should be required for template and data changes.

There are a few things in my head like jsonpath, thyme leaf, JavaScript, etc But, I love best practice and like to learn from someone with the real-life experience of similar use case.

After further research and first answer I am also thinking of the freemarker solution below.

But, how would I create a free marker template-data auto-magically from reading input json.i.e. without creating POJO/DTO?

Based on first answer :

     Configuration cfg = new Configuration(new Version("2.3.23"));
            cfg.setDefaultEncoding("UTF-8");

            // Loading you HTML template (via file or input stream):
            Template template = cfg.getTemplate("template.html");

  // Will this suffice for all JSON Structure, including nested deep ones

           Type mapType = new TypeToken<Map<String, Object>>(){}.getType();

    Map<String, String[]> templateData = new Gson().fromJson(json, mapType);

            try (StringWriter out = new StringWriter()) {
         // In output stream the result will be template with values from map:
                template.process(templateData, out);
                System.out.println(out.getBuffer().toString());

                out.flush();
            }

Thanks in advance.

NOTE: Code snippets, pseudo code, references are welcomed.

Body:
One of the options might be FreeMarker usage:

    Configuration cfg = new Configuration(new Version("2.3.23"));
    cfg.setDefaultEncoding("UTF-8");

    // Loading you HTML template (via file or input stream):
    Template template = cfg.getTemplate("template.html");

    // You need convert json to map of parameters (key-value):
    Map<String, Object> templateData = new HashMap<>();
    templateData.put("msg", "Today is a beautiful day");

    try (StringWriter out = new StringWriter()) {
        // In output stream the result will be template with values from map:
        template.process(templateData, out);
        System.out.println(out.getBuffer().toString());

        out.flush();
    }