问:
button BACK to a collapsingToolbar - Android
It happens that from my main activity I call an activity in that activity that I call tale with collapsingToolbar, well everything works fine only that I can not give BACK because the collapsinToolbar does not generate a button back.

Java code of the main activity

```<code>package com.herprogramacion.alquileres;

import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.herprogramacion.alquileres.provider.Contrato.Alquileres;

public class ActividadListaAlquileres extends AppCompatActivity implements       AdaptadorAlquileres.OnItemClickListener, LoaderManager.LoaderCallbacks<Cursor> {

private RecyclerView listaUI;
private LinearLayoutManager linearLayoutManager;
private AdaptadorAlquileres adaptador;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.actividad_lista_alquileres);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Filtro...", Snackbar.LENGTH_LONG)
                    .setAction("Acción", null).show();
        }
    });

    // Preparar lista

    listaUI = (RecyclerView) findViewById(R.id.lista);

    listaUI.setHasFixedSize(true);

    linearLayoutManager = new LinearLayoutManager(this);

    listaUI.setLayoutManager(linearLayoutManager);

    adaptador = new AdaptadorAlquileres(this, this);

    listaUI.setAdapter(adaptador);

    // Iniciar loader
   getSupportLoaderManager().restartLoader(1, null, this);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_actividad_lista_alquileres, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onClick(AdaptadorAlquileres.ViewHolder holder, String idAlquiler) {
   // Snackbar.make(findViewById(android.R.id.content), ":id = " + idAlquiler,
     //       Snackbar.LENGTH_LONG).show();
}

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    return new CursorLoader(this, Alquileres.URI_CONTENIDO, null, null, null, null);
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if (adaptador != null) {
        adaptador.swapCursor(data);
    }
}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
</code>```

Java code of the activity where I generate the collapsingToolbar

```<code>package com.herprogramacion.alquileres;

import android.content.Intent;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;

public class biografia2 extends AppCompatActivity {

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

    CollapsingToolbarLayout collapsingToolbar =
            (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
    collapsingToolbar.setTitle("Titulo ");

}
}
</code>```

Xml code of my main activity

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.herprogramacion.alquileres.ActividadListaAlquileres">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

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

    <include layout="@layout/contenido_actividad_lista_alquileres" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@drawable/icono_filtro" />

</android.support.design.widget.CoordinatorLayout>```
</div>
</div>
</p>

<p><strong>Xml code of the activity where I generate the collapsingToolbar</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/detail_backdrop_height"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:fitsSystemWindows="true">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleMarginEnd="64dp" >

            <ImageView
                android:id="@+id/backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                android:fitsSystemWindows="true"
                app:layout_collapseMode="parallax"
                android:src="@drawable/jack"
                android:alpha="0.5"/>
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="170dp"
                android:layout_gravity="center">

            </RelativeLayout>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                app:layout_collapseMode="pin" />

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

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

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:paddingTop="24dp">

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/card_margin">

                <LinearLayout
                    style="@style/Widget.CardContent"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Info"
                        android:textAppearance="@style/TextAppearance.AppCompat.Title" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/lorem_ipsum" />

                </LinearLayout>

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

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/card_margin"
                android:layout_marginLeft="@dimen/card_margin"
                android:layout_marginRight="@dimen/card_margin">

                <LinearLayout
                    style="@style/Widget.CardContent"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Friends"
                        android:textAppearance="@style/TextAppearance.AppCompat.Title" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/lorem_ipsum" />

                </LinearLayout>

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

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/card_margin"
                android:layout_marginLeft="@dimen/card_margin"
                android:layout_marginRight="@dimen/card_margin">

                <LinearLayout
                    style="@style/Widget.CardContent"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Related"
                        android:textAppearance="@style/TextAppearance.AppCompat.Title" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/lorem_ipsum" />

                </LinearLayout>

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

        </LinearLayout>

    </android.support.v4.widget.NestedScrollView>

    <android.support.design.widget.FloatingActionButton
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        app:layout_anchor="@id/appbar"
        app:layout_anchorGravity="bottom|right|end"
        android:src="@drawable/ic_discuss"
        android:layout_margin="@dimen/fab_margin"
        android:clickable="true"/>

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

答:
You can add back navigation icon in the xml for Toolbar component using app:navigationIcon attribute.

```<code><android.support.v7.widget.Toolbar
    android:id="@+id/materialup.toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    app:layout_scrollFlags="scroll"
    app:navigationIcon="?homeAsUpIndicator" />
</code>```

Body:
It happens that from my main activity I call an activity in that activity that I call tale with collapsingToolbar, well everything works fine only that I can not give BACK because the collapsinToolbar does not generate a button back.

Java code of the main activity

package com.herprogramacion.alquileres;

import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.herprogramacion.alquileres.provider.Contrato.Alquileres;

public class ActividadListaAlquileres extends AppCompatActivity implements       AdaptadorAlquileres.OnItemClickListener, LoaderManager.LoaderCallbacks<Cursor> {

private RecyclerView listaUI;
private LinearLayoutManager linearLayoutManager;
private AdaptadorAlquileres adaptador;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.actividad_lista_alquileres);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Filtro...", Snackbar.LENGTH_LONG)
                    .setAction("Acción", null).show();
        }
    });

    // Preparar lista

    listaUI = (RecyclerView) findViewById(R.id.lista);

    listaUI.setHasFixedSize(true);

    linearLayoutManager = new LinearLayoutManager(this);

    listaUI.setLayoutManager(linearLayoutManager);

    adaptador = new AdaptadorAlquileres(this, this);

    listaUI.setAdapter(adaptador);

    // Iniciar loader
   getSupportLoaderManager().restartLoader(1, null, this);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_actividad_lista_alquileres, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onClick(AdaptadorAlquileres.ViewHolder holder, String idAlquiler) {
   // Snackbar.make(findViewById(android.R.id.content), ":id = " + idAlquiler,
     //       Snackbar.LENGTH_LONG).show();
}

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    return new CursorLoader(this, Alquileres.URI_CONTENIDO, null, null, null, null);
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if (adaptador != null) {
        adaptador.swapCursor(data);
    }
}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}

Java code of the activity where I generate the collapsingToolbar

package com.herprogramacion.alquileres;

import android.content.Intent;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;

public class biografia2 extends AppCompatActivity {

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

    CollapsingToolbarLayout collapsingToolbar =
            (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
    collapsingToolbar.setTitle("Titulo ");

}
}

Xml code of my main activity

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.herprogramacion.alquileres.ActividadListaAlquileres">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

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

    <include layout="@layout/contenido_actividad_lista_alquileres" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@drawable/icono_filtro" />

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

Xml code of the activity where I generate the collapsingToolbar

<?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/detail_backdrop_height"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:fitsSystemWindows="true">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleMarginEnd="64dp" >

            <ImageView
                android:id="@+id/backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                android:fitsSystemWindows="true"
                app:layout_collapseMode="parallax"
                android:src="@drawable/jack"
                android:alpha="0.5"/>
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="170dp"
                android:layout_gravity="center">

            </RelativeLayout>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                app:layout_collapseMode="pin" />

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

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

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:paddingTop="24dp">

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/card_margin">

                <LinearLayout
                    style="@style/Widget.CardContent"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Info"
                        android:textAppearance="@style/TextAppearance.AppCompat.Title" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/lorem_ipsum" />

                </LinearLayout>

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

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/card_margin"
                android:layout_marginLeft="@dimen/card_margin"
                android:layout_marginRight="@dimen/card_margin">

                <LinearLayout
                    style="@style/Widget.CardContent"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Friends"
                        android:textAppearance="@style/TextAppearance.AppCompat.Title" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/lorem_ipsum" />

                </LinearLayout>

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

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/card_margin"
                android:layout_marginLeft="@dimen/card_margin"
                android:layout_marginRight="@dimen/card_margin">

                <LinearLayout
                    style="@style/Widget.CardContent"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Related"
                        android:textAppearance="@style/TextAppearance.AppCompat.Title" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/lorem_ipsum" />

                </LinearLayout>

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

        </LinearLayout>

    </android.support.v4.widget.NestedScrollView>

    <android.support.design.widget.FloatingActionButton
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        app:layout_anchor="@id/appbar"
        app:layout_anchorGravity="bottom|right|end"
        android:src="@drawable/ic_discuss"
        android:layout_margin="@dimen/fab_margin"
        android:clickable="true"/>

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

Body:
You can add back navigation icon in the xml for Toolbar component using app:navigationIcon attribute.

<android.support.v7.widget.Toolbar
    android:id="@+id/materialup.toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    app:layout_scrollFlags="scroll"
    app:navigationIcon="?homeAsUpIndicator" />


来源: stackexchange

问:
How to get the position of cardView item in recyclerView?
I created one adapter class for recycler for populating cardview layout in recyclerview. It is working fine, but when i click cardView item in recyclerview i need to get position of that cardview item , based on that i need to write a Intent activity. Along with how to delete that cardview item when i swipe left to right.
MyAdapter class.

```<code>public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
    private NavigationItem[] navigationItem;
    private Context mContext;

    public MyAdapter(NavigationItem[] navigationItem) {
        this.navigationItem = navigationItem;
    }

    @Override
    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemLayoutView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.navigation_row_cardview, null);
        ViewHolder viewHolder = new ViewHolder(itemLayoutView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
        holder.txtViewTitle.setText(navigationItem[position].getTitle());
    }

    @Override
    public int getItemCount() {
        return navigationItem.length;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        @InjectView(R.id.hambergerRecyclerView)
        public RelativeLayout recyclerView;
        public TextView txtViewTitle;

        public ViewHolder(final View itemLayoutView) {
            super(itemLayoutView);
            ButterKnife.inject(this, itemLayoutView);
            txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.navigationItemOptionName);

            itemLayoutView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // int itemPosition = RecyclerView.getChildPosition(view);
                    int itemPosition = recyclerView.getChildAdapterPosition(view);
                    String item = navigationItem.get(itemPosition);
                    Toast.makeText(mContext, item, Toast.LENGTH_LONG).show();
                }
            });
        }
    }
}
</code>```

答:
Try this on your onBindViewHolder in adapter

```<code>myViewHolder1.itemView.setTag(new Integer(position));
</code>```

and get like this on your OnClickListener:

```<code>Integer pos;
pos = (Integer) view.getTag();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I created one adapter class for recycler for populating cardview layout in recyclerview. It is working fine, but when i click cardView item in recyclerview i need to get position of that cardview item , based on that i need to write a Intent activity. Along with how to delete that cardview item when i swipe left to right.
MyAdapter class.

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
    private NavigationItem[] navigationItem;
    private Context mContext;

    public MyAdapter(NavigationItem[] navigationItem) {
        this.navigationItem = navigationItem;
    }

    @Override
    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemLayoutView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.navigation_row_cardview, null);
        ViewHolder viewHolder = new ViewHolder(itemLayoutView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
        holder.txtViewTitle.setText(navigationItem[position].getTitle());
    }

    @Override
    public int getItemCount() {
        return navigationItem.length;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        @InjectView(R.id.hambergerRecyclerView)
        public RelativeLayout recyclerView;
        public TextView txtViewTitle;

        public ViewHolder(final View itemLayoutView) {
            super(itemLayoutView);
            ButterKnife.inject(this, itemLayoutView);
            txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.navigationItemOptionName);

            itemLayoutView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // int itemPosition = RecyclerView.getChildPosition(view);
                    int itemPosition = recyclerView.getChildAdapterPosition(view);
                    String item = navigationItem.get(itemPosition);
                    Toast.makeText(mContext, item, Toast.LENGTH_LONG).show();
                }
            });
        }
    }
}

Body:
Try this on your onBindViewHolder in adapter

myViewHolder1.itemView.setTag(new Integer(position));

and get like this on your OnClickListener:

Integer pos;
pos = (Integer) view.getTag();


问:
Google Calendar API. Handling sharedExtendedProperty for events
Following Google API I add custom properties for the specified user.
I've tried it - it works for me in general. I can add String properties and String values. Also I was successful with loading correspond data from Google if property value completely matched. Format to specify criteria for shared properties is (similar for private):

```<code>  /**
   * Extended properties constraint specified as propertyName=value. Matches only shared
   * properties. This parameter might be repeated multiple times to return events that match all
   * given constraints.
   */
  public List setSharedExtendedProperty(java.util.List<java.lang.String> sharedExtendedProperty) {
    this.sharedExtendedProperty = sharedExtendedProperty;
    return this;
  }
</code>```

Right now I need have a collection in Google properties for publicCase property. And after that I should be able match one with correspond criteria request. Is it possible find in Google calendar events that contain publicCase custom property where publicCase in ["valueCollection"]? If Its possible please share for me correspond information.

Another question. Is it possible specify condition matching subSting of property value?

How I can specify OR rule in request? Is it possible?

PS

As Google client I use google-api-services-calendar-v3-rev225-1.22.0.jar. I would be happy if any correct example (java, js, pyton and other) or API documentation that answers my questions.

答:
I haven't got perfect solution provided by Google, but I used workaround that uses functionality provided by Google.

If I can't use complex condition to match field value by inRage or subValue or else, solution is based on building smart field names. For example, I need add crmCollection field filled in by data, but Google API provides me to add string value only. I would convert the collection into json and I'd represent it as string in this way custom field would be added but I'll not be able to search any calendar events by it. So collection should be separated on single elements. It's easy to split it on single elements if elements can be named in different way. In current case it almost impossible and workaround is to add at the end of field name special marker (each data element has an unique field like id which can be used in custom field name building). In the very end using same rule I've got ability build search requests using each custom property:

```<code>Map <String, String> (key | value)
-----------------------------------
"crmCollection" | "[crmObject1, crmObject2, crmObject3 ...]" (in json representation)
</code>```

transformed into:

```<code>Map <String, String> (key | value)
-----------------------------------
"crmCollectionIdOfFirstObject"  | "true"
"crmCollectionIdOfSecondObject" | "true"
"crmCollectionIdOfThirdObject"  | "true"
</code>```

the real objects i have in my storage, but in Google I've specified links on my objects to be loaded by need.

PS

I've considered a few other workarounds, but I've not published them because I think this one is the best of all of them. Anyway I open to consider other solutions (better ideas or missed Google API).

Body:
Following Google API I add custom properties for the specified user.
I've tried it - it works for me in general. I can add String properties and String values. Also I was successful with loading correspond data from Google if property value completely matched. Format to specify criteria for shared properties is (similar for private):

  /**
   * Extended properties constraint specified as propertyName=value. Matches only shared
   * properties. This parameter might be repeated multiple times to return events that match all
   * given constraints.
   */
  public List setSharedExtendedProperty(java.util.List<java.lang.String> sharedExtendedProperty) {
    this.sharedExtendedProperty = sharedExtendedProperty;
    return this;
  }

Right now I need have a collection in Google properties for publicCase property. And after that I should be able match one with correspond criteria request. Is it possible find in Google calendar events that contain publicCase custom property where publicCase in ["valueCollection"]? If Its possible please share for me correspond information.

Another question. Is it possible specify condition matching subSting of property value?

How I can specify OR rule in request? Is it possible?

PS

As Google client I use google-api-services-calendar-v3-rev225-1.22.0.jar. I would be happy if any correct example (java, js, pyton and other) or API documentation that answers my questions.

Body:
I haven't got perfect solution provided by Google, but I used workaround that uses functionality provided by Google.

If I can't use complex condition to match field value by inRage or subValue or else, solution is based on building smart field names. For example, I need add crmCollection field filled in by data, but Google API provides me to add string value only. I would convert the collection into json and I'd represent it as string in this way custom field would be added but I'll not be able to search any calendar events by it. So collection should be separated on single elements. It's easy to split it on single elements if elements can be named in different way. In current case it almost impossible and workaround is to add at the end of field name special marker (each data element has an unique field like id which can be used in custom field name building). In the very end using same rule I've got ability build search requests using each custom property:

Map <String, String> (key | value)
-----------------------------------
"crmCollection" | "[crmObject1, crmObject2, crmObject3 ...]" (in json representation)

transformed into:

Map <String, String> (key | value)
-----------------------------------
"crmCollectionIdOfFirstObject"  | "true"
"crmCollectionIdOfSecondObject" | "true"
"crmCollectionIdOfThirdObject"  | "true"

the real objects i have in my storage, but in Google I've specified links on my objects to be loaded by need.

PS

I've considered a few other workarounds, but I've not published them because I think this one is the best of all of them. Anyway I open to consider other solutions (better ideas or missed Google API).


问:
How to set weight attribute dynamically from Kotlin code?
How can I set the value for the attribute layout_weight for LinerLayout in android dynamically from Kotlin code ?

```<code>var orange : LinearLayout = findViewById(R.id.orangeLineFiveStars) as LinearLayout
</code>```

Is it right code ? [It doesn't work in my app]

```<code>    var orangeParams : LinearLayout.LayoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)

    orangeParams.weight = 0.33f
    orange.layoutParams = orangeParams
</code>```

This code doesn't work too

```<code>var orange.layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT,0.33f)
</code>```

XML :

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.sanke.ilafedoseev.raitmyworkstatistic.MainActivity">

    <LinearLayout
        android:layout_margin="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/orangeLineFiveStars"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="4dp"
            android:background="#febe40"
            android:orientation="horizontal"/>

        <LinearLayout
            android:id="@+id/whiteLineFiveStars"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"/>

    </LinearLayout>
</LinearLayout>
</code>```

答:
You cant try something like this:

```<code>    yourView.layoutParams.apply {
         (this as LinearLayout.LayoutParams).weight = .33f //your value for weight

    }.requestLayout()
</code>```

Or

```<code>val param = yourView.cardView.layoutParams as LinearLayout.LayoutParams
param.weight = .33f
yourView.layoutParams = param
</code>```

Body:
How can I set the value for the attribute layout_weight for LinerLayout in android dynamically from Kotlin code ?

var orange : LinearLayout = findViewById(R.id.orangeLineFiveStars) as LinearLayout

Is it right code ? [It doesn't work in my app]

    var orangeParams : LinearLayout.LayoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)

    orangeParams.weight = 0.33f
    orange.layoutParams = orangeParams

This code doesn't work too

var orange.layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT,0.33f)

XML :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.sanke.ilafedoseev.raitmyworkstatistic.MainActivity">

    <LinearLayout
        android:layout_margin="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/orangeLineFiveStars"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="4dp"
            android:background="#febe40"
            android:orientation="horizontal"/>

        <LinearLayout
            android:id="@+id/whiteLineFiveStars"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"/>

    </LinearLayout>
</LinearLayout>

Body:
You cant try something like this:

    yourView.layoutParams.apply {
         (this as LinearLayout.LayoutParams).weight = .33f //your value for weight

    }.requestLayout()

Or

val param = yourView.cardView.layoutParams as LinearLayout.LayoutParams
param.weight = .33f
yourView.layoutParams = param


问:
Cant access apprtc from another machine in same network
Iam new in webRtc. I need to run appRtc application on my local machine. I got the codebase from github and successfully run on my local ubuntu machine.

these are logs when try with browser on my pc

```<code>INFO     2017-11-30 09:00:18,966 api_server.py:205] Starting API server at: http://localhost:51242
WARNING  2017-11-30 09:00:18,976 inotify_file_watcher.py:196] There are too many directories in your application for changes in all of them to be monitored. You may have to restart the development server to see some changes to your files.
INFO     2017-11-30 09:00:18,976 dispatcher.py:197] Starting module "default" running at: http://localhost:8080
INFO     2017-11-30 09:00:18,978 admin_server.py:116] Starting admin server at: http://localhost:8000
INFO     2017-11-30 09:00:43,290 apprtc.py:93] Applying media constraints: {'video': {'mandatory': {}, 'optional': [{'minWidth': '1280'}, {'minHeight': '720'}]}, 'audio': True}
WARNING  2017-11-30 09:00:43,299 apprtc.py:137] Invalid or no value returned from memcache, using fallback: null
INFO     2017-11-30 09:00:43,370 module.py:788] default: "GET / HTTP/1.1" 200 8616
INFO     2017-11-30 09:00:43,430 module.py:788] default: "GET /callstats/callstats.min.js HTTP/1.1" 304 -
INFO     2017-11-30 09:00:43,433 module.py:788] default: "GET /css/main.css HTTP/1.1" 304 -
INFO     2017-11-30 09:00:43,491 module.py:788] default: "GET /js/apprtc.debug.js HTTP/1.1" 304 -
INFO     2017-11-30 09:00:47,736 apprtc.py:417] Added client 02588444 in room 490664053, retries = 0
INFO     2017-11-30 09:00:47,738 apprtc.py:93] Applying media constraints: {'video': {'mandatory': {}, 'optional': [{'minWidth': '1280'}, {'minHeight': '720'}]}, 'audio': True}
WARNING  2017-11-30 09:00:47,746 apprtc.py:137] Invalid or no value returned from memcache, using fallback: null
INFO     2017-11-30 09:00:47,748 apprtc.py:560] User 02588444 joined room 490664053
INFO     2017-11-30 09:00:47,751 apprtc.py:561] Room 490664053 has state ['02588444']
INFO     2017-11-30 09:00:47,902 module.py:788] default: "POST /join/490664053 HTTP/1.1" 200 1199
INFO     2017-11-30 09:00:49,820 apprtc.py:485] Saved message for client 02588444:{True, 1} in room 490664053, retries=0
INFO     2017-11-30 09:00:49,833 module.py:788] default: "POST /message/490664053/02588444 HTTP/1.1" 200 21
INFO     2017-11-30 09:00:49,880 apprtc.py:485] Saved message for client 02588444:{True, 2} in room 490664053, retries=0
INFO     2017-11-30 09:00:49,894 module.py:788] default: "POST /message/490664053/02588444 HTTP/1.1" 200 21
INFO     2017-11-30 09:00:49,930 apprtc.py:485] Saved message for client 02588444:{True, 3} in room 490664053, retries=0
INFO     2017-11-30 09:00:49,958 module.py:788] default: "POST /message/490664053/02588444 HTTP/1.1" 200 21
INFO     2017-11-30 09:00:49,970 apprtc.py:485] Saved message for client 02588444:{True, 4} in room 490664053, retries=0
INFO     2017-11-30 09:00:49,982 module.py:788] default: "POST /message/490664053/02588444 HTTP/1.1" 200 21
INFO     2017-11-30 09:00:50,074 apprtc.py:485] Saved message for client 02588444:{True, 5} in room 490664053, retries=0
INFO     2017-11-30 09:00:50,084 module.py:788] default: "POST /message/490664053/02588444 HTTP/1.1" 200 21
</code>```

I can open apprtc application on my browser. But i canot access from any other machine in same network.

these are the logs when try with browser on any other pc in same network.

```<code>INFO     2017-11-30 08:55:06,749 api_server.py:205] Starting API server at: http://localhost:55410
    WARNING  2017-11-30 08:55:06,758 inotify_file_watcher.py:196] There are too many directories in your application for changes in all of them to be monitored. You may have to restart the development server to see some changes to your files.
    INFO     2017-11-30 08:55:06,759 dispatcher.py:197] Starting module "default" running at: http://localhost:8080
    INFO     2017-11-30 08:55:06,760 admin_server.py:116] Starting admin server at: http://localhost:8000
    INFO     2017-11-30 08:55:10,582 apprtc.py:93] Applying media constraints: {'audio': True, 'video': {'optional': [{'minWidth': '1280'}, {'minHeight': '720'}], 'mandatory': {}}}
    WARNING  2017-11-30 08:55:10,589 apprtc.py:137] Invalid or no value returned from memcache, using fallback: null
    INFO     2017-11-30 08:55:10,636 module.py:788] default: "GET / HTTP/1.1" 200 8616
    INFO     2017-11-30 08:55:10,685 module.py:788] default: "GET /css/main.css HTTP/1.1" 200 6402
    INFO     2017-11-30 08:55:10,689 module.py:788] default: "GET /callstats/callstats.min.js HTTP/1.1" 200 245432
    INFO     2017-11-30 08:55:10,696 module.py:788] default: "GET /js/apprtc.debug.js HTTP/1.1" 200 101567
    INFO     2017-11-30 08:55:11,086 module.py:788] default: "GET /images/webrtc-icon-192x192.png HTTP/1.1" 200 31806
    INFO     2017-11-30 08:55:18,872 apprtc.py:417] Added client 26553344 in room 419183955, retries = 0
    INFO     2017-11-30 08:55:18,874 apprtc.py:93] Applying media constraints: {'audio': True, 'video': {'optional': [{'minWidth': '1280'}, {'minHeight': '720'}], 'mandatory': {}}}
    WARNING  2017-11-30 08:55:18,879 apprtc.py:137] Invalid or no value returned from memcache, using fallback: null
    INFO     2017-11-30 08:55:18,880 apprtc.py:560] User 26553344 joined room 419183955
    INFO     2017-11-30 08:55:18,881 apprtc.py:561] Room 419183955 has state ['26553344']
    INFO     2017-11-30 08:55:18,896 module.py:788] default: "POST /join/419183955 HTTP/1.1" 200 1203
    INFO     2017-11-30 08:55:24,331 module.py:788] default: "GET /images/webrtc-icon-192x192.png HTTP/1.1" 304 -
    INFO     2017-11-30 08:55:24,363 apprtc.py:485] Saved message for client 26553344:{True, 1} in room 419183955, retries=0
    INFO     2017-11-30 08:55:24,383 module.py:788] default: "POST /message/419183955/26553344 HTTP/1.1" 200 21
    INFO     2017-11-30 08:55:24,396 apprtc.py:485] Saved message for client 26553344:{True, 2} in room 419183955, retries=1
    INFO     2017-11-30 08:55:24,405 module.py:788] default: "POST /message/419183955/26553344 HTTP/1.1" 200 21
    INFO     2017-11-30 08:55:58,211 apprtc.py:455] Removed client 26553344 from room 419183955, retries=0
    INFO     2017-11-30 08:55:58,212 apprtc.py:494] Room 419183955 has state None
    INFO     2017-11-30 08:55:58,221 module.py:788] default: "POST /leave/419183955/26553344 HTTP/1.1" 200 -
    INFO     2017-11-30 08:55:59,071 module.py:788] default: "GET /r/ HTTP/1.1" 404 154
    INFO     2017-11-30 08:56:00,542 module.py:788] default: "GET /favicon.ico HTTP/1.1" 404 154
</code>```

The browser shows some error message like this

```<code>Failed to get access to local media. Error name was NotSupportedError. Continuing without sending a stream.
</code>```

Why this behaviour? i need to access from other pc. is this possible?

答: Please do enable SSL. The access will only work with SSL</p>

Body:
Iam new in webRtc. I need to run appRtc application on my local machine. I got the codebase from github and successfully run on my local ubuntu machine.

these are logs when try with browser on my pc

INFO     2017-11-30 09:00:18,966 api_server.py:205] Starting API server at: http://localhost:51242
WARNING  2017-11-30 09:00:18,976 inotify_file_watcher.py:196] There are too many directories in your application for changes in all of them to be monitored. You may have to restart the development server to see some changes to your files.
INFO     2017-11-30 09:00:18,976 dispatcher.py:197] Starting module "default" running at: http://localhost:8080
INFO     2017-11-30 09:00:18,978 admin_server.py:116] Starting admin server at: http://localhost:8000
INFO     2017-11-30 09:00:43,290 apprtc.py:93] Applying media constraints: {'video': {'mandatory': {}, 'optional': [{'minWidth': '1280'}, {'minHeight': '720'}]}, 'audio': True}
WARNING  2017-11-30 09:00:43,299 apprtc.py:137] Invalid or no value returned from memcache, using fallback: null
INFO     2017-11-30 09:00:43,370 module.py:788] default: "GET / HTTP/1.1" 200 8616
INFO     2017-11-30 09:00:43,430 module.py:788] default: "GET /callstats/callstats.min.js HTTP/1.1" 304 -
INFO     2017-11-30 09:00:43,433 module.py:788] default: "GET /css/main.css HTTP/1.1" 304 -
INFO     2017-11-30 09:00:43,491 module.py:788] default: "GET /js/apprtc.debug.js HTTP/1.1" 304 -
INFO     2017-11-30 09:00:47,736 apprtc.py:417] Added client 02588444 in room 490664053, retries = 0
INFO     2017-11-30 09:00:47,738 apprtc.py:93] Applying media constraints: {'video': {'mandatory': {}, 'optional': [{'minWidth': '1280'}, {'minHeight': '720'}]}, 'audio': True}
WARNING  2017-11-30 09:00:47,746 apprtc.py:137] Invalid or no value returned from memcache, using fallback: null
INFO     2017-11-30 09:00:47,748 apprtc.py:560] User 02588444 joined room 490664053
INFO     2017-11-30 09:00:47,751 apprtc.py:561] Room 490664053 has state ['02588444']
INFO     2017-11-30 09:00:47,902 module.py:788] default: "POST /join/490664053 HTTP/1.1" 200 1199
INFO     2017-11-30 09:00:49,820 apprtc.py:485] Saved message for client 02588444:{True, 1} in room 490664053, retries=0
INFO     2017-11-30 09:00:49,833 module.py:788] default: "POST /message/490664053/02588444 HTTP/1.1" 200 21
INFO     2017-11-30 09:00:49,880 apprtc.py:485] Saved message for client 02588444:{True, 2} in room 490664053, retries=0
INFO     2017-11-30 09:00:49,894 module.py:788] default: "POST /message/490664053/02588444 HTTP/1.1" 200 21
INFO     2017-11-30 09:00:49,930 apprtc.py:485] Saved message for client 02588444:{True, 3} in room 490664053, retries=0
INFO     2017-11-30 09:00:49,958 module.py:788] default: "POST /message/490664053/02588444 HTTP/1.1" 200 21
INFO     2017-11-30 09:00:49,970 apprtc.py:485] Saved message for client 02588444:{True, 4} in room 490664053, retries=0
INFO     2017-11-30 09:00:49,982 module.py:788] default: "POST /message/490664053/02588444 HTTP/1.1" 200 21
INFO     2017-11-30 09:00:50,074 apprtc.py:485] Saved message for client 02588444:{True, 5} in room 490664053, retries=0
INFO     2017-11-30 09:00:50,084 module.py:788] default: "POST /message/490664053/02588444 HTTP/1.1" 200 21

I can open apprtc application on my browser. But i canot access from any other machine in same network.

these are the logs when try with browser on any other pc in same network.

INFO     2017-11-30 08:55:06,749 api_server.py:205] Starting API server at: http://localhost:55410
    WARNING  2017-11-30 08:55:06,758 inotify_file_watcher.py:196] There are too many directories in your application for changes in all of them to be monitored. You may have to restart the development server to see some changes to your files.
    INFO     2017-11-30 08:55:06,759 dispatcher.py:197] Starting module "default" running at: http://localhost:8080
    INFO     2017-11-30 08:55:06,760 admin_server.py:116] Starting admin server at: http://localhost:8000
    INFO     2017-11-30 08:55:10,582 apprtc.py:93] Applying media constraints: {'audio': True, 'video': {'optional': [{'minWidth': '1280'}, {'minHeight': '720'}], 'mandatory': {}}}
    WARNING  2017-11-30 08:55:10,589 apprtc.py:137] Invalid or no value returned from memcache, using fallback: null
    INFO     2017-11-30 08:55:10,636 module.py:788] default: "GET / HTTP/1.1" 200 8616
    INFO     2017-11-30 08:55:10,685 module.py:788] default: "GET /css/main.css HTTP/1.1" 200 6402
    INFO     2017-11-30 08:55:10,689 module.py:788] default: "GET /callstats/callstats.min.js HTTP/1.1" 200 245432
    INFO     2017-11-30 08:55:10,696 module.py:788] default: "GET /js/apprtc.debug.js HTTP/1.1" 200 101567
    INFO     2017-11-30 08:55:11,086 module.py:788] default: "GET /images/webrtc-icon-192x192.png HTTP/1.1" 200 31806
    INFO     2017-11-30 08:55:18,872 apprtc.py:417] Added client 26553344 in room 419183955, retries = 0
    INFO     2017-11-30 08:55:18,874 apprtc.py:93] Applying media constraints: {'audio': True, 'video': {'optional': [{'minWidth': '1280'}, {'minHeight': '720'}], 'mandatory': {}}}
    WARNING  2017-11-30 08:55:18,879 apprtc.py:137] Invalid or no value returned from memcache, using fallback: null
    INFO     2017-11-30 08:55:18,880 apprtc.py:560] User 26553344 joined room 419183955
    INFO     2017-11-30 08:55:18,881 apprtc.py:561] Room 419183955 has state ['26553344']
    INFO     2017-11-30 08:55:18,896 module.py:788] default: "POST /join/419183955 HTTP/1.1" 200 1203
    INFO     2017-11-30 08:55:24,331 module.py:788] default: "GET /images/webrtc-icon-192x192.png HTTP/1.1" 304 -
    INFO     2017-11-30 08:55:24,363 apprtc.py:485] Saved message for client 26553344:{True, 1} in room 419183955, retries=0
    INFO     2017-11-30 08:55:24,383 module.py:788] default: "POST /message/419183955/26553344 HTTP/1.1" 200 21
    INFO     2017-11-30 08:55:24,396 apprtc.py:485] Saved message for client 26553344:{True, 2} in room 419183955, retries=1
    INFO     2017-11-30 08:55:24,405 module.py:788] default: "POST /message/419183955/26553344 HTTP/1.1" 200 21
    INFO     2017-11-30 08:55:58,211 apprtc.py:455] Removed client 26553344 from room 419183955, retries=0
    INFO     2017-11-30 08:55:58,212 apprtc.py:494] Room 419183955 has state None
    INFO     2017-11-30 08:55:58,221 module.py:788] default: "POST /leave/419183955/26553344 HTTP/1.1" 200 -
    INFO     2017-11-30 08:55:59,071 module.py:788] default: "GET /r/ HTTP/1.1" 404 154
    INFO     2017-11-30 08:56:00,542 module.py:788] default: "GET /favicon.ico HTTP/1.1" 404 154

The browser shows some error message like this

Failed to get access to local media. Error name was NotSupportedError. Continuing without sending a stream.

Why this behaviour? i need to access from other pc. is this possible?


问:
Angular4 sharing data to child component
I have a parent component that invokes an API and gets the data returned.
It has a loop like this:

```<code><div *ngIf="campaign">
    <div *ngFor="let question of campaign.questions" bzQuestion></div>
</div>
</code>```

You can see that I have another component called bzQuestion that repeats itself. I want to pass the data (question) to that component. I watched a video saying you can use @Input(), so I did this:

```<code>import { Component, OnInit, Input } from '@angular/core';
import { IQuestion } from '../data/models/question.model';

@Component({
  selector: 'bz-question',
  templateUrl: './question.component.html',
  styleUrls: ['./question.component.scss'],
  providers: [ ]
})
export class QuestionComponent {
  @Input() public question: IQuestion;
}
</code>```

I tried to then add the question to the child component by doing this to the parent:

```<code><div *ngIf="campaign">
    <div *ngFor="let question of campaign.questions" [question]="question" bzQuestion></div>
</div>
</code>```

But the compiler moans saying:

Can't bind to 'question' since it isn't a known property of 'div'. ("

Does anyone know what I am doing wrong?

答:
You need to do it in component, not div. Component selector is app-bzQuestion, or something like that, u can find that in .ts file of your component.</p>

```<code><div *ngIf="campaign">
    <app-bzQuestion *ngFor="let question of campaign.questions" [question]="question"></app-bzQuestion>
</div>
</code>```

Body:
I have a parent component that invokes an API and gets the data returned.
It has a loop like this:

You can see that I have another component called bzQuestion that repeats itself. I want to pass the data (question) to that component. I watched a video saying you can use @Input(), so I did this:

import { Component, OnInit, Input } from '@angular/core';
import { IQuestion } from '../data/models/question.model';

@Component({
  selector: 'bz-question',
  templateUrl: './question.component.html',
  styleUrls: ['./question.component.scss'],
  providers: [ ]
})
export class QuestionComponent {
  @Input() public question: IQuestion;
}

I tried to then add the question to the child component by doing this to the parent:

But the compiler moans saying:

Can't bind to 'question' since it isn't a known property of 'div'. ("

Does anyone know what I am doing wrong?

Body:
You need to do it in component, not div. Component selector is app-bzQuestion, or something like that, u can find that in .ts file of your component.

<div *ngIf="campaign">
    <app-bzQuestion *ngFor="let question of campaign.questions" [question]="question"></app-bzQuestion>
</div>


答:
First: a nitpick: k-Means is not a hierarchical clustering algorithm, see https://www.quora.com/What-is-the-difference-between-k-means-and-hierarchical-clustering for details o the difference.

Second: you don't want to convert a distance matrix back to the points it originated from as you take a step back. Sadly the k-Means implementation you linked only has an API that allows you to enter raw coordinates and assumes Euclidean distance, therefore you have some possibilities, depending on your requirements:

Where do you get the distance matrix from? If it is possible, get the raw coordinates (and make sure the distance measure is euclidean distance) and use the library you linked.

Override the Point class in the library you linked: specifically the getDistanceWith method to return values from your matrix

If you only need to calculate the cluster once, use python and sklearn. This library does exactly what you want. Especially: https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.cluster.hierarchy.linkage.html

Write your own code: clustering is quite an easy topic and therefore it is a nice coding exercise.

Title: How can I get clusters from distance matrix, using PHP?

Body:
I have distance matrix as two-dimensional array, like this:

So, I need to find clusters, of elements with its help. I can do it, using hierarchic clusterization, like k-means. I have found such example here PHP K-Means

How can I convert my two-dimensional array into array of points, listed in this example?

$points = [
[80,55],[86,59],[19,85],[41,47],[57,58],
[76,22],[94,60],[13,93],[90,48],[52,54],
[62,46],[88,44],[85,24],[63,14],[51,40],
[75,31],[86,62],[81,95],[47,22],[43,95],
[71,19],[17,65],[69,21],[59,60],[59,12],
[15,22],[49,93],[56,35],[18,20],[39,59],
[50,15],[81,36],[67,62],[32,15],[75,65],
[10,47],[75,18],[13,45],[30,62],[95,79],
[64,11],[92,14],[94,49],[39,13],[60,68],
[62,10],[74,44],[37,42],[97,60],[47,73],
];


问:
Hexadecimal entities are changed in UTF characters
In my XML some hexa decimal entities are there when i am transforming its changed into UTF - 8.

INPUT FILE:

```<code><?xml version="1.0" encoding="UTF-8"?>
<root>
    <a>a text.</a>
    <b>b – text.</b>
</root>
</code>```

My XSLT:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">

    <xsl:output method="xml"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>
</code>```

CURRENT OUTPUT:

```<code><root>
    <a>a text.</a>
    <b>b – text.</b>
</root>
</code>```

DESIRED OUTPUT:

```<code><?xml version="1.0" encoding="UTF-8"?>
<root>
    <a>a text.</a>
    <b>b – text.</b>
</root>
</code>```

答:
It would be useful to know WHY you need this, because different techniques might or might not meet your requirement.

One approach is to specify US-ASCII as the output encoding. Then all non-ASCII characters will appear as numeric entities (character references) in the output. Unfortunately this also means you can't use non-ASCII characters in element or attribute names.

Body:
In my XML some hexa decimal entities are there when i am transforming its changed into UTF - 8.

INPUT FILE:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    a text.
    b – text.
</root>

My XSLT:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">

    <xsl:output method="xml"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

CURRENT OUTPUT:

<root>
    a text.
    b – text.
</root>

DESIRED OUTPUT:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    a text.
    b – text.
</root>


问:
npm request moudule not giving the output
Why when I run the npm request module the output I get is undefined?

```<code>const request = require('request');
request({
  url: 'https://maps.googleapis.com/maps/api/geocode/json?address=1301%20lombard%20street%20philadelphia',
  json: true
  }, (error, response, body) => {
     console.log(body);
});
</code>```

答:
I checked for proxy using
 env|grep -i proxy
and then unset proxy for http_proxy or other proxies which is set.The command for that is:unset http_proxy</p>

Body:
Why when I run the npm request module the output I get is undefined?

const request = require('request');
request({
  url: 'https://maps.googleapis.com/maps/api/geocode/json?address=1301%20lombard%20street%20philadelphia',
  json: true
  }, (error, response, body) => {
     console.log(body);
});


问:
Pass object to javascript function in dynamically generated html
I have run into a problem along these lines a couple of times now and rather than create a 'hack' work around I thought it best to ask is there a better way to handle a situation like this.

I am using angular datatables and on the datatable we have a cell with a clickable id which brings up a bootstrap modal.

I would like to pass in the full object of the item in the row on an ng-click action however it doesn't seem to work and I think it's caused by the object being awkwardly passed into the function which is some dynamically generated html:

Datatable:

```<code>$scope.dtColumns = [DTColumnBuilder.newColumn('Id').withTitle('Id').renderWith(CommonService.renderId),
                            DTColumnBuilder.newColumn('status').withTitle('Status').renderWith(CommonService.renderStatus),
                            DTColumnBuilder.newColumn('description').withTitle('Description').renderWith(CommonService.renderLength),
                            DTColumnBuilder.newColumn('rating').withTitle('Rating').withOption('type', 'rating'),
                            DTColumnBuilder.newColumn('date').withTitle('Date'),
                            DTColumnBuilder.newColumn("category").withTitle('Category').renderWith(CommonService.renderLength),
                            DTColumnBuilder.newColumn("subcategory").withTitle('Sub Category').renderWith(CommonService.renderLength)];
</code>```

CommonService:

```<code>function renderId(data, type, full, meta){

        var render = "ID-"+data;

        //'hack' function to store object for later lookup
        setObjectForModal(full);

        //Dynamically generated html to apply link on id with ng-click function which passes in 'full' object

        var html = ' <span class="link" ng-click="showModal('+full+')" > ' + render + ' </span> ';

        return html;
    }
</code>```

As you can see showModal('+full+') i believe appending the object this way is rendering it strangely in the html it displays as showModal([Object object]) is there any way to get this to work as currently clicking on this link does nothing, but passing in the id as an int raises the modal fine.

As a further similar experience I also noticed this same issue in my protractor testing. Saying:

```<code>expect('ID-'+id).toEqual(ID-123456);
</code>```

produces an error along the lines of ID-[Object object] is not equal to ID-123456.

Is there some string concatenation issue I'm causing and is there a way to prevent it?

Thanks!

答:
By pure chance I found the solution to this problem. Basically comes down to dynamic html rendering, to pass an object like above you must use JSON.Stringify() to convert to [Object object] into a json string which you can read the properties off.

```<code>function renderId(data, type, full, meta){

    var render = "ID-"+data;

    //'hack' function to store object for later lookup
    setObjectForModal(full);

    //Dynamically generated html to apply link on id with ng-click function which passes in 'full' object

    var html = ' <span class="link" ng-click="showModal('+ JSON.stringify(full) +')" > ' + render + ' </span> ';

    return html;
}
</code>```

Hope this helps someone.

Body:
I have run into a problem along these lines a couple of times now and rather than create a 'hack' work around I thought it best to ask is there a better way to handle a situation like this.

I am using angular datatables and on the datatable we have a cell with a clickable id which brings up a bootstrap modal.

I would like to pass in the full object of the item in the row on an ng-click action however it doesn't seem to work and I think it's caused by the object being awkwardly passed into the function which is some dynamically generated html:

Datatable:

$scope.dtColumns = [DTColumnBuilder.newColumn('Id').withTitle('Id').renderWith(CommonService.renderId),
                            DTColumnBuilder.newColumn('status').withTitle('Status').renderWith(CommonService.renderStatus),
                            DTColumnBuilder.newColumn('description').withTitle('Description').renderWith(CommonService.renderLength),
                            DTColumnBuilder.newColumn('rating').withTitle('Rating').withOption('type', 'rating'),
                            DTColumnBuilder.newColumn('date').withTitle('Date'),
                            DTColumnBuilder.newColumn("category").withTitle('Category').renderWith(CommonService.renderLength),
                            DTColumnBuilder.newColumn("subcategory").withTitle('Sub Category').renderWith(CommonService.renderLength)];

CommonService:

function renderId(data, type, full, meta){

        var render = "ID-"+data;

        //'hack' function to store object for later lookup
        setObjectForModal(full);

        //Dynamically generated html to apply link on id with ng-click function which passes in 'full' object

        var html = '  ' + render + '  ';

        return html;
    }

As you can see showModal('+full+') i believe appending the object this way is rendering it strangely in the html it displays as showModal([Object object]) is there any way to get this to work as currently clicking on this link does nothing, but passing in the id as an int raises the modal fine.

As a further similar experience I also noticed this same issue in my protractor testing. Saying:

expect('ID-'+id).toEqual(ID-123456);

produces an error along the lines of ID-[Object object] is not equal to ID-123456.

Is there some string concatenation issue I'm causing and is there a way to prevent it?

Thanks!

Body:
By pure chance I found the solution to this problem. Basically comes down to dynamic html rendering, to pass an object like above you must use JSON.Stringify() to convert to [Object object] into a json string which you can read the properties off.

function renderId(data, type, full, meta){

    var render = "ID-"+data;

    //'hack' function to store object for later lookup
    setObjectForModal(full);

    //Dynamically generated html to apply link on id with ng-click function which passes in 'full' object

    var html = ' <span class="link" ng-click="showModal('+ JSON.stringify(full) +')" > ' + render + ' </span> ';

    return html;
}

Hope this helps someone.


问:
Linq lambda query to select child and specify parent data
I have two tables, User and Group. I need to select user table and name of the group through lambda expression, and the return type of the method is User table

Below is my schema structure for user

Below is my schema structure for Group table

答:
Try something like;</p>

```<code>        var query = yourContext.Users.Select(user => new
        {
            User = user,
            GroupName = user.Group.Name
        });
</code>```

Body:
Try something like;

        var query = yourContext.Users.Select(user => new
        {
            User = user,
            GroupName = user.Group.Name
        });


问:
Sum aggregation for each columns in cassandra
I have a Data model like below,

```<code>CREATE TABLE appstat.nodedata (
    nodeip text,
    timestamp timestamp,
    flashmode text,
    physicalusage int,
    readbw int,
    readiops int,
    totalcapacity int,
    writebw int,
    writeiops int,
    writelatency int,
    PRIMARY KEY (nodeip, timestamp)
) WITH CLUSTERING ORDER BY (timestamp DESC)
</code>```

where, nodeip - primary key and timestamp - clustering key (Sorted by descinding oder to get the latest),

Sample data in this table,

```<code>SELECT * from nodedata WHERE nodeip = '172.30.56.60' LIMIT 2;

 nodeip       | timestamp                       | flashmode | physicalusage | readbw | readiops | totalcapacity | writebw | writeiops | writelatency
--------------+---------------------------------+-----------+---------------+--------+----------+---------------+---------+-----------+--------------
 172.30.56.60 | 2017-12-08 06:13:07.161000+0000 |       yes |            34 |     57 |       19 |            27 |       8 |        89 |           57
 172.30.56.60 | 2017-12-08 06:12:07.161000+0000 |       yes |            70 |      6 |       43 |            88 |      79 |        83 |           89
</code>```

This is properly available and whenever I need to get the statistics I am able to get the data using the partition key like below,

(The above logic seems similar to my previous question : Aggregation in Cassandra across partitions) but expectation is different,

I have value for each column (like readbw, latency etc.,) populated for every one minute in all the 4 nodes.

Now, If I need to get the max value for a column (Example : readbw), It is possible using the following query,

```<code>SELECT max(readbw) FROM nodedata WHERE nodeip IN ('172.30.56.60','172.30.56.61','172.30.56.60','172.30.56.63') AND timestamp < 1512652272989 AND timestamp > 1512537899000;
</code>```

1) First question : Is there a way to perform max aggregation on all nodes of a column (readbw) without using IN query?

2) Second question : Is there a way in Cassandra, whenever I insert the data in Node 1, Node 2, Node 3 and Node 4.
It needs to be aggregated and stored in another table. So that I will collect the aggregated value of each column from the aggregated table.

If any of my point is not clear, please let me know.

Thanks,

Harry

答: If you are dse Cassandra you can enable spark and write the aggregation queries </p>

Body:
I have a Data model like below,

CREATE TABLE appstat.nodedata (
    nodeip text,
    timestamp timestamp,
    flashmode text,
    physicalusage int,
    readbw int,
    readiops int,
    totalcapacity int,
    writebw int,
    writeiops int,
    writelatency int,
    PRIMARY KEY (nodeip, timestamp)
) WITH CLUSTERING ORDER BY (timestamp DESC)

where, nodeip - primary key and timestamp - clustering key (Sorted by descinding oder to get the latest),

Sample data in this table,

SELECT * from nodedata WHERE nodeip = '172.30.56.60' LIMIT 2;

 nodeip       | timestamp                       | flashmode | physicalusage | readbw | readiops | totalcapacity | writebw | writeiops | writelatency
--------------+---------------------------------+-----------+---------------+--------+----------+---------------+---------+-----------+--------------
 172.30.56.60 | 2017-12-08 06:13:07.161000+0000 |       yes |            34 |     57 |       19 |            27 |       8 |        89 |           57
 172.30.56.60 | 2017-12-08 06:12:07.161000+0000 |       yes |            70 |      6 |       43 |            88 |      79 |        83 |           89

This is properly available and whenever I need to get the statistics I am able to get the data using the partition key like below,

(The above logic seems similar to my previous question : Aggregation in Cassandra across partitions) but expectation is different,

I have value for each column (like readbw, latency etc.,) populated for every one minute in all the 4 nodes.

Now, If I need to get the max value for a column (Example : readbw), It is possible using the following query,

SELECT max(readbw) FROM nodedata WHERE nodeip IN ('172.30.56.60','172.30.56.61','172.30.56.60','172.30.56.63') AND timestamp < 1512652272989 AND timestamp > 1512537899000;

1) First question : Is there a way to perform max aggregation on all nodes of a column (readbw) without using IN query?

2) Second question : Is there a way in Cassandra, whenever I insert the data in Node 1, Node 2, Node 3 and Node 4.
It needs to be aggregated and stored in another table. So that I will collect the aggregated value of each column from the aggregated table.

If any of my point is not clear, please let me know.

Thanks,

Harry


问:
Prevent JQuery Datatables from keeping old data in the table after being destroyed
Good day

Painting the scenario:
I have a scenario I am working on for work, where I had to freeze the header row and first column on larger tables. I have utilized the jquery Datatables plugin with its fixedColumns extension to be able to do so

The table that I am working on also happens to have knockout.js bindings, which renders the
 rows from data obtained in the page's typescript.

the issue
When I do a pull from the server to get the data from the table, on page refresh or on interactions with other controls on the page, I run the following code (be warned, it's quite ugly - just trying to get it to work now):

```<code>module dataTable {
export class dataTableClass {
    applyTable(tableIdString: string) : void {
        (<any>$(tableIdString))
            .DataTable({
                scrollY: 1000,
                scrollX: true,
                scrollCollapse: true,
                paging: false,
                searching: false,
                fixedHeader: true,
                fixedColumns: {
                    leftColumns: 1
                }
            });
    }

    dataTableExists(tableIdString: string): boolean {
        return (<any>$.fn.DataTable.isDataTable(tableIdString));
    }

    applyDatatableIfTableExists(retryCount: number, elementId: string): void {
        if (!elementId) {
            console.warn("table id not defined.");
            return;
        }

        if (!retryCount) {
            retryCount = 0;
        } else if (retryCount > 100) {
            console.warn("could not convert table to dataTable.");
            return;
        }

        window.setTimeout(() => {
            var tableIdString = "#" + elementId;
            if ((<any>$(tableIdString)).length <= 0) {
                this.applyDatatableIfTableExists(++retryCount, elementId);
            } else {
                if (this.dataTableExists(tableIdString)) {
                    debugger;
                    (<any>$(tableIdString)).DataTable({ retrieve: true }).destroy(); // <-- issue here. it seems to restore old data to the now-datatable-less table
                }

                window.setTimeout(() => {
                    this.applyTable(tableIdString);
                    if (!this.dataTableExists(tableIdString)) {
                        this.applyDatatableIfTableExists(++retryCount, elementId);
                    }
                }, 250);

                if (!(<any>$(tableIdString)).hasClass(".dataTable")) {
                    (<any>$(tableIdString)).addClass(".dataTable");
                }
            }
        }, 250);
    }

    applyDataTable(id) {
        this.applyDatatableIfTableExists(0, id);
    }
}
</code>```

}

On server pull, in typescript, when the deferred code resolves and sets the table's data on an knockout observable array, the applyDataTable class gets called with the table's html ID

all the code runs fine for the first time - I allow the browser some time to render the table and to convert the table into a DataTable

When a user interacts with other controls on the page (to set filters for the knockout Observable array to change the table's contents), I destroy the table - presuming the table has already been initialised.

I recreate the table with the same DataTable options immediately after that so that new data (theoretically) displays in the table, having the fixedColumns extension render correctly again (since it changes cells and table header cells into tables of their own and apply css to make it look neat)

The issue comes on the line I marked. What happens on-screen is that it definitely removes the changes applied by DataTables from the HTML, but, the table that renders has old data in it (even though I fetched new data from the server by changing my search criteria on page - which generates new ....).

Also commenting out all this code inside my applyDataTable() method, it never sets the datatable plugin on my html table (as expected) and changing my filters reflects the newest and correct data on my table.

So in tl;dr - what is happening is that some state information gets stored by datatables. is there a way for me to clear this state and only apply a datatable with my settings over my html table?

答:
You can remove the old data from table body or the whole table. It depends on whether you're recreating column headers later.

For example:

$('#example').DataTable().destroy();
$('#example tbody').empty();
```

<p>So in your case it would be something like:</p>

<pre class="lang-js prettyprint-override"><code>(<any>$(tableIdString)).DataTable().destroy();
(<any>$(tableIdString + ' tbody')).empty();
</code>```

Body:
Good day

Painting the scenario:
I have a scenario I am working on for work, where I had to freeze the header row and first column on larger tables. I have utilized the jquery Datatables plugin with its fixedColumns extension to be able to do so

The table that I am working on also happens to have knockout.js bindings, which renders the
 rows from data obtained in the page's typescript.

the issue
When I do a pull from the server to get the data from the table, on page refresh or on interactions with other controls on the page, I run the following code (be warned, it's quite ugly - just trying to get it to work now):

module dataTable {
export class dataTableClass {
    applyTable(tableIdString: string) : void {
        (<any>$(tableIdString))
            .DataTable({
                scrollY: 1000,
                scrollX: true,
                scrollCollapse: true,
                paging: false,
                searching: false,
                fixedHeader: true,
                fixedColumns: {
                    leftColumns: 1
                }
            });
    }

    dataTableExists(tableIdString: string): boolean {
        return (<any>$.fn.DataTable.isDataTable(tableIdString));
    }

    applyDatatableIfTableExists(retryCount: number, elementId: string): void {
        if (!elementId) {
            console.warn("table id not defined.");
            return;
        }

        if (!retryCount) {
            retryCount = 0;
        } else if (retryCount > 100) {
            console.warn("could not convert table to dataTable.");
            return;
        }

        window.setTimeout(() => {
            var tableIdString = "#" + elementId;
            if ((<any>$(tableIdString)).length <= 0) {
                this.applyDatatableIfTableExists(++retryCount, elementId);
            } else {
                if (this.dataTableExists(tableIdString)) {
                    debugger;
                    (<any>$(tableIdString)).DataTable({ retrieve: true }).destroy(); // <-- issue here. it seems to restore old data to the now-datatable-less table
                }

                window.setTimeout(() => {
                    this.applyTable(tableIdString);
                    if (!this.dataTableExists(tableIdString)) {
                        this.applyDatatableIfTableExists(++retryCount, elementId);
                    }
                }, 250);

                if (!(<any>$(tableIdString)).hasClass(".dataTable")) {
                    (<any>$(tableIdString)).addClass(".dataTable");
                }
            }
        }, 250);
    }

    applyDataTable(id) {
        this.applyDatatableIfTableExists(0, id);
    }
}

}

On server pull, in typescript, when the deferred code resolves and sets the table's data on an knockout observable array, the applyDataTable class gets called with the table's html ID

all the code runs fine for the first time - I allow the browser some time to render the table and to convert the table into a DataTable

When a user interacts with other controls on the page (to set filters for the knockout Observable array to change the table's contents), I destroy the table - presuming the table has already been initialised.

I recreate the table with the same DataTable options immediately after that so that new data (theoretically) displays in the table, having the fixedColumns extension render correctly again (since it changes cells and table header cells into tables of their own and apply css to make it look neat)

The issue comes on the line I marked. What happens on-screen is that it definitely removes the changes applied by DataTables from the HTML, but, the table that renders has old data in it (even though I fetched new data from the server by changing my search criteria on page - which generates new ....).

Also commenting out all this code inside my applyDataTable() method, it never sets the datatable plugin on my html table (as expected) and changing my filters reflects the newest and correct data on my table.

So in tl;dr - what is happening is that some state information gets stored by datatables. is there a way for me to clear this state and only apply a datatable with my settings over my html table?

Body:
You can remove the old data from table body or the whole table. It depends on whether you're recreating column headers later.

For example:

$('#example').DataTable().destroy();
$('#example tbody').empty();

So in your case it would be something like:

(<any>$(tableIdString)).DataTable().destroy();
(<any>$(tableIdString + ' tbody')).empty();


问:
Regex replace h1 tag with h2 tag globally with php
I'm having a hard time trying to replace
 tags with
 in a piece of content.

The closest i have gotten is this:

```<code>preg_replace('/<h1[\s*](class|id|style)="(.*?)">(\w*?)<\/h1>/mi', '<h2 $1="$2">$3</h2>',  $content);
</code>```

The issue here is that a regular h1 line as:

This is the heading

won't get capturet.

This line:

Another heading

Also won't get captured, which baffles me since it uses the same setup as class and id, only with special characters, such as -, : and so on. I thought .*? would cover.

Any help would be really appreciated.

答:
Here is something similar, taking all attributes : (every thing but > in attributes)</p>

```<code>$str= <<<EOT
<h1>This is the heading</h1>
<h1 style="font-size:13px">Another heading</h1>
EOT;

$str = preg_replace('#<h1([^>]*)>(.*)</h1>#m','<h2$1>$2</h2>', $str);
print $str;
</code>```

Body:
I'm having a hard time trying to replace
 tags with
 in a piece of content.

The closest i have gotten is this:

preg_replace('/
(\w*?)<\/h1>/mi', '
$3
',  $content);

The issue here is that a regular h1 line as:

This is the heading

won't get capturet.

This line:

Another heading

Also won't get captured, which baffles me since it uses the same setup as class and id, only with special characters, such as -, : and so on. I thought .*? would cover.

Any help would be really appreciated.

Body:
Here is something similar, taking all attributes : (every thing but > in attributes)

$str= <<<EOT
<h1>This is the heading</h1>
<h1 style="font-size:13px">Another heading</h1>
EOT;

$str = preg_replace('#<h1([^>]*)>(.*)</h1>#m','<h2$1>$2</h2>', $str);
print $str;


问:
How do you search for a certain thing in a text file in python?
I have a text file:

```<code>E5341,21/09/2015,C102,440,E,0
E5342,21/09/2015,C103,290,A,290
E5343,21/09/2015,C104,730,N,0
E5344,22/09/2015,C105,180,A,180
E5345,22/09/2015,C106,815,A,400
E5346,23/09/2015,C107,970,N,0
E5347,23/09/2015,C108,1050,E,0
E5348,23/09/2015,C109,370,A,200
E5349,25/09/2015,C110,480,A,250
E5350,25/09/2015,C111,330,A,330
E5351,25/09/2015,C112,1750,E,0
E5352,28/09/2015,C113,1500,N,0
E5353,28/09/2015,C114,272,A,200
E5354,29/09/2015,C115,560,E,0
E5355,29/09/2015,C116,530,A,450
E5356,29/09/2015,C117,860,E,0
E5357,29/09/2015,C118,650,E,0
E5358,29/09/2015,C119,380,A,380
E5359,29/09/2015,C120,980,N,0
E5360,30/09/2015,C121,1375,E,0
E5361,01/10/2015,C122,374,A,374
</code>```

The E stands for the estimate number

The date following the estimate number is the estimated date

The C stands for the customer number

The number following the customer number is the final total in £

The letter after the final total tells you if the job was accepted(A) or not accepted (N) or the job was just an estimate (E)

The number after the status^ is the total amount already paid in £

I want to find out how if I enter one of the estimate numbers in python can I print out the date or work out the outstanding payments and find out what status the job is.

I've tried to research this but I don't understand it, I would really appreciate any help towards this.

The expected outcome if i put in the estimate number of 5353 is meant to show the date which would be 28/09/2015 for that example

答:
The basic idea in Python 2 (note I have not tested this, but it should be close or work as is):

```<code>search = '5356' # supply this as your search
search = 'E'+search
fh = open('textfile.txt')
for line in fh:
    elements = line.split(',')
    if len(elements) == 6:
        if elements[0] == search:
            print 'For Estimate #'+search
            print 'date:'+elements[1]
            print 'cust:'+elements[2]
            print 'totl:'+elements[3]
            print 'stat:'+elements[4]
            print 'paid:'+elements[5]
fh.close()
</code>```

Now... go look up each statement in that example in the Python 2 documentation and see what the various items in it do. That'll give you a little kickstart towards learning the language, if you are ever going to do any more in it.

Keep in mind that failure is possible: What if the text file name is wrong, for instance, and the file open fails? You'll want to look at the try and except Python language elements.

Everyone needs to start somewhere, which is why I didn't give you a snarky "show your work" answer. So here's your start. Go forth and learn. :)

Body:
I have a text file:

E5341,21/09/2015,C102,440,E,0
E5342,21/09/2015,C103,290,A,290
E5343,21/09/2015,C104,730,N,0
E5344,22/09/2015,C105,180,A,180
E5345,22/09/2015,C106,815,A,400
E5346,23/09/2015,C107,970,N,0
E5347,23/09/2015,C108,1050,E,0
E5348,23/09/2015,C109,370,A,200
E5349,25/09/2015,C110,480,A,250
E5350,25/09/2015,C111,330,A,330
E5351,25/09/2015,C112,1750,E,0
E5352,28/09/2015,C113,1500,N,0
E5353,28/09/2015,C114,272,A,200
E5354,29/09/2015,C115,560,E,0
E5355,29/09/2015,C116,530,A,450
E5356,29/09/2015,C117,860,E,0
E5357,29/09/2015,C118,650,E,0
E5358,29/09/2015,C119,380,A,380
E5359,29/09/2015,C120,980,N,0
E5360,30/09/2015,C121,1375,E,0
E5361,01/10/2015,C122,374,A,374

The E stands for the estimate number

The date following the estimate number is the estimated date

The C stands for the customer number

The number following the customer number is the final total in £

The letter after the final total tells you if the job was accepted(A) or not accepted (N) or the job was just an estimate (E)

The number after the status^ is the total amount already paid in £

I want to find out how if I enter one of the estimate numbers in python can I print out the date or work out the outstanding payments and find out what status the job is.

I've tried to research this but I don't understand it, I would really appreciate any help towards this.

The expected outcome if i put in the estimate number of 5353 is meant to show the date which would be 28/09/2015 for that example

Body:
The basic idea in Python 2 (note I have not tested this, but it should be close or work as is):

search = '5356' # supply this as your search
search = 'E'+search
fh = open('textfile.txt')
for line in fh:
    elements = line.split(',')
    if len(elements) == 6:
        if elements[0] == search:
            print 'For Estimate #'+search
            print 'date:'+elements[1]
            print 'cust:'+elements[2]
            print 'totl:'+elements[3]
            print 'stat:'+elements[4]
            print 'paid:'+elements[5]
fh.close()

Now... go look up each statement in that example in the Python 2 documentation and see what the various items in it do. That'll give you a little kickstart towards learning the language, if you are ever going to do any more in it.

Keep in mind that failure is possible: What if the text file name is wrong, for instance, and the file open fails? You'll want to look at the try and except Python language elements.

Everyone needs to start somewhere, which is why I didn't give you a snarky "show your work" answer. So here's your start. Go forth and learn. :)


问:
Save matches (only string) by xPath on a file
is it possible to save all results from a xPath on a file? I am using Chrome to search the class elements in the DOM tree.  E.g. .//*[contains(@class, 'NAME_')].
'NAME_' is always given in the DOM. I don't need the whole Node, just the string 'NAME_somethingElse' on a text file

Thanks in advance!

答:
If this XPath,

```<code>.//*[contains(@class, 'NAME_')]
</code>```

selects all of the elements you want, then this XPath,

```<code>.//*[contains(@class, 'NAME_')]/@class
</code>```

will select the associated class attributes only, without the elements.

Body:
If this XPath,

.//*[contains(@class, 'NAME_')]

selects all of the elements you want, then this XPath,

.//*[contains(@class, 'NAME_')]/@class

will select the associated class attributes only, without the elements.


问:
How to configure Apache Kafka to sending data at specified time?
Lets consider the following abstaract schema of working Apache Kafka:

```<code>Poducers ->(Send messages) -> Apache Kafka -> (Resend to customers) -> Customers
</code>```

It is possible to configure Kafka to send messages to customers at the specified time?

The second question is it real to roll back message to Kafka from customer?

答:
Extending to Robin,

Kafka won't push messages to consumer, consumer need to pull messages from Kafka.

Look at below python snippet to read messages from Kafka:

```<code>running = True
while running:
    msg = c.poll(timeout=1.0)
    if not msg.error():
        print('Received message: %s' % msg.value().decode('utf-8'))
    elif msg.error().code() != KafkaError._PARTITION_EOF:
        print(msg.error())
        running = False
</code>```

In above snippet msg = c.poll(timeout=1.0) is used to pull message from Kafka every second. if you want to you increase timeout to any number of seconds. these means Kafka consumer consumer will pull message from every time interval.

if you want to do schedule, you have to call poll method at schedule timings.

Note : you session.timeout.ms should be greater than poll time

Body:
Lets consider the following abstaract schema of working Apache Kafka:

Poducers ->(Send messages) -> Apache Kafka -> (Resend to customers) -> Customers

It is possible to configure Kafka to send messages to customers at the specified time?

The second question is it real to roll back message to Kafka from customer?

Body:
Extending to Robin,

Kafka won't push messages to consumer, consumer need to pull messages from Kafka.

Look at below python snippet to read messages from Kafka:

running = True
while running:
    msg = c.poll(timeout=1.0)
    if not msg.error():
        print('Received message: %s' % msg.value().decode('utf-8'))
    elif msg.error().code() != KafkaError._PARTITION_EOF:
        print(msg.error())
        running = False

In above snippet msg = c.poll(timeout=1.0) is used to pull message from Kafka every second. if you want to you increase timeout to any number of seconds. these means Kafka consumer consumer will pull message from every time interval.

if you want to do schedule, you have to call poll method at schedule timings.

Note : you session.timeout.ms should be greater than poll time


问:
How to get indexOf of multidimentional array?
I'm having some troubles getting the indexOf a multidimentional array.

```<code>var z = [["231f20", 5385], ["ffffff", 2419], ["ffafff", 2419]];
var index = z[0].indexOf('ffffff');
alert(index); #returns -1
</code>```

As you can observe, the hex value and numbers (pixel quantity) are inside the same list in z.

How can I filter and get the indexOf the correct list ?

答:
I've written a quick and dirty deep indexOf function which returns an array of indices to follow:

```<code>Object.prototype.deepIndexOf = Array.prototype.deepIndexOf = function (v) {
    for (var i in this) {
        if (this[i] === v) {
            return [i];
        }

        if ('object' === typeof this[i]) {
            var t = this[i].deepIndexOf(v);
            if (t !== undefined) {
                t.unshift(i);
                return t;
            }
        }
    }
    return undefined;
}
</code>```

This probably fails in some cases, but works for simple arrays and objects:

Object.prototype.deepIndexOf = Array.prototype.deepIndexOf = function(v) {
 for(var i in this) {
   if(this[i] === v) {
     return [i];
    }

    if('object' === typeof this[i]) {
     var t = this[i].deepIndexOf(v);
      if(t !== undefined) {
       t.unshift(i);
       return t;
      }
    }
  }
  return undefined;
}

var z = [["231f20", 5385], ["ffffff", 2419], ["ffafff", 2419]];

var z2 = {
 hello: {
   world: 5
  },
  bye: {
   world: 3,
    earth: 4
  }
}

console.log(z.deepIndexOf('ffffff'));
console.log(z2.deepIndexOf(4));

// And even very deep objects/arrays:

var verydeep = {
    one: {
        two: [
            [
                {
                    five: {
                        six: [
                            'Hello'
                        ]
                    }
                }
            ]
        ]
    }
}

console.log(verydeep.deepIndexOf('Hello'))```
</div>
</div>
</p>

<p>Outputs:</p>

```[
  "1",
  "0"
]
[
  "bye",
  "earth"
]
[
  "one",
  "two",
  "0",
  "0",
  "five",
  "six",
  "0"
]
```

Body:
I'm having some troubles getting the indexOf a multidimentional array.

var z = [["231f20", 5385], ["ffffff", 2419], ["ffafff", 2419]];
var index = z[0].indexOf('ffffff');
alert(index); #returns -1

As you can observe, the hex value and numbers (pixel quantity) are inside the same list in z.

How can I filter and get the indexOf the correct list ?

Body:
I've written a quick and dirty deep indexOf function which returns an array of indices to follow:

Object.prototype.deepIndexOf = Array.prototype.deepIndexOf = function (v) {
    for (var i in this) {
        if (this[i] === v) {
            return [i];
        }

        if ('object' === typeof this[i]) {
            var t = this[i].deepIndexOf(v);
            if (t !== undefined) {
                t.unshift(i);
                return t;
            }
        }
    }
    return undefined;
}

This probably fails in some cases, but works for simple arrays and objects:

Object.prototype.deepIndexOf = Array.prototype.deepIndexOf = function(v) {
 for(var i in this) {
   if(this[i] === v) {
     return [i];
    }

    if('object' === typeof this[i]) {
     var t = this[i].deepIndexOf(v);
      if(t !== undefined) {
       t.unshift(i);
       return t;
      }
    }
  }
  return undefined;
}

var z = [["231f20", 5385], ["ffffff", 2419], ["ffafff", 2419]];

var z2 = {
 hello: {
   world: 5
  },
  bye: {
   world: 3,
    earth: 4
  }
}

console.log(z.deepIndexOf('ffffff'));
console.log(z2.deepIndexOf(4));

// And even very deep objects/arrays:

var verydeep = {
    one: {
        two: [
            [
                {
                    five: {
                        six: [
                            'Hello'
                        ]
                    }
                }
            ]
        ]
    }
}

console.log(verydeep.deepIndexOf('Hello'))

Outputs:

[
  "1",
  "0"
]
[
  "bye",
  "earth"
]
[
  "one",
  "two",
  "0",
  "0",
  "five",
  "six",
  "0"
]