问:
Error compiling app on emulator
I'm trying to install my app into the emulator to prove it but when I try to start the app this crash and doesn't let me open

I'm using CoordinarorLayout in the MainActivity:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="mx.com.dtss.carritocompras.MainActivity">

    <android.support.v7.app.AlertController.RecycleListView
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </android.support.v7.app.AlertController.RecycleListView>

</android.support.design.widget.CoordinatorLayout>
</code>```

and in other activity I use a CardView:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.FitWindowsLinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/img"/>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/txtDesPro"/>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/txtDetalle"/>
        </LinearLayout>
    </android.support.v7.widget.FitWindowsLinearLayout>

</android.support.v7.widget.CardView>
</code>```

this is what I've in my AndroidManifest:

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="mx.com.dtss.carritocompras" >

        <uses-permission android:name="android.permission.INTERNET"></uses-permission>

        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme" >
            <activity android:name=".MainActivity" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>

    </manifest>

and this is what I have in my `MainActivity`:

package mx.com.dtss.carritocompras;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    RecyclerView recycler;
    RecyclerView.Adapter adap;
    ArrayList<elemento> listaCard;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recycler = (RecyclerView)findViewById(R.id.recycler);
        recycler.setHasFixedSize(true);
        recycler.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

        Thread tr = new Thread(){
            @Override
            public void run(){
                String NAMESPACE = "http://tempuri.org/";
                String URL = "http://192.168.0.14/Publicacion/WebServiceCarrito.asmx";
                String METHOD_NAME = "listarProductos";
                String SOAP_ACTION = "http://tempuri.org/listarProductos";

                SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                envelope.dotNet= true;
                envelope.setOutputSoapObject(request);
                HttpTransportSE transporte = new HttpTransportSE(URL);

                try{
                    transporte.call(SOAP_ACTION, envelope);
                    final SoapObject soap = (SoapObject)envelope.getResponse();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            listarProductos(soap);
                        }
                    });
                } catch (Exception e){

                }
            }
        };
        tr.start();
    }

    public void listarProductos(SoapObject soap){
        listaCard = new ArrayList<elemento>();
            for(int i = 0; i < soap.getPropertyCount(); i++){
                SoapObject reg = (SoapObject)soap.getProperty(i);
                elemento e1 = new elemento(reg.getProperty(0).toString(), reg.getProperty(1).toString(),
                        reg.getProperty(2).toString(), Double.parseDouble(reg.getProperty(4).toString()),
                        reg.getProperty(5).toString());

                listaCard.add(e1);
        }

        adap = new Adaptador(listaCard, getApplication());
        recycler.setAdapter(adap);
    }
}
</code>```

And this is the error that throw me when I try to compile:

```<code>07-04 22:34:30.059 13691-13691/mx.com.dtss.carritocompras E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: mx.com.dtss.carritocompras, PID: 13691
                                                                            java.lang.RuntimeException: Unable to start activity ComponentInfo{mx.com.dtss.carritocompras/mx.com.dtss.carritocompras.MainActivity}: android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class android.support.v7.app.AlertController.RecycleListView
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2423)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:157)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5477)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                             Caused by: android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class android.support.v7.app.AlertController.RecycleListView
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
                                                                                at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                                                at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                                at mx.com.dtss.carritocompras.MainActivity.onCreate(MainActivity.java:24)
                                                                                at android.app.Activity.performCreate(Activity.java:6445)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:157)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5477)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                             Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class android.support.v7.app.AlertController.RecycleListView
                                                                                at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:776)
                                                                                at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
                                                                                at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
                                                                                at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
                                                                                at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                                                at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                                at mx.com.dtss.carritocompras.MainActivity.onCreate(MainActivity.java:24)
                                                                                at android.app.Activity.performCreate(Activity.java:6445)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:157)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5477)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                             Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.v7.app.AlertController.RecycleListView" on path: DexPathList[[zip file "/data/app/mx.com.dtss.carritocompras-1/base.apk", zip file "/data/app/mx.com.dtss.carritocompras-1/split_lib_dependencies_apk.apk", zip file "/data/app/mx.com.dtss.carritocompras-1/split_lib_slice_0_apk.apk", zip file "/data/app/mx.com.dtss.carritocompras-1/split_lib_slice_1_apk.apk", zip file "/data/app/mx.com.dtss.carritocompras-1/split_lib_slice_2_apk.apk", zip file "/data/app/mx.com.dtss.carritocompras-1/split_lib_slice_3_apk.apk", zip file "/data/app/mx.com.dtss.carritocompras-1/split_lib_slice_4_apk.apk", zip file "/data/app/mx.com.dtss.carritocompras-1/split_lib_slice_5_apk.apk", zip file "/data/app/mx.com.dtss.carritocompras-1/split_lib_slice_6_apk.apk", zip file "/data/app/mx.com.dtss.carritocompras-1/split_lib_slice_7_apk.apk", zip file "/data/app/mx.com.dtss.carritocompras-1/split_lib_slice_8_apk.apk", zip file "/data/app/mx.com.dtss.carritocompras-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/mx.com.dtss.carritocompras-1/lib/arm64, /vendor/lib64, /system/lib64]]
                                                                                at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                                                at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
                                                                                at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
                                                                                at android.view.LayoutInflater.createView(LayoutInflater.java:583)
                                                                                at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:764)
                                                                                at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
                                                                                at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
                                                                                at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
                                                                                at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                                                at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                                at mx.com.dtss.carritocompras.MainActivity.onCreate(MainActivity.java:24)
                                                                                at android.app.Activity.performCreate(Activity.java:6445)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:157)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5477)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                                Suppressed: java.lang.ClassNotFoundException: android.support.v7.app.AlertController.RecycleListView
                                                                                at java.lang.Class.classForName(Native Method)
</code>```

I hope someone can help me

答:
As the Logcat says that there is error on line 10 which is

```<code> <android.support.v7.app.AlertController.RecycleListView
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </android.support.v7.app.AlertController.RecycleListView>
</code>```

Instead of this use below

```<code>   <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        </android.support.v7.widget.RecyclerView>
</code>```

Title: Error compiling app on emulator

Body:
I'm trying to install my app into the emulator to prove it but when I try to start the app this crash and doesn't let me open

I'm using CoordinarorLayout in the MainActivity:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="mx.com.dtss.carritocompras.MainActivity">

    <android.support.v7.app.AlertController.RecycleListView
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </android.support.v7.app.AlertController.RecycleListView>

</android.support.design.widget.CoordinatorLayout>

and in other activity I use a CardView:

    <?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.FitWindowsLinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/img"/>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/txtDesPro"/>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/txtDetalle"/>
        </LinearLayout>
    </android.support.v7.widget.FitWindowsLinearLayout>

</android.support.v7.widget.CardView>

this is what I've in my AndroidManifest:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="mx.com.dtss.carritocompras" >

        <uses-permission android:name="android.permission.INTERNET"></uses-permission>

        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme" >
            <activity android:name=".MainActivity" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>

    </manifest>

and this is what I have in my `MainActivity`:

package mx.com.dtss.carritocompras;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    RecyclerView recycler;
    RecyclerView.Adapter adap;
    ArrayList<elemento> listaCard;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recycler = (RecyclerView)findViewById(R.id.recycler);
        recycler.setHasFixedSize(true);
        recycler.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

        Thread tr = new Thread(){
            @Override
            public void run(){
                String NAMESPACE = "http://tempuri.org/";
                String URL = "http://192.168.0.14/Publicacion/WebServiceCarrito.asmx";
                String METHOD_NAME = "listarProductos";
                String SOAP_ACTION = "http://tempuri.org/listarProductos";

                SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                envelope.dotNet= true;
                envelope.setOutputSoapObject(request);
                HttpTransportSE transporte = new HttpTransportSE(URL);

                try{
                    transporte.call(SOAP_ACTION, envelope);
                    final SoapObject soap = (SoapObject)envelope.getResponse();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            listarProductos(soap);
                        }
                    });
                } catch (Exception e){

                }
            }
        };
        tr.start();
    }

    public void listarProductos(SoapObject soap){
        listaCard = new ArrayList<elemento>();
            for(int i = 0; i < soap.getPropertyCount(); i++){
                SoapObject reg = (SoapObject)soap.getProperty(i);
                elemento e1 = new elemento(reg.getProperty(0).toString(), reg.getProperty(1).toString(),
                        reg.getProperty(2).toString(), Double.parseDouble(reg.getProperty(4).toString()),
                        reg.getProperty(5).toString());

                listaCard.add(e1);
        }

        adap = new Adaptador(listaCard, getApplication());
        recycler.setAdapter(adap);
    }
}

And this is the error that throw me when I try to compile:

07-04 22:34:30.059 13691-13691/mx.com.dtss.carritocompras E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: mx.com.dtss.carritocompras, PID: 13691
                                                                            java.lang.RuntimeException: Unable to start activity ComponentInfo{mx.com.dtss.carritocompras/mx.com.dtss.carritocompras.MainActivity}: android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class android.support.v7.app.AlertController.RecycleListView
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2423)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:157)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5477)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                             Caused by: android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class android.support.v7.app.AlertController.RecycleListView
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
                                                                                at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                                                at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                                at mx.com.dtss.carritocompras.MainActivity.onCreate(MainActivity.java:24)
                                                                                at android.app.Activity.performCreate(Activity.java:6445)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:157)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5477)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                             Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class android.support.v7.app.AlertController.RecycleListView
                                                                                at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:776)
                                                                                at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
                                                                                at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
                                                                                at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
                                                                                at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                                                at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                                at mx.com.dtss.carritocompras.MainActivity.onCreate(MainActivity.java:24)
                                                                                at android.app.Activity.performCreate(Activity.java:6445)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:157)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5477)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                             Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.v7.app.AlertController.RecycleListView" on path: DexPathList[[zip file "/data/app/mx.com.dtss.carritocompras-1/base.apk", zip file "/data/app/mx.com.dtss.carritocompras-1/split_lib_dependencies_apk.apk", zip file "/data/app/mx.com.dtss.carritocompras-1/split_lib_slice_0_apk.apk", zip file "/data/app/mx.com.dtss.carritocompras-1/split_lib_slice_1_apk.apk", zip file "/data/app/mx.com.dtss.carritocompras-1/split_lib_slice_2_apk.apk", zip file "/data/app/mx.com.dtss.carritocompras-1/split_lib_slice_3_apk.apk", zip file "/data/app/mx.com.dtss.carritocompras-1/split_lib_slice_4_apk.apk", zip file "/data/app/mx.com.dtss.carritocompras-1/split_lib_slice_5_apk.apk", zip file "/data/app/mx.com.dtss.carritocompras-1/split_lib_slice_6_apk.apk", zip file "/data/app/mx.com.dtss.carritocompras-1/split_lib_slice_7_apk.apk", zip file "/data/app/mx.com.dtss.carritocompras-1/split_lib_slice_8_apk.apk", zip file "/data/app/mx.com.dtss.carritocompras-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/mx.com.dtss.carritocompras-1/lib/arm64, /vendor/lib64, /system/lib64]]
                                                                                at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                                                at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
                                                                                at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
                                                                                at android.view.LayoutInflater.createView(LayoutInflater.java:583)
                                                                                at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:764)
                                                                                at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
                                                                                at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
                                                                                at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
                                                                                at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                                                at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                                at mx.com.dtss.carritocompras.MainActivity.onCreate(MainActivity.java:24)
                                                                                at android.app.Activity.performCreate(Activity.java:6445)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:157)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5477)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                                Suppressed: java.lang.ClassNotFoundException: android.support.v7.app.AlertController.RecycleListView
                                                                                at java.lang.Class.classForName(Native Method)

I hope someone can help me

Body:
As the Logcat says that there is error on line 10 which is

 <android.support.v7.app.AlertController.RecycleListView
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </android.support.v7.app.AlertController.RecycleListView>

Instead of this use below

   <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        </android.support.v7.widget.RecyclerView>


来源: stackexchange

问:
rstudio like repl for spark-shell
I am looking for an interactive way to work with the spark-shell that would resemble rstudio.
My use is simple - I want to write code in the editor and execute line-by-line in the terminal of spark shell.
I have tried Jupyter notebooks and Zeppelin, but they seem to not yet be as ready as the Python backends.
Currently I cut and paste every time, but that becomes tiring after a short while.
Google searches haven't come up with anything I found useful.

答:
You can use Jupyter notebook, But you need respective kernel to be installed and configured to Jupyter.

All available kernels for Jupyter

As you said spark-shell, I assume you are writing scala code.

Available kernels for scala are : sparkmagic and Jupyter-scala

As of now Jupyter will allow you to download the script as a file with .py extension

Changing its extension and compiling will be an overhead(even though it can reduce your work to some extent)

ContentLicense: CC BY-SA 3.0

Title: rstudio like repl for spark-shell


问:
Django Rendering Matplotlib chart in HTML using mpld3
I'm trying to get a mpld3 chart into my webapp using Django and MPLD3/Matplotlib. As described here it should be straightforward getting the HTML code of the figure written in python.

Views.py

```<code>def figure(request):

    np.random.seed(9615)

    N = 100
    df = pd.DataFrame((.1 * (np.random.random((N, 5)) - .5)).cumsum(0),
                  columns=['a', 'b', 'c', 'd', 'e'], )

    # plot line + confidence interval
    fig, ax = plt.subplots()
    ax.grid(True, alpha=0.3)

    for key, val in df.iteritems():
        l, = ax.plot(val.index, val.values, label=key)
        ax.fill_between(val.index,
                        val.values * .5, val.values * 1.5,
                        color=l.get_color(), alpha=.4)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_title('Interactive legend', size=20)

    html_fig = mpld3.fig_to_html(fig,template_type='general')
    plt.close(fig)

    return render(request, "dashboard.html", {'active_page' : 'dashboard.html', 'div_figure' : html_fig})
</code>```

dashboard.html

```<code><div id="fig_container">
                {{ div_figure }}
</div>
</code>```

AFAIK, the python code gets translated into javascript and should be executed when views.py is rendering dashboard.html, right?

As result, I get the HTML code displayed as text on my dashboard.hmtl.

QUESTION: How do I get the chart displayed? Do I need to parse the HTML string which is returned by the method html_to_fig?

答:
try this in the html</p>

```<code><div id="fig_container">
   {{ div_figure|safe }}
</div>
</code>```

Body:
I'm trying to get a mpld3 chart into my webapp using Django and MPLD3/Matplotlib. As described here it should be straightforward getting the HTML code of the figure written in python.

Views.py

def figure(request):

    np.random.seed(9615)

    N = 100
    df = pd.DataFrame((.1 * (np.random.random((N, 5)) - .5)).cumsum(0),
                  columns=['a', 'b', 'c', 'd', 'e'], )

    # plot line + confidence interval
    fig, ax = plt.subplots()
    ax.grid(True, alpha=0.3)

    for key, val in df.iteritems():
        l, = ax.plot(val.index, val.values, label=key)
        ax.fill_between(val.index,
                        val.values * .5, val.values * 1.5,
                        color=l.get_color(), alpha=.4)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_title('Interactive legend', size=20)

    html_fig = mpld3.fig_to_html(fig,template_type='general')
    plt.close(fig)

    return render(request, "dashboard.html", {'active_page' : 'dashboard.html', 'div_figure' : html_fig})

dashboard.html

                {{ div_figure }}

AFAIK, the python code gets translated into javascript and should be executed when views.py is rendering dashboard.html, right?

As result, I get the HTML code displayed as text on my dashboard.hmtl.

QUESTION: How do I get the chart displayed? Do I need to parse the HTML string which is returned by the method html_to_fig?

Body:
try this in the html

<div id="fig_container">
   {{ div_figure|safe }}
</div>


问:
iOS like over scroll effect on Android
I want to implement the iOS-like bounce overscroll effect in my app.

I came across this link which suggests creating a custom ScrollView. But the problem is that when I am scrolling up and down fast it's working fine but as soon as I pull the bottom or top of the screen it's just stuck and the effect is not working anymore.

As an example of the kind of animation I want to achieve you can look at this:

This is the code I currently have:

```<code>public class ObservableScrollView extends ScrollView
{
    private static final int MAX_Y_OVERSCROLL_DISTANCE = 150;

    private Context mContext;
    private int mMaxYOverscrollDistance;

    public ObservableScrollView(Context context)
    {
        super(context);
        mContext = context;
        initBounceScrollView();
    }

    public ObservableScrollView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        mContext = context;
        initBounceScrollView();
    }

    public ObservableScrollView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        mContext = context;
        initBounceScrollView();
    }

    private void initBounceScrollView()
    {
        //get the density of the screen and do some maths with it on the max overscroll distance
        //variable so that you get similar behaviors no matter what the screen size

        final DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();
        final float density = metrics.density;

        mMaxYOverscrollDistance = (int) (density * MAX_Y_OVERSCROLL_DISTANCE);
    }

    @Override
    protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent)
    {
        //This is where the magic happens, we have replaced the incoming maxOverScrollY with our own custom variable mMaxYOverscrollDistance;
        return super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, maxOverScrollX, mMaxYOverscrollDistance, isTouchEvent);
    }
}
</code>```

答:
Use this</p>

```<code>Private ScrollView scrMain;

scrMain = (ScrollView) v.findViewbyId(R.id.scrMain);

OverScrollDecorHandler.setScrollView(scrMain);
</code>```

Title: iOS like over scroll effect on Android

Body:
I want to implement the iOS-like bounce overscroll effect in my app.

I came across this link which suggests creating a custom ScrollView. But the problem is that when I am scrolling up and down fast it's working fine but as soon as I pull the bottom or top of the screen it's just stuck and the effect is not working anymore.

As an example of the kind of animation I want to achieve you can look at this:

This is the code I currently have:

public class ObservableScrollView extends ScrollView
{
    private static final int MAX_Y_OVERSCROLL_DISTANCE = 150;

    private Context mContext;
    private int mMaxYOverscrollDistance;

    public ObservableScrollView(Context context)
    {
        super(context);
        mContext = context;
        initBounceScrollView();
    }

    public ObservableScrollView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        mContext = context;
        initBounceScrollView();
    }

    public ObservableScrollView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        mContext = context;
        initBounceScrollView();
    }

    private void initBounceScrollView()
    {
        //get the density of the screen and do some maths with it on the max overscroll distance
        //variable so that you get similar behaviors no matter what the screen size

        final DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();
        final float density = metrics.density;

        mMaxYOverscrollDistance = (int) (density * MAX_Y_OVERSCROLL_DISTANCE);
    }

    @Override
    protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent)
    {
        //This is where the magic happens, we have replaced the incoming maxOverScrollY with our own custom variable mMaxYOverscrollDistance;
        return super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, maxOverScrollX, mMaxYOverscrollDistance, isTouchEvent);
    }
}

Body:
Use this

Private ScrollView scrMain;

scrMain = (ScrollView) v.findViewbyId(R.id.scrMain);

OverScrollDecorHandler.setScrollView(scrMain);


问:
How to set store id to cms block output
I am using below code to display static block content but it display only first store block every time.I am load this cms block on admin side.
I have two block with same identifier but assign it to diffrent store so i would like to display it store wise.

Here is code i m using but it didn't help.

```<code>Mage::app()->getLayout()->createBlock('cms/block')->setBlockId('pdf_page_of')->setStoreId($storeId)->toHtml()
</code>```

答:
You can try the code below: </p>

```<code>Mage::getModel('cms/block')
    ->setStoreId(Mage::app()->getStore()->getId())
    ->load('pdf_page_of')
;
</code>```

Title: How to set store id to cms block output

Body:
I am using below code to display static block content but it display only first store block every time.I am load this cms block on admin side.
I have two block with same identifier but assign it to diffrent store so i would like to display it store wise.

Here is code i m using but it didn't help.

Mage::app()->getLayout()->createBlock('cms/block')->setBlockId('pdf_page_of')->setStoreId($storeId)->toHtml()

Body:
You can try the code below:

Mage::getModel('cms/block')
    ->setStoreId(Mage::app()->getStore()->getId())
    ->load('pdf_page_of')
;

ContentLicense: CC BY-SA 4.0


问:
Compare two objects by reference when equality operator is overridden
I need to check if two objects of the same type are the same instances and point to the same allocation of memory. The problem is that the type has overloaded equality operator and thus it will use it as comparing the both for equality, but I need to check them for reference. I looked through object.ReferenceEquals() method, but it internally applies equality operator

答:
Operators can't be overridden - they can only be overloaded.

So the == operator in object.ReferenceEquals is still comparing references, or you could do the same thing yourself by casting one or both operands:

```<code>string x = "some value";
string y = new string(x.ToCharArray());
Console.WriteLine(x == y);                   // True
Console.WriteLine((object) x == (object) y); // False
Console.WriteLine(ReferenceEquals(x, y));    // False
</code>```

Body:
Operators can't be overridden - they can only be overloaded.

So the == operator in object.ReferenceEquals is still comparing references, or you could do the same thing yourself by casting one or both operands:

string x = "some value";
string y = new string(x.ToCharArray());
Console.WriteLine(x == y);                   // True
Console.WriteLine((object) x == (object) y); // False
Console.WriteLine(ReferenceEquals(x, y));    // False


问:
add zero after single number if needed
i want to add zero after number if number is single

e.g $a = 2 then 20
if $a = 20 then 20
if $a = 12 then '12'

like this. I some things but it didn't work for me.
How to do it ?

答:
Use str_pad to pad with zeros.

http://php.net/manual/en/function.str-pad.php

```<code>Echo str_pad($a, 2, "0", STR_PAD_RIGHT);
</code>```

Title: add zero after single number if needed

Body:
Use str_pad to pad with zeros.

http://php.net/manual/en/function.str-pad.php

Echo str_pad($a, 2, "0", STR_PAD_RIGHT);


问:
Add js scripts in the application.html.erb
I am new to rails, I know that we add our css and js files in application.html.erb file.

But do we also add the js scripts in the same file?

For example this script below

```<code>   <script>
    $(function () {
      $("#slider").responsiveSlides({
        auto: true,
        speed: 500,
        namespace: "callbacks",
        pager: true,
      });
    });
  </script>
</code>```

答: you can create a custom js file in /assets/javascripts folder and write all your js code and it will load in your page also.


问:
Expression trees - substitute expression
Consider two expression trees:

```<code>Expression<Func<float, float, float>> f1 = (x, y) => x + y;
Expression<Func<float, float>> f2 = x => x * x;
</code>```

I want to substitute the expression f2 as a second parameter of f1 and obtain the following expression:

```<code>Expression<Func<float, float, float>> f3 = (x, y) => x + y * y;
</code>```

The simplest way is to use Expression.Lambda and Expression.Invoke, but the result will look like

```<code>(x, y) => f1(x, f2(y))
</code>```

But this is unacceptable for me due to ORM limitations that cannot handle invoke/lambda properly.

Is it possible to construct the expression without full traversal of expression trees? A working example that fulfill my needs can be found here but I want simpler solution.

答:
You cannot do it without full traversal of both expressions. Fortunately, ExpressionVisitor makes full traversal really easy:

```<code>class ReplaceParameter : ExpressionVisitor {
    private readonly Expression replacement;
    private readonly ParameterExpression parameter;
    public ReplaceParameter(
        ParameterExpression parameter
    ,   Expression replacement
    ) {
        this.replacement = replacement;
        this.parameter = parameter;
    }
    protected override Expression VisitParameter(ParameterExpression node) {
        return node == parameter ? replacement : node;
    }
}
</code>```

Use this visitor twice to complete the replacement:

```<code>Expression<Func<float,float,float>> f1 = (x, y) => x + y;
Expression<Func<float,float>> f2 = x => x * x;
var pX = f2.Parameters[0];
var pY = f1.Parameters[1];
var replacerF2 = new ReplaceParameter(pX, pY);
var replacerF1 = new ReplaceParameter(pY, replacerF2.Visit(f2.Body));
var modifiedF1 = Expression.Lambda(
    replacerF1.Visit(f1.Body)
,   f1.Parameters
);
Console.WriteLine(modifiedF1);
</code>```

The above prints

```<code>(x, y) => (x + (y * y))
</code>```

Demo.

Body:
Consider two expression trees:

Expression<Func<float, float, float>> f1 = (x, y) => x + y;
Expression<Func<float, float>> f2 = x => x * x;

I want to substitute the expression f2 as a second parameter of f1 and obtain the following expression:

Expression<Func<float, float, float>> f3 = (x, y) => x + y * y;

The simplest way is to use Expression.Lambda and Expression.Invoke, but the result will look like

(x, y) => f1(x, f2(y))

But this is unacceptable for me due to ORM limitations that cannot handle invoke/lambda properly.

Is it possible to construct the expression without full traversal of expression trees? A working example that fulfill my needs can be found here but I want simpler solution.

Body:
You cannot do it without full traversal of both expressions. Fortunately, ExpressionVisitor makes full traversal really easy:

class ReplaceParameter : ExpressionVisitor {
    private readonly Expression replacement;
    private readonly ParameterExpression parameter;
    public ReplaceParameter(
        ParameterExpression parameter
    ,   Expression replacement
    ) {
        this.replacement = replacement;
        this.parameter = parameter;
    }
    protected override Expression VisitParameter(ParameterExpression node) {
        return node == parameter ? replacement : node;
    }
}

Use this visitor twice to complete the replacement:

Expression<Func<float,float,float>> f1 = (x, y) => x + y;
Expression<Func<float,float>> f2 = x => x * x;
var pX = f2.Parameters[0];
var pY = f1.Parameters[1];
var replacerF2 = new ReplaceParameter(pX, pY);
var replacerF1 = new ReplaceParameter(pY, replacerF2.Visit(f2.Body));
var modifiedF1 = Expression.Lambda(
    replacerF1.Visit(f1.Body)
,   f1.Parameters
);
Console.WriteLine(modifiedF1);

The above prints

(x, y) => (x + (y * y))

Demo.


问:
How to get the callback value of function that is inside an another function?
I have two functions updateSpeaker(),uploadSpeakerImageAdd() I want to upload the image to the webapi and get the filename as callback and i want to post the filename within the  updateSpeaker() .

updateSpeaker()

```<code>   updateSpeaker(menuItem)
        {

          this.uploadSpeakerImageAdd();
          console.log(this.imagename)
        let update_event_speakers_body={
                '_id':this.menuItem.id,
                'name':this.menuItem.name,
                'matter':this.menuItem.matter,
                'image':this.imagename,       //file name getting from the uploadSpeakerImageAdd().
                'session':this.menuItem.session,
                'link':this.menuItem.link,
                'event_id':this.EventId };
        this.getPostMenuService.doUpdateSpeakers(update_event_speakers_body).subscribe(
                    data => {
                    console.log(data);
                   },err => {
                    console.log("error")
                  });

        }
</code>```

uploadSpeakerImageAdd()

```<code> uploadSpeakerImageAdd() {
    let inputEl: HTMLInputElement = this.inputEl.nativeElement;
    let fileCount: number = inputEl.files.length;
    console.log(fileCount);
    let formData = new FormData();
    if (fileCount > 0) { // a file was selected
        for (let i = 0; i < fileCount; i++) {
            formData.append('file[]', inputEl.files.item(i));
        }

        this.getPostMenuService.doPostImage( formData).subscribe(data => {

                        this.imagename=data.file;
                       console.log( this.imagename);

                   },
            err => {
             console.log("error")

          });
     }

  }
</code>```

This code is working but only getting the file name after the execution of updateSpeaker()

答:
From your html part , fire change event like this:

```<code><input type="file" (change)="uploadSpeakerImageAdd($event)" value="file">

And in your component or controller:

uploadSpeakerImageAdd($event): void {
   let inputValue: any;
   inputValue = $event.target;
   this.file = inputValue.files[0];

   this.getPostMenuService.doPostImage(this.file)
    .subscribe(
     data => {
       this.imagename=data.file;
     },
     error => {

     };

    });
}
</code>```

Call your uploadSpeakerImageAdd on change event.

Body:
I have two functions updateSpeaker(),uploadSpeakerImageAdd() I want to upload the image to the webapi and get the filename as callback and i want to post the filename within the  updateSpeaker() .

updateSpeaker()

   updateSpeaker(menuItem)
        {

          this.uploadSpeakerImageAdd();
          console.log(this.imagename)
        let update_event_speakers_body={
                '_id':this.menuItem.id,
                'name':this.menuItem.name,
                'matter':this.menuItem.matter,
                'image':this.imagename,       //file name getting from the uploadSpeakerImageAdd().
                'session':this.menuItem.session,
                'link':this.menuItem.link,
                'event_id':this.EventId };
        this.getPostMenuService.doUpdateSpeakers(update_event_speakers_body).subscribe(
                    data => {
                    console.log(data);
                   },err => {
                    console.log("error")
                  });

        }

uploadSpeakerImageAdd()

 uploadSpeakerImageAdd() {
    let inputEl: HTMLInputElement = this.inputEl.nativeElement;
    let fileCount: number = inputEl.files.length;
    console.log(fileCount);
    let formData = new FormData();
    if (fileCount > 0) { // a file was selected
        for (let i = 0; i < fileCount; i++) {
            formData.append('file[]', inputEl.files.item(i));
        }

        this.getPostMenuService.doPostImage( formData).subscribe(data => {

                        this.imagename=data.file;
                       console.log( this.imagename);

                   },
            err => {
             console.log("error")

          });
     }

  }

This code is working but only getting the file name after the execution of updateSpeaker()

Body:
From your html part , fire change event like this:

<input type="file" (change)="uploadSpeakerImageAdd($event)" value="file">

And in your component or controller:

uploadSpeakerImageAdd($event): void {
   let inputValue: any;
   inputValue = $event.target;
   this.file = inputValue.files[0];

   this.getPostMenuService.doPostImage(this.file)
    .subscribe(
     data => {
       this.imagename=data.file;
     },
     error => {

     };

    });
}

Call your uploadSpeakerImageAdd on change event.


问:
WebDriver cannot be initialized
I got NullPointerException when I run the @testCase

1. In FrameworkTestCases.class -> @BeforeClass I initialize the instance of the selected webdriver. The browser is running when I start the  FrameworkTestCases.class as jUnit test, but when I reach the testCase it says NullPointerException. What is the reason? I also used a constructor with 2 arguments to inherit the driver from the Generic.class to LoginPageFactory.class, but nothing happened.

Here is my FrameworkTestCases class:

```<code>public class FrameworkTestCases {

static WebDriver driver;
private static String baseURl = "https://management.tacticlicks.com/";
static LoginPageFactory loginPage;
static Generic generic;
//WebDriver driver;
//static LoginPageFactory lpFactory;

@BeforeClass
public static void setUp() {
    generic = new Generic(driver);
    generic.getDriver(baseURl, "chrome");
}

@Test
public void test() {
    System.out.println("Executing test");

    loginPage
    .fillUsernameField("ivailostefanov1989@gmail.com")
    .fillPasswordField("astral8909")
    .clickSubmit();
}

@AfterClass
public static void tearDown() {
    driver.quit();
}
}

public class LoginPageFactory extends Generic {

public LoginPageFactory(WebDriver driver2, Class<LoginPageFactory> class1) {
    super(driver2, class1);
    // TODO Auto-generated constructor stub
}

WebDriver driver;

@FindBy(name="email") //.//*[@id='login']/div[1]/div/div/table/tbody/tr/td[2]/div[1]/form/div[1]/input
WebElement loginUsernameField;

@FindBy(name="password")
WebElement loginPasswordField;

@FindBy(tagName="button")
WebElement loginSubmitButton;

public LoginPageFactory(WebDriver driver) {
    System.out.println("LoginPageFactory");
    this.driver = driver;
    PageFactory.initElements(driver, this);
}

public LoginPageFactory fillUsernameField(String username) {
    System.out.println("Before field initializing");
    WebElement emailField = driver.findElement(By.name("email"));
    emailField.click();
    emailField.sendKeys(username);
    return this;
}

public LoginPageFactory fillPasswordField(String password) {
    loginPasswordField.click();
    loginPasswordField.clear();
    loginPasswordField.sendKeys(password);
    return this;
}

public LoginPageFactory clickSubmit() {
    loginSubmitButton.click();
    return this;
}
}

public class Generic {

WebDriver driver;

public Generic(WebDriver driver) {
    this.driver = driver;
}

public Generic(WebDriver driver2, Class<LoginPageFactory> class1) {
    // TODO Auto-generated constructor stub
}

private void getBrowser(String browser) {

    if (browser.equalsIgnoreCase("Firefox")) {
        File chromeDriver = new File("C:\\Users\\Ivo\\Desktop\\geckodriver.exe");
        System.setProperty("webdriver.gecko.driver", chromeDriver.getAbsolutePath());
        driver = new FirefoxDriver();
    } else if (browser.equalsIgnoreCase("Chrome")) {

        //set chromedriver property
        File chromeDriver = new File("C:\\Users\\Ivo\\Desktop\\chromedriver.exe");
        System.setProperty("webdriver.chrome.driver", chromeDriver.getAbsolutePath());
        driver = new ChromeDriver();

    } else {
        System.out.println("Browser cannot be launched");
    }

}

public WebDriver getDriver(String appUrl, String browser) {
    getBrowser(browser);
    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    driver.manage().window().maximize();
    driver.get(appUrl);
    return driver;
}
}
</code>```

答:
You are missing a variable assignment in @BeforeClass method.

Change

```<code>@BeforeClass
public static void setUp() {
    generic = new Generic(driver);
    generic.getDriver(baseURl, "chrome");
}
</code>```

to

```<code>@BeforeClass
public static void setUp() {
    generic = new Generic(driver);
    driver = generic.getDriver(baseURl, "chrome");
}
</code>```

And also you did not create any instance of LoginPageFactory class. You have created a variable static LoginPageFactory loginPage; but didn't initialize it (at least nowhere in provided code).
In method

```<code>@Test
public void test() {
    System.out.println("Executing test");

    //add this line of code to initialize elements via Page Factory
    loginPage = new LoginPageFactory(driver);

    loginPage
    .fillUsernameField("ivailostefanov1989@gmail.com")
    .fillPasswordField("astral8909")
    .clickSubmit();
}
</code>```

Title: WebDriver cannot be initialized

Body:
I got NullPointerException when I run the @testCase

1. In FrameworkTestCases.class -> @BeforeClass I initialize the instance of the selected webdriver. The browser is running when I start the  FrameworkTestCases.class as jUnit test, but when I reach the testCase it says NullPointerException. What is the reason? I also used a constructor with 2 arguments to inherit the driver from the Generic.class to LoginPageFactory.class, but nothing happened.

Here is my FrameworkTestCases class:

public class FrameworkTestCases {

static WebDriver driver;
private static String baseURl = "https://management.tacticlicks.com/";
static LoginPageFactory loginPage;
static Generic generic;
//WebDriver driver;
//static LoginPageFactory lpFactory;

@BeforeClass
public static void setUp() {
    generic = new Generic(driver);
    generic.getDriver(baseURl, "chrome");
}

@Test
public void test() {
    System.out.println("Executing test");

    loginPage
    .fillUsernameField("ivailostefanov1989@gmail.com")
    .fillPasswordField("astral8909")
    .clickSubmit();
}

@AfterClass
public static void tearDown() {
    driver.quit();
}
}

public class LoginPageFactory extends Generic {

public LoginPageFactory(WebDriver driver2, Class<LoginPageFactory> class1) {
    super(driver2, class1);
    // TODO Auto-generated constructor stub
}

WebDriver driver;

@FindBy(name="email") //.//*[@id='login']/div[1]/div/div/table/tbody/tr/td[2]/div[1]/form/div[1]/input
WebElement loginUsernameField;

@FindBy(name="password")
WebElement loginPasswordField;

@FindBy(tagName="button")
WebElement loginSubmitButton;

public LoginPageFactory(WebDriver driver) {
    System.out.println("LoginPageFactory");
    this.driver = driver;
    PageFactory.initElements(driver, this);
}

public LoginPageFactory fillUsernameField(String username) {
    System.out.println("Before field initializing");
    WebElement emailField = driver.findElement(By.name("email"));
    emailField.click();
    emailField.sendKeys(username);
    return this;
}

public LoginPageFactory fillPasswordField(String password) {
    loginPasswordField.click();
    loginPasswordField.clear();
    loginPasswordField.sendKeys(password);
    return this;
}

public LoginPageFactory clickSubmit() {
    loginSubmitButton.click();
    return this;
}
}

public class Generic {

WebDriver driver;

public Generic(WebDriver driver) {
    this.driver = driver;
}

public Generic(WebDriver driver2, Class<LoginPageFactory> class1) {
    // TODO Auto-generated constructor stub
}

private void getBrowser(String browser) {

    if (browser.equalsIgnoreCase("Firefox")) {
        File chromeDriver = new File("C:\\Users\\Ivo\\Desktop\\geckodriver.exe");
        System.setProperty("webdriver.gecko.driver", chromeDriver.getAbsolutePath());
        driver = new FirefoxDriver();
    } else if (browser.equalsIgnoreCase("Chrome")) {

        //set chromedriver property
        File chromeDriver = new File("C:\\Users\\Ivo\\Desktop\\chromedriver.exe");
        System.setProperty("webdriver.chrome.driver", chromeDriver.getAbsolutePath());
        driver = new ChromeDriver();

    } else {
        System.out.println("Browser cannot be launched");
    }

}

public WebDriver getDriver(String appUrl, String browser) {
    getBrowser(browser);
    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    driver.manage().window().maximize();
    driver.get(appUrl);
    return driver;
}
}

Body:
You are missing a variable assignment in @BeforeClass method.

Change

@BeforeClass
public static void setUp() {
    generic = new Generic(driver);
    generic.getDriver(baseURl, "chrome");
}

to

@BeforeClass
public static void setUp() {
    generic = new Generic(driver);
    driver = generic.getDriver(baseURl, "chrome");
}

And also you did not create any instance of LoginPageFactory class. You have created a variable static LoginPageFactory loginPage; but didn't initialize it (at least nowhere in provided code).
In method

@Test
public void test() {
    System.out.println("Executing test");

    //add this line of code to initialize elements via Page Factory
    loginPage = new LoginPageFactory(driver);

    loginPage
    .fillUsernameField("ivailostefanov1989@gmail.com")
    .fillPasswordField("astral8909")
    .clickSubmit();
}


问:
Sign string with PEM PrivateKey
I have a PEM-encoded private key and I need to sign a string with it. But the code keeps crashing with exception:

```<code>java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0c0890ba:ASN.1 encoding routines:asn1_check_tlen:WRONG_TAG
</code>```

the key string:

```<code>-----BEGIN ENCRYPTED PRIVATE KEY-----
MIICxjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQI4P/+9mJV6RwCAggA
MBQGCCqGSIb3DQMHBAg/ZWGXeLHgeASCAoAhExhFxfcikmIKbFP0rgAlJuj1r999
... and so on...
hlgzM2p71FdC6NDVyyxbit/IzbimtJyhkRwOAnZ98yqtXWUEOx2v7CcUqiU8dSLA
K0PsaxNTUeUcQV+Z7yJk/8HxfE1ya3u2CgPXCZsWWmbxQG/+awE0eEnZ
-----END ENCRYPTED PRIVATE KEY-----
</code>```

I've tried many variants, looked through many answers, but the results were the same

Edit: with James K Polk's help I've managed to get private key bytes, but now I get java.security.NoSuchAlgorithmException: SecretKeyFactory PBES2 implementation not found. Modified code:

```<code>private String sign(String dataString, String pkString, String privateKeyPass) throws Exception {
        pkString = pkString.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----", "");
        pkString = pkString.replace("-----END ENCRYPTED PRIVATE KEY-----", "");
        pkString = pkString.replaceAll("\\s+","");
        byte[] privateKeyBytes = decryptPrivateKey(Base64.decode(pkString, Base64.DEFAULT), privateKeyPass);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));

        Signature instance = Signature.getInstance("SHA1withRSA");
        instance.initSign(privateKey);
        instance.update(dataString.getBytes(UTF_8));
        return Base64.encodeToString(instance.sign(), Base64.DEFAULT);
    }

public static byte[] decryptPrivateKey(byte[] key, String pass) throws Exception {
        PBEKeySpec passKeySpec = new PBEKeySpec(pass.toCharArray());

        EncryptedPrivateKeyInfo encryptedKey = new EncryptedPrivateKeyInfo(key);
        Timber.w("encryptedKey.getAlgName(): %s", encryptedKey.getAlgName());
        SecretKeyFactory keyFac = SecretKeyFactory.getInstance(encryptedKey.getAlgName());//PBES2
        SecretKey passKey = keyFac.generateSecret(passKeySpec);

        // Create PBE Cipher
        Cipher pbeCipher = Cipher.getInstance(encryptedKey.getAlgName());
        // Initialize PBE Cipher with key and parameters
        pbeCipher.init(Cipher.DECRYPT_MODE, passKey, encryptedKey.getAlgParameters());

        // Decrypt the private key
        return pbeCipher.doFinal(encryptedKey.getEncryptedData());
    }
</code>```

EDIT: I ended up using class from http://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art050:

```<code>PrivateKey privateKey = KeyImport.readPrivateKeyFile(pkFileName, privateKeyPass);
</code>```

I save keyString into a file and then feed it to readPrivateKeyFile

答:
Your private key is encrypted according PKCS#8, so you need to use the EncryptedPrivateKeyInfo class among others. This stackoverflow question contains an example showing how to retrieve it. I have turned it into a more complete example below:

```<code>import javax.crypto.Cipher;
import javax.crypto.EncryptedPrivateKeyInfo;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.List;

public class Main {

    private static byte [] pemFileToBytes(String filename) throws IOException {
        // read in PEM file, throw away the begin and end lines
        List<String> pemLines = Files.readAllLines(Paths.get(filename), StandardCharsets.US_ASCII);
        pemLines.remove(0);
        pemLines.remove(pemLines.size() - 1);
        String pem = String.join("", pemLines);

        // base64 decode and return the result.

        return Base64.getDecoder().decode(pem);
    }

    private static PrivateKey parsePrivateKey (String filename, char [] password) throws Exception{
        PBEKeySpec passKeySpec = new PBEKeySpec(password); //my password

        EncryptedPrivateKeyInfo encryptedKey = new EncryptedPrivateKeyInfo(pemFileToBytes(filename));
        SecretKeyFactory keyFac = SecretKeyFactory.getInstance(encryptedKey.getAlgName());
        SecretKey passKey = keyFac.generateSecret(passKeySpec);

        // Create PBE Cipher
        Cipher pbeCipher = Cipher.getInstance(encryptedKey.getAlgName());
        // Initialize PBE Cipher with key and parameters
        pbeCipher.init(Cipher.DECRYPT_MODE, passKey, encryptedKey.getAlgParameters());

        // Decrypt the private key

        byte [] encodedPrivateKey = pbeCipher.doFinal(encryptedKey.getEncryptedData());
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePrivate(privateKeySpec);

    }

    public static void main(String[] args) throws Exception {
        PrivateKey pk = parsePrivateKey("x.pk8", "pass".toCharArray());
    }
}
</code>```

You last line, return new String(instance.sign(), UTF_8); doesn't make any sense as Signature.sign() returns an array of bytes that is not likely to be a valid string in any character set. If you must convert the signature to a string then the standard way is to base64 encode it.

Title: Sign string with PEM PrivateKey

Body:
I have a PEM-encoded private key and I need to sign a string with it. But the code keeps crashing with exception:

java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0c0890ba:ASN.1 encoding routines:asn1_check_tlen:WRONG_TAG

the key string:

-----BEGIN ENCRYPTED PRIVATE KEY-----
MIICxjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQI4P/+9mJV6RwCAggA
MBQGCCqGSIb3DQMHBAg/ZWGXeLHgeASCAoAhExhFxfcikmIKbFP0rgAlJuj1r999
... and so on...
hlgzM2p71FdC6NDVyyxbit/IzbimtJyhkRwOAnZ98yqtXWUEOx2v7CcUqiU8dSLA
K0PsaxNTUeUcQV+Z7yJk/8HxfE1ya3u2CgPXCZsWWmbxQG/+awE0eEnZ
-----END ENCRYPTED PRIVATE KEY-----

I've tried many variants, looked through many answers, but the results were the same

Edit: with James K Polk's help I've managed to get private key bytes, but now I get java.security.NoSuchAlgorithmException: SecretKeyFactory PBES2 implementation not found. Modified code:

private String sign(String dataString, String pkString, String privateKeyPass) throws Exception {
        pkString = pkString.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----", "");
        pkString = pkString.replace("-----END ENCRYPTED PRIVATE KEY-----", "");
        pkString = pkString.replaceAll("\\s+","");
        byte[] privateKeyBytes = decryptPrivateKey(Base64.decode(pkString, Base64.DEFAULT), privateKeyPass);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));

        Signature instance = Signature.getInstance("SHA1withRSA");
        instance.initSign(privateKey);
        instance.update(dataString.getBytes(UTF_8));
        return Base64.encodeToString(instance.sign(), Base64.DEFAULT);
    }

public static byte[] decryptPrivateKey(byte[] key, String pass) throws Exception {
        PBEKeySpec passKeySpec = new PBEKeySpec(pass.toCharArray());

        EncryptedPrivateKeyInfo encryptedKey = new EncryptedPrivateKeyInfo(key);
        Timber.w("encryptedKey.getAlgName(): %s", encryptedKey.getAlgName());
        SecretKeyFactory keyFac = SecretKeyFactory.getInstance(encryptedKey.getAlgName());//PBES2
        SecretKey passKey = keyFac.generateSecret(passKeySpec);

        // Create PBE Cipher
        Cipher pbeCipher = Cipher.getInstance(encryptedKey.getAlgName());
        // Initialize PBE Cipher with key and parameters
        pbeCipher.init(Cipher.DECRYPT_MODE, passKey, encryptedKey.getAlgParameters());

        // Decrypt the private key
        return pbeCipher.doFinal(encryptedKey.getEncryptedData());
    }

EDIT: I ended up using class from http://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art050:

PrivateKey privateKey = KeyImport.readPrivateKeyFile(pkFileName, privateKeyPass);

I save keyString into a file and then feed it to readPrivateKeyFile

Body:
Your private key is encrypted according PKCS#8, so you need to use the EncryptedPrivateKeyInfo class among others. This stackoverflow question contains an example showing how to retrieve it. I have turned it into a more complete example below:

import javax.crypto.Cipher;
import javax.crypto.EncryptedPrivateKeyInfo;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.List;

public class Main {

    private static byte [] pemFileToBytes(String filename) throws IOException {
        // read in PEM file, throw away the begin and end lines
        List<String> pemLines = Files.readAllLines(Paths.get(filename), StandardCharsets.US_ASCII);
        pemLines.remove(0);
        pemLines.remove(pemLines.size() - 1);
        String pem = String.join("", pemLines);

        // base64 decode and return the result.

        return Base64.getDecoder().decode(pem);
    }

    private static PrivateKey parsePrivateKey (String filename, char [] password) throws Exception{
        PBEKeySpec passKeySpec = new PBEKeySpec(password); //my password

        EncryptedPrivateKeyInfo encryptedKey = new EncryptedPrivateKeyInfo(pemFileToBytes(filename));
        SecretKeyFactory keyFac = SecretKeyFactory.getInstance(encryptedKey.getAlgName());
        SecretKey passKey = keyFac.generateSecret(passKeySpec);

        // Create PBE Cipher
        Cipher pbeCipher = Cipher.getInstance(encryptedKey.getAlgName());
        // Initialize PBE Cipher with key and parameters
        pbeCipher.init(Cipher.DECRYPT_MODE, passKey, encryptedKey.getAlgParameters());

        // Decrypt the private key

        byte [] encodedPrivateKey = pbeCipher.doFinal(encryptedKey.getEncryptedData());
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePrivate(privateKeySpec);

    }

    public static void main(String[] args) throws Exception {
        PrivateKey pk = parsePrivateKey("x.pk8", "pass".toCharArray());
    }
}

You last line, return new String(instance.sign(), UTF_8); doesn't make any sense as Signature.sign() returns an array of bytes that is not likely to be a valid string in any character set. If you must convert the signature to a string then the standard way is to base64 encode it.


问:
Transferring data from two components to the service (angular 2)
I recently in angular2, I made 2 components (users.component and tasks.component) which should pass their data to the service, that it would perform some actions and pass it on to the parent component.

users.component.ts

```<code>  import { Component } from '@angular/core';

  @Component({
    selector: 'users',
    templateUrl: 'app/users.component.html',
    styleUrls: ['app/users.component.css']
  })
  export class UsersComponent {
    usersArr: any[] = [];

    designUsers: any[] = [];
    frontendUsers: any[] = [];
    backendUsers: any[] = [];

    addUsersRow(): void {
      this.usersArr.push({});
    }

    recountUsers(i: number, userSpec: any): void {

            if (userSpec === 'd' || userSpec === 'D') {
                this.designUsers.push(this.usersArr[i]);
            } else if (userSpec === 'f' || userSpec === 'F') {
                this.frontendUsers.push(this.usersArr[i]);
            } else if (userSpec === 'b' || userSpec === 'B') {
                this.backendUsers.push(this.usersArr[i]);
            }

            for (let j = 0; j < this.designUsers.length; j++) {
              if (this.designUsers[j].spec == 'f' || this.designUsers[j].spec == 'b') {
                this.designUsers.splice(j, 1);
              }
            }

            for (let j = 0; j < this.frontendUsers.length; j++) {
              if (this.frontendUsers[j].spec == 'b' || this.frontendUsers[j].spec == 'd') {
                this.frontendUsers.splice(j, 1);
              }
            }

            for (let j = 0; j < this.backendUsers.length; j++) {

              if (this.backendUsers[j].spec == 'f' || this.backendUsers[j].spec == 'd') {
                this.backendUsers.splice(j, 1);
              }
            }

    }

    usersName(i: number, userName: any): void {
      this.usersArr[i].name = userName;
    }

    usersSpec(i: number, userSpec: any): void {

        this.usersArr[i].spec = userSpec;

        this.recountUsers(i, userSpec);
    }

    usersPrice(i: number, userPrice: any): void {
      this.usersArr[i].price = userPrice;
    }
  }
</code>```

users.component.html

```<code><div class="addUser" id="addUser">
                <h1>USER</h1>
                <button class="addUser__button" id="addUserButton" type="button" (click)="addUsersRow()">Добавить USER</button>
                <div class="addUser__input" *ngFor="let rowUsers of usersArr; let i=index">{{i}}
                    <input class="addUser__input-name" type="text" placeholder=" Имя: Петр" (change)="usersName(i, userName.value)" #userName required>
                    <input class="addUser__input-spec" type="text" placeholder=" Специализация: f/b/d" maxlength="1" pattern="[dbfDBF]" (change)="usersSpec(i, userSpec.value)" #userSpec required>
                    <input class="addUser__input-price" type="number" placeholder=" Цена: 2000" min="0" (change)="usersPrice(i, userPrice.value)" #userPrice required>
                </div>
            </div>
</code>```

tasks.component.ts

```<code>import { Component } from '@angular/core';

        @Component({
            selector: 'tasks',
            templateUrl: 'app/tasks.component.html',
            styleUrls: ['app/tasks.component.css']
        })
        export class TasksComponent {
            tasksArr: any[] = [];

            designTasks: any[] = [];
            frontendTasks: any[] = [];
            backendTasks: any[] = [];

            addTasksRow(): void {
              this.tasksArr.push({});
            }

            recountTasks(i: number, taskSpec: any): void {

                if (taskSpec == 'd' || taskSpec == 'D') {
                    this.designTasks.push(this.tasksArr[i]);
                } else if (taskSpec == 'f' || taskSpec == 'F') {
                    this.frontendTasks.push(this.tasksArr[i]);
                } else if (taskSpec == 'b' || taskSpec == 'B') {
                    this.backendTasks.push(this.tasksArr[i]);
                }

                for (let j = 0; j < this.designTasks.length; j++) {
                  if (this.designTasks[j].spec == 'f' || this.designTasks[j].spec == 'b') {
                    this.designTasks.splice(j, 1);
                  }
                }

                for (let j = 0; j < this.frontendTasks.length; j++) {
                  if (this.frontendTasks[j].spec == 'b' || this.frontendTasks[j].spec == 'd') {
                    this.frontendTasks.splice(j, 1);
                  }
                }

                for (let j = 0; j < this.backendTasks.length; j++) {

                  if (this.backendTasks[j].spec == 'f' || this.backendTasks[j].spec == 'd') {
                    this.backendTasks.splice(j, 1);
                  }
                }
            }

            tasksSpec(i: number, taskSpec: any): void {

                this.tasksArr[i].spec = taskSpec;

                this.recountTasks(i, taskSpec);

                console.log('tasksArr:');
                console.log(this.tasksArr);
            }

            tasksHours(i: number, taskHours: any): void {
                this.tasksArr[i].hours = taskHours;
            }
        }
</code>```

tasks.component.html

```<code><div class="addTask" id="addTask">
                    <h1>TASK</h1>
                    <button class="addTask__button" id="addTaskButton" type="button" (click)="addTasksRow();">Добавить TASK</button>
                    <div class="addTask__input" *ngFor="let rowTasks of tasksArr; let i=index">{{i}}
                        <input class="addTask__input-spec" type="text" placeholder=" Специализация: f/b/d" maxlength="1" pattern="[dbfDBF]" (change)="tasksSpec(i, taskSpec.value)" #taskSpec required>
                        <input class="addTask__input-hours" type="number" placeholder=" Часы: 20" min="0" (change)="tasksHours(i, taskHours.value)" #taskHours required>
                    </div>
                </div>
</code>```

compare.service.ts

```<code>import { Injectable } from '@angular/core';

@Injectable()
export class CompareService {
    code...
}
</code>```

I want to implement this structure:
enter image description here

From users.component I need to take designUsers, frontendUsers and backendUsers, and from tasks like designTasks and so on (every arrays). The question is, is it possible to implement such a structure and if not, help please the idea how it would be possible to implement this thought, thanks.

答:
Check out this plunkr example. There are two child components, both can change a state of some service.

```<code>@Component({
  selector: 'child1',
  template: `
      <button (click)="handle()">child 1</button>
  `,
})
export class Child1Component {
  constructor(private service: Service) {}

  handle() {
    this.service.child1State = true;
  }
}
</code>```

There is a parrent component which is subscribed to the service's state changes:

```<code>@Component({
  selector: 'my-app',
  template: `
    <div>{{state}}</div>
    <child1></child1>
    <child2></child2>
  `,
})
export class App implements OnInit {
  state = 'unset';

  constructor(private service: Service) {}

  ngOnInit() {
    this.service.observable.subscribe(val => {
      if (val) {
        this.state = 'set';
      } else {
        this.state = 'unset';
      }
    });
  }
}
</code>```

And here is the service. It checks the state after each changes and notify the subscriber-component if needed:

```<code>@Injectable()
export class Service {
  private _child1State = false;
  private _child2State = false;
  private subject = new Subject<boolean>;
  observable = this.subject.asObservable();

  set child1State(val: boolean) {
    this._child1State = val;
    if (this.isAllSet()) {
      this.subject.next(true);
    }
  }

  set child2State(val: boolean) {
    this._child2State = val;
    if (this.isAllSet()) {
      this.subject.next(true);
    }
  }

  private isAllSet(): boolean {
    return this._child1State && this._child2State;
  }
}
</code>```

Body:
I recently in angular2, I made 2 components (users.component and tasks.component) which should pass their data to the service, that it would perform some actions and pass it on to the parent component.

users.component.ts

  import { Component } from '@angular/core';

  @Component({
    selector: 'users',
    templateUrl: 'app/users.component.html',
    styleUrls: ['app/users.component.css']
  })
  export class UsersComponent {
    usersArr: any[] = [];

    designUsers: any[] = [];
    frontendUsers: any[] = [];
    backendUsers: any[] = [];

    addUsersRow(): void {
      this.usersArr.push({});
    }

    recountUsers(i: number, userSpec: any): void {

            if (userSpec === 'd' || userSpec === 'D') {
                this.designUsers.push(this.usersArr[i]);
            } else if (userSpec === 'f' || userSpec === 'F') {
                this.frontendUsers.push(this.usersArr[i]);
            } else if (userSpec === 'b' || userSpec === 'B') {
                this.backendUsers.push(this.usersArr[i]);
            }

            for (let j = 0; j < this.designUsers.length; j++) {
              if (this.designUsers[j].spec == 'f' || this.designUsers[j].spec == 'b') {
                this.designUsers.splice(j, 1);
              }
            }

            for (let j = 0; j < this.frontendUsers.length; j++) {
              if (this.frontendUsers[j].spec == 'b' || this.frontendUsers[j].spec == 'd') {
                this.frontendUsers.splice(j, 1);
              }
            }

            for (let j = 0; j < this.backendUsers.length; j++) {

              if (this.backendUsers[j].spec == 'f' || this.backendUsers[j].spec == 'd') {
                this.backendUsers.splice(j, 1);
              }
            }

    }

    usersName(i: number, userName: any): void {
      this.usersArr[i].name = userName;
    }

    usersSpec(i: number, userSpec: any): void {

        this.usersArr[i].spec = userSpec;

        this.recountUsers(i, userSpec);
    }

    usersPrice(i: number, userPrice: any): void {
      this.usersArr[i].price = userPrice;
    }
  }

users.component.html

USER

                <button class="addUser__button" id="addUserButton" type="button" (click)="addUsersRow()">Добавить USER</button>

{{i}}
                    <input class="addUser__input-name" type="text" placeholder=" Имя: Петр" (change)="usersName(i, userName.value)" #userName required>
                    <input class="addUser__input-spec" type="text" placeholder=" Специализация: f/b/d" maxlength="1" pattern="[dbfDBF]" (change)="usersSpec(i, userSpec.value)" #userSpec required>
                    <input class="addUser__input-price" type="number" placeholder=" Цена: 2000" min="0" (change)="usersPrice(i, userPrice.value)" #userPrice required>

tasks.component.ts

import { Component } from '@angular/core';

        @Component({
            selector: 'tasks',
            templateUrl: 'app/tasks.component.html',
            styleUrls: ['app/tasks.component.css']
        })
        export class TasksComponent {
            tasksArr: any[] = [];

            designTasks: any[] = [];
            frontendTasks: any[] = [];
            backendTasks: any[] = [];

            addTasksRow(): void {
              this.tasksArr.push({});
            }

            recountTasks(i: number, taskSpec: any): void {

                if (taskSpec == 'd' || taskSpec == 'D') {
                    this.designTasks.push(this.tasksArr[i]);
                } else if (taskSpec == 'f' || taskSpec == 'F') {
                    this.frontendTasks.push(this.tasksArr[i]);
                } else if (taskSpec == 'b' || taskSpec == 'B') {
                    this.backendTasks.push(this.tasksArr[i]);
                }

                for (let j = 0; j < this.designTasks.length; j++) {
                  if (this.designTasks[j].spec == 'f' || this.designTasks[j].spec == 'b') {
                    this.designTasks.splice(j, 1);
                  }
                }

                for (let j = 0; j < this.frontendTasks.length; j++) {
                  if (this.frontendTasks[j].spec == 'b' || this.frontendTasks[j].spec == 'd') {
                    this.frontendTasks.splice(j, 1);
                  }
                }

                for (let j = 0; j < this.backendTasks.length; j++) {

                  if (this.backendTasks[j].spec == 'f' || this.backendTasks[j].spec == 'd') {
                    this.backendTasks.splice(j, 1);
                  }
                }
            }

            tasksSpec(i: number, taskSpec: any): void {

                this.tasksArr[i].spec = taskSpec;

                this.recountTasks(i, taskSpec);

                console.log('tasksArr:');
                console.log(this.tasksArr);
            }

            tasksHours(i: number, taskHours: any): void {
                this.tasksArr[i].hours = taskHours;
            }
        }

tasks.component.html

TASK

                    <button class="addTask__button" id="addTaskButton" type="button" (click)="addTasksRow();">Добавить TASK</button>

{{i}}
                        <input class="addTask__input-spec" type="text" placeholder=" Специализация: f/b/d" maxlength="1" pattern="[dbfDBF]" (change)="tasksSpec(i, taskSpec.value)" #taskSpec required>
                        <input class="addTask__input-hours" type="number" placeholder=" Часы: 20" min="0" (change)="tasksHours(i, taskHours.value)" #taskHours required>

compare.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class CompareService {
    code...
}

I want to implement this structure:
enter image description here

From users.component I need to take designUsers, frontendUsers and backendUsers, and from tasks like designTasks and so on (every arrays). The question is, is it possible to implement such a structure and if not, help please the idea how it would be possible to implement this thought, thanks.

Body:
Check out this plunkr example. There are two child components, both can change a state of some service.

@Component({
  selector: 'child1',
  template: `
      <button (click)="handle()">child 1</button>
  `,
})
export class Child1Component {
  constructor(private service: Service) {}

  handle() {
    this.service.child1State = true;
  }
}

There is a parrent component which is subscribed to the service's state changes:

@Component({
  selector: 'my-app',
  template: `
    <div>{{state}}</div>
    <child1></child1>
    <child2></child2>
  `,
})
export class App implements OnInit {
  state = 'unset';

  constructor(private service: Service) {}

  ngOnInit() {
    this.service.observable.subscribe(val => {
      if (val) {
        this.state = 'set';
      } else {
        this.state = 'unset';
      }
    });
  }
}

And here is the service. It checks the state after each changes and notify the subscriber-component if needed:

@Injectable()
export class Service {
  private _child1State = false;
  private _child2State = false;
  private subject = new Subject<boolean>;
  observable = this.subject.asObservable();

  set child1State(val: boolean) {
    this._child1State = val;
    if (this.isAllSet()) {
      this.subject.next(true);
    }
  }

  set child2State(val: boolean) {
    this._child2State = val;
    if (this.isAllSet()) {
      this.subject.next(true);
    }
  }

  private isAllSet(): boolean {
    return this._child1State && this._child2State;
  }
}