问:
Two Recyclerview one in Bottom Sheet Layout not showing data in Coordinate Layout
Hey Everyone I have two recyclerviews out of which one is in bottom sheet. The top one is working fine but bottom one is not showing anything. and there is no error displaying in logcat as well.
This is my MainActivity.Class

```<code>import android.content.ContentValues;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.app.adapter.CardViewDataAdapter;
import com.example.app.adapter.UserListAdapter;
import com.example.app.beans.ItemsBean;
import com.example.app.classes.UserSelectedItems;
import com.example.app.database.DBHelper;
import com.example.app.utils.CommonUtilities;
import com.example.app.utils.Constants;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;

    private RecyclerView mRecyclerView, selected_recyclerview;
    private RecyclerView.Adapter mAdapter;
    UserListAdapter adapter;
    private RecyclerView.LayoutManager mLayoutManager;
    List<String> selected_items= new ArrayList<>();
    View bottomSheet;
    BottomSheetBehavior behavior;

    private List<ItemsBean> itemList;
    String[] items= new String[]{"Sugar", "Tea", "Coffee", "Milk", "Bread", "Butter", "Jeera", "Egg", "Buiscuit", "JAM", "Maggi",
    "Wheat", "Lentils", "Shampoo","Soap", "oil", "Hair Spray", "Coconut", "Cream", "Curd", "Cheese"};

    String[] item_ids= new String[]{"101", "102", "103", "104", "105", "106", "107", "108", "109", "110", "111", "112", "113", "114",
    "115", "116", "117", "118", "119", "120", "121"};

    private Button btnSelection;
    DBHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        btnSelection = (Button) findViewById(R.id.btnShow);
        selected_recyclerview= (RecyclerView)findViewById(R.id.recyclerView);
        bottomSheet = findViewById(R.id.bottom_sheet);
        behavior = BottomSheetBehavior.from(bottomSheet);
        behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                // React to state change
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                // React to dragging events
            }
        });
        dbHelper= CommonUtilities.getDBObject(this);
        itemList = new ArrayList<>();

        for (int i = 0; i < items.length; i++) {
            ItemsBean bean= new ItemsBean();
            bean.setItemId(item_ids[i]);
            bean.setItemName(items[i]);
            bean.setItemStatus(1);
            itemList.add(bean);
            ContentValues values= new ContentValues();
            values.put(Constants.ITEM_ID,item_ids[i]);
            values.put(Constants.ITEM_NAME, items[i]);
            values.put(Constants.ITEM_STATUS,1);
            dbHelper.insertContentVals(Constants.MASTER_ITEM_TABLE, values);

        }

        if (toolbar != null) {
            setSupportActionBar(toolbar);
            getSupportActionBar().setTitle("Grocery List");

        }

        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        mRecyclerView.setHasFixedSize(true);

        // use a linear layout manager
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        // create an Object for Adapter
        mAdapter = new CardViewDataAdapter(itemList);

        // set the adapter object to the Recyclerview
        mRecyclerView.setAdapter(mAdapter);

        btnSelection.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String data = "";
                List<ItemsBean> stList = ((CardViewDataAdapter) mAdapter)
                        .getStudentist();

                for (int i = 0; i < stList.size(); i++) {
                    ItemsBean singleStudent = stList.get(i);
                    if (singleStudent.isSelected() == true) {
                        selected_items.add(singleStudent.getItemName().toString());
                        data = data + "\n" + singleStudent.getItemName().toString();
                        /*
                         * Toast.makeText( CardViewActivity.this, " " +
                         * singleStudent.getName() + " " +
                         * singleStudent.getEmailId() + " " +
                         * singleStudent.isSelected(),
                         * Toast.LENGTH_SHORT).show();
                         */
                    }

                }

                selected_recyclerview.setHasFixedSize(true);
                LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
                linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                selected_recyclerview.setLayoutManager(linearLayoutManager);

                adapter = new UserListAdapter(MainActivity.this, selected_items);
                selected_recyclerview.setAdapter(adapter);
                behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                Log.e("size", "size=" + selected_items.size());
                /*Intent i= new Intent(MainActivity.this, UserSelectedItems.class);
                i.putStringArrayListExtra("selected", (ArrayList<String>) selected_items);
                Toast.makeText(MainActivity.this,
                        "Selected Students: \n" + data, Toast.LENGTH_LONG)
                        .show();
                startActivity(i);*/
            }
        });

    }

}
</code>```

Here is my xml file

```<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"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#a3b1ef"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <include
            android:id="@+id/toolbar"
            layout="@layout/toolbar" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/my_recycler_view"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:scrollbars="vertical" />

        <Button
            android:id="@+id/btnShow"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:background="#00796B"
            android:text="Show Selected"
            android:textColor="@color/TextPrimaryColor" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/bottom_sheet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#fff"
        android:gravity="center"
        android:orientation="vertical"
        app:layout_behavior="@string/bottom_sheet_behavior">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="16dp"
            android:layout_marginTop="16dp"
            android:background="#fff" />

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/proceed"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:layout_margin="10dp"
            android:src="@android:drawable/arrow_up_float" />

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

Here is user_list_row

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:padding="5dp"
    android:gravity="center">

    <TextView
        android:id="@+id/item_name"
        android:layout_width="0dp"
        android:layout_weight="0.2"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:textColor="@color/col444"
        android:text="Sugar"/>

    <Spinner
        android:id="@+id/brand"
        android:layout_width="0dp"
        android:layout_weight="0.3"
        android:layout_height="wrap_content"
        android:textColor="@color/col444"
        android:layout_toRightOf="@id/item_name"
        ></Spinner>

    <Spinner
        android:id="@+id/unit"
        android:layout_width="0dp"
        android:textColor="@color/col444"
        android:layout_weight="0.3"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/brand"
        ></Spinner>

    <EditText
        android:id="@+id/quantity"
        android:layout_width="0dp"
        android:layout_weight="0.2"
        android:hint="Qty."
        android:textColor="@color/col444"
        android:layout_height="wrap_content" />

</LinearLayout>
</code>```

Here is UserItem Adapter

```<code>import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import com.example.app.R;
import com.example.app.beans.SelectedBean;
import com.example.app.classes.UserSelectedItems;
import java.util.List;

/**
 * Created by me on 9/22/2016.
 */
public class UserListAdapter extends  RecyclerView.Adapter<UserListAdapter.UserViewHolder>{

    Context context;
    List<String> data;
    String[] brands= new String[]{
            "Select Brand","Brand One", "Brand Two", "Brand Three", "Brand Four"
    };
    String[] units= new String[]{"Select Unit", "Kg", "Gms", "Lbs", "Pieces"};

    public UserListAdapter(Context context, List<String> data){
       this.context= context;
       this.data= data;
    }

    @Override
    public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // create a new view
        View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.user_list_row, null);
        // create ViewHolder
        UserViewHolder viewHolder = new UserViewHolder(itemLayoutView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(UserViewHolder holder, int position) {
        holder.itemName.setText(data.get(position));
        ArrayAdapter<String> adapter= new ArrayAdapter<String>(context, android.R.layout.simple_spinner_dropdown_item, brands);
        holder.brand.setAdapter(adapter);
        ArrayAdapter<String> madapter= new ArrayAdapter<String>(context, android.R.layout.simple_spinner_dropdown_item, units);
        holder.unit.setAdapter(madapter);
       /* holder.unit.setSelection(0);
        holder.brand.setSelection(0);*/
        final SelectedBean bean= new SelectedBean();
        bean.setItemName(data.get(position));
        holder.unit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(position!=0){
                    bean.setUnitName(units[position]);
                    bean.setUnitSelectedPos(position);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
               /* if(DetailActivity.list!=null && DetailActivity.list.size()>0) {
                    holder.brand.setSelection(DetailActivity.list.get(position).getBrandSelectedPos());
                    holder.unit.setSelection(DetailActivity.list.get(position).getUnitSelectedPos());
                }*/
            }
        });
        holder.brand.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                bean.setBrandName(brands[position]);
                bean.setBrandSelectedPos(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        holder.quantity.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                bean.setQuantity(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        holder.brand.setSelection(bean.getBrandSelectedPos());
        holder.unit.setSelection(bean.getUnitSelectedPos());
        Log.e("size", "= "+  UserSelectedItems.list.size());

        UserSelectedItems.list.add(bean);

    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public class UserViewHolder extends RecyclerView.ViewHolder{

        TextView itemName;
        EditText quantity;
        Spinner brand, unit;

        public UserViewHolder(View itemView) {
            super(itemView);
            itemName= (TextView)itemView.findViewById(R.id.item_name);
            quantity= (EditText) itemView.findViewById(R.id.quantity);
            brand= (Spinner)itemView.findViewById(R.id.brand);
            unit= (Spinner)itemView.findViewById(R.id.unit);
        }
    }
}
</code>```

Please let me know what should I do to show data in recyclerview in bottom sheet layout. There is a button at the bottom on click of which the bottom sheet expands like below.

Thanks in advance.

答:
set in parent view</p>

```<code>android:weightSum="1"
</code>```

Body:
Hey Everyone I have two recyclerviews out of which one is in bottom sheet. The top one is working fine but bottom one is not showing anything. and there is no error displaying in logcat as well.
This is my MainActivity.Class

import android.content.ContentValues;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.app.adapter.CardViewDataAdapter;
import com.example.app.adapter.UserListAdapter;
import com.example.app.beans.ItemsBean;
import com.example.app.classes.UserSelectedItems;
import com.example.app.database.DBHelper;
import com.example.app.utils.CommonUtilities;
import com.example.app.utils.Constants;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;

    private RecyclerView mRecyclerView, selected_recyclerview;
    private RecyclerView.Adapter mAdapter;
    UserListAdapter adapter;
    private RecyclerView.LayoutManager mLayoutManager;
    List<String> selected_items= new ArrayList<>();
    View bottomSheet;
    BottomSheetBehavior behavior;

    private List<ItemsBean> itemList;
    String[] items= new String[]{"Sugar", "Tea", "Coffee", "Milk", "Bread", "Butter", "Jeera", "Egg", "Buiscuit", "JAM", "Maggi",
    "Wheat", "Lentils", "Shampoo","Soap", "oil", "Hair Spray", "Coconut", "Cream", "Curd", "Cheese"};

    String[] item_ids= new String[]{"101", "102", "103", "104", "105", "106", "107", "108", "109", "110", "111", "112", "113", "114",
    "115", "116", "117", "118", "119", "120", "121"};

    private Button btnSelection;
    DBHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        btnSelection = (Button) findViewById(R.id.btnShow);
        selected_recyclerview= (RecyclerView)findViewById(R.id.recyclerView);
        bottomSheet = findViewById(R.id.bottom_sheet);
        behavior = BottomSheetBehavior.from(bottomSheet);
        behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                // React to state change
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                // React to dragging events
            }
        });
        dbHelper= CommonUtilities.getDBObject(this);
        itemList = new ArrayList<>();

        for (int i = 0; i < items.length; i++) {
            ItemsBean bean= new ItemsBean();
            bean.setItemId(item_ids[i]);
            bean.setItemName(items[i]);
            bean.setItemStatus(1);
            itemList.add(bean);
            ContentValues values= new ContentValues();
            values.put(Constants.ITEM_ID,item_ids[i]);
            values.put(Constants.ITEM_NAME, items[i]);
            values.put(Constants.ITEM_STATUS,1);
            dbHelper.insertContentVals(Constants.MASTER_ITEM_TABLE, values);

        }

        if (toolbar != null) {
            setSupportActionBar(toolbar);
            getSupportActionBar().setTitle("Grocery List");

        }

        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        mRecyclerView.setHasFixedSize(true);

        // use a linear layout manager
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        // create an Object for Adapter
        mAdapter = new CardViewDataAdapter(itemList);

        // set the adapter object to the Recyclerview
        mRecyclerView.setAdapter(mAdapter);

        btnSelection.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String data = "";
                List<ItemsBean> stList = ((CardViewDataAdapter) mAdapter)
                        .getStudentist();

                for (int i = 0; i < stList.size(); i++) {
                    ItemsBean singleStudent = stList.get(i);
                    if (singleStudent.isSelected() == true) {
                        selected_items.add(singleStudent.getItemName().toString());
                        data = data + "\n" + singleStudent.getItemName().toString();
                        /*
                         * Toast.makeText( CardViewActivity.this, " " +
                         * singleStudent.getName() + " " +
                         * singleStudent.getEmailId() + " " +
                         * singleStudent.isSelected(),
                         * Toast.LENGTH_SHORT).show();
                         */
                    }

                }

                selected_recyclerview.setHasFixedSize(true);
                LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
                linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                selected_recyclerview.setLayoutManager(linearLayoutManager);

                adapter = new UserListAdapter(MainActivity.this, selected_items);
                selected_recyclerview.setAdapter(adapter);
                behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                Log.e("size", "size=" + selected_items.size());
                /*Intent i= new Intent(MainActivity.this, UserSelectedItems.class);
                i.putStringArrayListExtra("selected", (ArrayList<String>) selected_items);
                Toast.makeText(MainActivity.this,
                        "Selected Students: \n" + data, Toast.LENGTH_LONG)
                        .show();
                startActivity(i);*/
            }
        });

    }

}

Here is my xml file

<?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:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#a3b1ef"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <include
            android:id="@+id/toolbar"
            layout="@layout/toolbar" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/my_recycler_view"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:scrollbars="vertical" />

        <Button
            android:id="@+id/btnShow"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:background="#00796B"
            android:text="Show Selected"
            android:textColor="@color/TextPrimaryColor" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/bottom_sheet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#fff"
        android:gravity="center"
        android:orientation="vertical"
        app:layout_behavior="@string/bottom_sheet_behavior">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="16dp"
            android:layout_marginTop="16dp"
            android:background="#fff" />

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/proceed"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:layout_margin="10dp"
            android:src="@android:drawable/arrow_up_float" />

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

Here is user_list_row

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:padding="5dp"
    android:gravity="center">

    <TextView
        android:id="@+id/item_name"
        android:layout_width="0dp"
        android:layout_weight="0.2"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:textColor="@color/col444"
        android:text="Sugar"/>

    <Spinner
        android:id="@+id/brand"
        android:layout_width="0dp"
        android:layout_weight="0.3"
        android:layout_height="wrap_content"
        android:textColor="@color/col444"
        android:layout_toRightOf="@id/item_name"
        ></Spinner>

    <Spinner
        android:id="@+id/unit"
        android:layout_width="0dp"
        android:textColor="@color/col444"
        android:layout_weight="0.3"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/brand"
        ></Spinner>

    <EditText
        android:id="@+id/quantity"
        android:layout_width="0dp"
        android:layout_weight="0.2"
        android:hint="Qty."
        android:textColor="@color/col444"
        android:layout_height="wrap_content" />

</LinearLayout>

Here is UserItem Adapter

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import com.example.app.R;
import com.example.app.beans.SelectedBean;
import com.example.app.classes.UserSelectedItems;
import java.util.List;

/**
 * Created by me on 9/22/2016.
 */
public class UserListAdapter extends  RecyclerView.Adapter<UserListAdapter.UserViewHolder>{

    Context context;
    List<String> data;
    String[] brands= new String[]{
            "Select Brand","Brand One", "Brand Two", "Brand Three", "Brand Four"
    };
    String[] units= new String[]{"Select Unit", "Kg", "Gms", "Lbs", "Pieces"};

    public UserListAdapter(Context context, List<String> data){
       this.context= context;
       this.data= data;
    }

    @Override
    public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // create a new view
        View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.user_list_row, null);
        // create ViewHolder
        UserViewHolder viewHolder = new UserViewHolder(itemLayoutView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(UserViewHolder holder, int position) {
        holder.itemName.setText(data.get(position));
        ArrayAdapter<String> adapter= new ArrayAdapter<String>(context, android.R.layout.simple_spinner_dropdown_item, brands);
        holder.brand.setAdapter(adapter);
        ArrayAdapter<String> madapter= new ArrayAdapter<String>(context, android.R.layout.simple_spinner_dropdown_item, units);
        holder.unit.setAdapter(madapter);
       /* holder.unit.setSelection(0);
        holder.brand.setSelection(0);*/
        final SelectedBean bean= new SelectedBean();
        bean.setItemName(data.get(position));
        holder.unit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(position!=0){
                    bean.setUnitName(units[position]);
                    bean.setUnitSelectedPos(position);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
               /* if(DetailActivity.list!=null && DetailActivity.list.size()>0) {
                    holder.brand.setSelection(DetailActivity.list.get(position).getBrandSelectedPos());
                    holder.unit.setSelection(DetailActivity.list.get(position).getUnitSelectedPos());
                }*/
            }
        });
        holder.brand.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                bean.setBrandName(brands[position]);
                bean.setBrandSelectedPos(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        holder.quantity.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                bean.setQuantity(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        holder.brand.setSelection(bean.getBrandSelectedPos());
        holder.unit.setSelection(bean.getUnitSelectedPos());
        Log.e("size", "= "+  UserSelectedItems.list.size());

        UserSelectedItems.list.add(bean);

    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public class UserViewHolder extends RecyclerView.ViewHolder{

        TextView itemName;
        EditText quantity;
        Spinner brand, unit;

        public UserViewHolder(View itemView) {
            super(itemView);
            itemName= (TextView)itemView.findViewById(R.id.item_name);
            quantity= (EditText) itemView.findViewById(R.id.quantity);
            brand= (Spinner)itemView.findViewById(R.id.brand);
            unit= (Spinner)itemView.findViewById(R.id.unit);
        }
    }
}

Please let me know what should I do to show data in recyclerview in bottom sheet layout. There is a button at the bottom on click of which the bottom sheet expands like below.

Thanks in advance.

Body:
set in parent view

android:weightSum="1"


来源: stackexchange

问:
Requests module is multiplying api calls in Python
I am using the Requests python module to do RESTFUL POST API calls to create a new item.

PROBLEM: Items are being duplicated. Sometimes 3 of each item get created. No check for existing data is in place in the final api prevent duplication.

GOAL: I want to send data to create a single new item in a third party application called Netbox which is made with Django.

WHAT HAVE I DONE?:

I have tried writing code to check for existing items and it still
makes duplicates.

I have tried set a timer to pause execution of code by 10 seconds until the request is complete.

The process flow looks like this:

```<code>Python Backend (Flask)         ---> Python Backend (Flask)           --> Netbox (Django)

Data Origin sent via Requests  ---> Data Netbox Calls (Via PyNetBox) --> Final DataStore
</code>```

The two backends are hosted in Cloud Foundry while Netbox is spun up on a Linux on Prem Server.

I have a dictionary like below that represents each item I need to create in Netbox.

```<code>Ex. payload = {'site':'1', 'device':'switch01'}
</code>```

I send each piece of data to my middleware backend via a loop to make the final api call to netbox via pynetbox. I am not able to hit netbox directly.

```<code>for payload in payloads:
     URL = f'{MIDDLEWARE_URL}/netbox/create_item'
     print(f'URL is: {URL} | Payload is {payload}')

     headers = { 'content-type': 'application/json', 'cache-control': "no-cache"}
     proxies={'http' : None, 'https': None}

     r = requests.post(URL, data=json.dumps(payload), headers=headers, verify=False, proxies=proxies)
</code>```

I would appreciate any help as to why this is happening and any best practices to improving my baseline code logic.

All the best,
Faraz

答:
So I figured it out after some more research and it turns out flask was creating two processes and therefore running my functions twice each time.

This was due to debug being true so used this:

```<code>app.run(debug=True, use_reloader=False)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using the Requests python module to do RESTFUL POST API calls to create a new item.

PROBLEM: Items are being duplicated. Sometimes 3 of each item get created. No check for existing data is in place in the final api prevent duplication.

GOAL: I want to send data to create a single new item in a third party application called Netbox which is made with Django.

WHAT HAVE I DONE?:

I have tried writing code to check for existing items and it still
makes duplicates.

I have tried set a timer to pause execution of code by 10 seconds until the request is complete.

The process flow looks like this:

Python Backend (Flask)         ---> Python Backend (Flask)           --> Netbox (Django)

Data Origin sent via Requests  ---> Data Netbox Calls (Via PyNetBox) --> Final DataStore

The two backends are hosted in Cloud Foundry while Netbox is spun up on a Linux on Prem Server.

I have a dictionary like below that represents each item I need to create in Netbox.

Ex. payload = {'site':'1', 'device':'switch01'}

I send each piece of data to my middleware backend via a loop to make the final api call to netbox via pynetbox. I am not able to hit netbox directly.

for payload in payloads:
     URL = f'{MIDDLEWARE_URL}/netbox/create_item'
     print(f'URL is: {URL} | Payload is {payload}')

     headers = { 'content-type': 'application/json', 'cache-control': "no-cache"}
     proxies={'http' : None, 'https': None}

     r = requests.post(URL, data=json.dumps(payload), headers=headers, verify=False, proxies=proxies)

I would appreciate any help as to why this is happening and any best practices to improving my baseline code logic.

All the best,
Faraz

Body:
So I figured it out after some more research and it turns out flask was creating two processes and therefore running my functions twice each time.

This was due to debug being true so used this:

app.run(debug=True, use_reloader=False)


问:
Linq list of interface, interface has member an array of strings, I want linq statement that aggregates all strings from array of objects
I have an array of interfaces in C#, in the interface there is a member, a list of strings, I'm trying to add all the strings together from the array of interface members that has a property of array of strings. </p>

```<code>IPackingFlowEvaluation[]

public interface IPackingFlowEvaluation
{
    IPackingFlow PackingFlow { get; }

    int Priority { get; }

    bool CanUse { get; }

    string[] Reasons { get; }
}
</code>```

<p>I want a linq statement that will add up all the strings of the array of interface member into one large list of strings. A giant list of reasons containing all the reasons from the array of interfaces that has a member itself that has an array of strings.   </p>

答:
sounds like you're after SelectMany

```<code>var reasons = source.SelectMany(e => e.Reasons).ToList();
</code>```

where source refers to IPackingFlowEvaluation[].

Body:
I have an array of interfaces in C#, in the interface there is a member, a list of strings, I'm trying to add all the strings together from the array of interface members that has a property of array of strings.

IPackingFlowEvaluation[]

public interface IPackingFlowEvaluation
{
    IPackingFlow PackingFlow { get; }

    int Priority { get; }

    bool CanUse { get; }

    string[] Reasons { get; }
}

I want a linq statement that will add up all the strings of the array of interface member into one large list of strings. A giant list of reasons containing all the reasons from the array of interfaces that has a member itself that has an array of strings.

Body:
sounds like you're after SelectMany

var reasons = source.SelectMany(e => e.Reasons).ToList();

where source refers to IPackingFlowEvaluation[].


问:
Liferay Json Web Service Parameters input
I user Liferay 6.2
I create an Entity (notizia) with Service Builder.

I generated Web Services.
I have a method to print a string like this:

```<code>public class notiziaServiceImpl extends notiziaServiceBaseImpl {

    @Override
    @AccessControlled(guestAccessEnabled=true)
    public String printMyString()
    {
        return "i'm the string ";
    }
}
</code>```

It works!
I added another method with an input parameter

```<code>@AccessControlled(guestAccessEnabled=true)
    public String getHelloWorld(String worldName)
                    throws com.liferay.portal.kernel.exception.PortalException,
                    com.liferay.portal.kernel.exception.SystemException {
        return "Hello world: " + worldName;
    }
</code>```

"getHelloWorld" method not work.
I got this error in console:

```<code>[MethodParametersResolverImpl:59] java.lang.IllegalArgumentException
java.lang.IllegalArgumentException
</code>```

I don't know what i miss.
How can i solve it?

答:
Thanks for that answer @Dhruv Pandey! you saved my day (or days).

By the way, I want to point out that even if in the Jodd's link you posted they say: "Jodd may be used on any platform where there is a suitable Java 8 runtime environment." that doesn't mean we can't use it in, for example, a server running on Java 11.

What's important here is that the artifact we deploy has the target runtime environment set as Java 8, otherwise we'll get the exception.

So I'm running a Liferay 7.2 instance in Java 11, and had this configuration in the build plugin of my service pom.xml:

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

This was throwing the error. What I did, is changed the configuration to the following:

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

After that, the error was gone.

Body:
I user Liferay 6.2
I create an Entity (notizia) with Service Builder.

I generated Web Services.
I have a method to print a string like this:

public class notiziaServiceImpl extends notiziaServiceBaseImpl {

    @Override
    @AccessControlled(guestAccessEnabled=true)
    public String printMyString()
    {
        return "i'm the string ";
    }
}

It works!
I added another method with an input parameter

@AccessControlled(guestAccessEnabled=true)
    public String getHelloWorld(String worldName)
                    throws com.liferay.portal.kernel.exception.PortalException,
                    com.liferay.portal.kernel.exception.SystemException {
        return "Hello world: " + worldName;
    }

"getHelloWorld" method not work.
I got this error in console:

[MethodParametersResolverImpl:59] java.lang.IllegalArgumentException
java.lang.IllegalArgumentException

I don't know what i miss.
How can i solve it?

Body:
Thanks for that answer @Dhruv Pandey! you saved my day (or days).

By the way, I want to point out that even if in the Jodd's link you posted they say: "Jodd may be used on any platform where there is a suitable Java 8 runtime environment." that doesn't mean we can't use it in, for example, a server running on Java 11.

What's important here is that the artifact we deploy has the target runtime environment set as Java 8, otherwise we'll get the exception.

So I'm running a Liferay 7.2 instance in Java 11, and had this configuration in the build plugin of my service pom.xml:

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

This was throwing the error. What I did, is changed the configuration to the following:

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

After that, the error was gone.


问:
TPROXY for IPV6
I have my own NAT modules for IPV6.I need TPROXY support.Is there any patch available for download?I am using the 2.6.32-71 kernel.</p>

答:
If you are using a RedHat kernel IPv6 TProxy support was backported into RHEL6.1

https://bugzilla.redhat.com/show_bug.cgi?id=591335

http://rhn.redhat.com/errata/RHSA-2011-0542.html

ContentLicense: CC BY-SA 2.5

Title: TPROXY for IPV6

ContentLicense: CC BY-SA 3.0


问:
Flutter release APK is not working but debug APK is working
My debug APK is working fine but release APK is not working after building it from the command flutter build apk. What can be the real issue here?

答:
In debug mode, any global variables or methods will work perfectly but in case of release mode, only native code is compiled. So let's assume we are getting some unformatted text and we want to format it and return so if you have a global function to format text like below it will work fine in debug mode but might cause problems in release mode.

Code with global function.

```<code>// Global Function
String formatText(String unformattedText){
    // ....
    return formattedText;
}

Widget _showFormattedText(String unformattedText) {
   final fd = formatText(unformattedText);
   return Text(fd);
}
</code>```

Instead of this we should follow best practices and wrap everything inside a class which is present globally.

```<code>// Code with class method.
class CustomFunctions{
  static String formatText(String unformattedText){
      // ....
      return formattedText;
  }
}

Widget _showFormattedText(String unformattedText) {
   final fd = CustomFunctions.formatText(unformattedText);
   return Text(fd);
}
</code>```

Body:
In debug mode, any global variables or methods will work perfectly but in case of release mode, only native code is compiled. So let's assume we are getting some unformatted text and we want to format it and return so if you have a global function to format text like below it will work fine in debug mode but might cause problems in release mode.

Code with global function.

// Global Function
String formatText(String unformattedText){
    // ....
    return formattedText;
}

Widget _showFormattedText(String unformattedText) {
   final fd = formatText(unformattedText);
   return Text(fd);
}

Instead of this we should follow best practices and wrap everything inside a class which is present globally.

// Code with class method.
class CustomFunctions{
  static String formatText(String unformattedText){
      // ....
      return formattedText;
  }
}

Widget _showFormattedText(String unformattedText) {
   final fd = CustomFunctions.formatText(unformattedText);
   return Text(fd);
}


问:
print level order traversal of binary tree in Zigzag manner
I have to print the nodes of a binary tree using level order traversal but in spiral form i.e nodes at different level should be printed in spiral form.

for eg: If the tree look like:

The output should be 10 5 20 25 15 6 4.

The algorithm i used is simple and is just a small variation of level order traversal. I just took a variable p.if the variable is equal to 1 than print the order at a given level left to right , if it is -1 print right to left.

```<code>void getlevel(struct node *root,int n,int p)
{
        if(root==NULL)
        return;
        if(n==0)
        {
                printf("%d ",root->info);
                return;
        }
        if(n>0)
        {
            if(p==1)
            {
                 getlevel(root->left,n-1,p);
                 getlevel(root->right,n-1,p);
            }
            if(p==-1)
            {
                 getlevel(root->right,n-1,p);
                 getlevel(root->left,n-1,p);
            }
        }
}
</code>```

I am getting the answer but the worst case complexity is probably O(n^2) in case of skewed tree.

Can there be a better algorithm for this task?..

My entire program is here

答:
I believe the simplest of them all without any variable just two stacks.

```<code>public void zigzagNew() {
    TreeNode t = this.root;
    Stack<TreeNode> cs = new Stack<>();
    Stack<TreeNode> ns = new Stack<>();
    cs.add(t);
    while(cs.isEmpty()==false || ns.isEmpty() == false) {
        while(cs.isEmpty() == false) {
            TreeNode cur = cs.pop();
            System.out.print(cur.val + " ");
            if(cur.left != null) {
                ns.push(cur.left);
            }
            if(cur.right != null) {
                ns.push(cur.right);
            }
        }
        System.out.println();
        while(ns.isEmpty()==false) {
            TreeNode cur = ns.pop();
            System.out.print(cur.val + " ");
            if(cur.right != null) {
                cs.push(cur.right);
            }
            if(cur.left != null) {
                cs.push(cur.left);
            }
        }
        System.out.println();
    }
}
</code>```

Body:
I have to print the nodes of a binary tree using level order traversal but in spiral form i.e nodes at different level should be printed in spiral form.

for eg: If the tree look like:

The output should be 10 5 20 25 15 6 4.

The algorithm i used is simple and is just a small variation of level order traversal. I just took a variable p.if the variable is equal to 1 than print the order at a given level left to right , if it is -1 print right to left.

void getlevel(struct node *root,int n,int p)
{
        if(root==NULL)
        return;
        if(n==0)
        {
                printf("%d ",root->info);
                return;
        }
        if(n>0)
        {
            if(p==1)
            {
                 getlevel(root->left,n-1,p);
                 getlevel(root->right,n-1,p);
            }
            if(p==-1)
            {
                 getlevel(root->right,n-1,p);
                 getlevel(root->left,n-1,p);
            }
        }
}

I am getting the answer but the worst case complexity is probably O(n^2) in case of skewed tree.

Can there be a better algorithm for this task?..

My entire program is here

Body:
I believe the simplest of them all without any variable just two stacks.

public void zigzagNew() {
    TreeNode t = this.root;
    Stack<TreeNode> cs = new Stack<>();
    Stack<TreeNode> ns = new Stack<>();
    cs.add(t);
    while(cs.isEmpty()==false || ns.isEmpty() == false) {
        while(cs.isEmpty() == false) {
            TreeNode cur = cs.pop();
            System.out.print(cur.val + " ");
            if(cur.left != null) {
                ns.push(cur.left);
            }
            if(cur.right != null) {
                ns.push(cur.right);
            }
        }
        System.out.println();
        while(ns.isEmpty()==false) {
            TreeNode cur = ns.pop();
            System.out.print(cur.val + " ");
            if(cur.right != null) {
                cs.push(cur.right);
            }
            if(cur.left != null) {
                cs.push(cur.left);
            }
        }
        System.out.println();
    }
}


问:
Laravel 7.6 maatawebsite 3.1 excel import not saving data in datatable
I have been trying to upload excel in my data-table but its not working. I'm getting the success message data uploaded but it's not saving excel entries.

I followed this links instructions as well:
https://www.studentstutorial.com/laravel/import
https://www.webslesson.info/2019/02/import-excel-file-in-laravel.html

Here's my controller:

```<code>//Save the File
    if($request->hasFile('file'))
    {
        // Get the file with extension
        $filenameWithExt = $request->file('file')->getClientOriginalName();
        //Get the file name
        $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
        //Get the ext
        $extension = $request->file('file')->getClientOriginalExtension();
        //File name to store
        $fileNameToStore = $filename.'_'.time().'.'.$extension;
        //Upload File
        $path = $request->file('file')->storeAS('public/excels', $fileNameToStore);

    }

    $this->validate($request, [
        'file' => 'required|mimes:xlsx,xls',
    ]);

    $data = Excel::import(new Product, $path);

    foreach ($data as $row) {

        $arr[] = [
            'Title' => $row->title,
            'Text' => $row->text,
            'Slug' => $row->slug,
            'Brand_id' => $row->brand_id,
            'Category_id' => $row->category_id,
            'Image' => $row->image,
        ];

            if (!empty($arr)) {
                DB::table('products')->insert($arr);
            }
        }

    return back()->with('success', 'Products Added');
</code>```

My Form:

```<code><form role="form" method="POST" action="{{ action('ProductsController@import')}}" enctype="multipart/form-data">
                            @csrf
                            <div class="input-group mb-3 shadow">
                                <input type="file" name="file" class="btn btn-dark" title="Select File">
                                <button type="submit" class="btn btn-success rounded-0">Upload</button>
                            </div>
                        </form>
</code>```

答:
After some time I was able solve it myself.I crated a new Import Controller and made this change in the ProductsController@import

The change I made in my controller:

```<code>$products = Excel::toArray(new ProductsImport(), $request->file('file'));

    foreach($products[0] as $row) {
        //  dd($row[1].' '.$row[2]);
        $arr[] = [
            // If uncomment this id from here, remove [0] from foreach
            // 'id' => $row[0],
            'image' => $row[1],
            'title' => $row[2],
            'slug' => $row[3],
            'text' => $row[4],
            'brand_id' => $row[5],
            'category_id' => $row[6],
        ];
    }
    // dd($products);

    if(!empty($arr)){
        DB::table('products')->insert($arr);
    }

    return back()->with('success', 'Products Added');
</code>```

Now, the file is being saved in public/excels and data being imported to datatable.

Body:
I have been trying to upload excel in my data-table but its not working. I'm getting the success message data uploaded but it's not saving excel entries.

I followed this links instructions as well:
https://www.studentstutorial.com/laravel/import
https://www.webslesson.info/2019/02/import-excel-file-in-laravel.html

Here's my controller:

//Save the File
    if($request->hasFile('file'))
    {
        // Get the file with extension
        $filenameWithExt = $request->file('file')->getClientOriginalName();
        //Get the file name
        $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
        //Get the ext
        $extension = $request->file('file')->getClientOriginalExtension();
        //File name to store
        $fileNameToStore = $filename.'_'.time().'.'.$extension;
        //Upload File
        $path = $request->file('file')->storeAS('public/excels', $fileNameToStore);

    }

    $this->validate($request, [
        'file' => 'required|mimes:xlsx,xls',
    ]);

    $data = Excel::import(new Product, $path);

    foreach ($data as $row) {

        $arr[] = [
            'Title' => $row->title,
            'Text' => $row->text,
            'Slug' => $row->slug,
            'Brand_id' => $row->brand_id,
            'Category_id' => $row->category_id,
            'Image' => $row->image,
        ];

            if (!empty($arr)) {
                DB::table('products')->insert($arr);
            }
        }

    return back()->with('success', 'Products Added');

My Form:

<form role="form" method="POST" action="{{ action('ProductsController@import')}}" enctype="multipart/form-data">
                            @csrf

                                <input type="file" name="file" class="btn btn-dark" title="Select File">
                                <button type="submit" class="btn btn-success rounded-0">Upload</button>

                        </form>

Body:
After some time I was able solve it myself.I crated a new Import Controller and made this change in the ProductsController@import

The change I made in my controller:

$products = Excel::toArray(new ProductsImport(), $request->file('file'));

    foreach($products[0] as $row) {
        //  dd($row[1].' '.$row[2]);
        $arr[] = [
            // If uncomment this id from here, remove [0] from foreach
            // 'id' => $row[0],
            'image' => $row[1],
            'title' => $row[2],
            'slug' => $row[3],
            'text' => $row[4],
            'brand_id' => $row[5],
            'category_id' => $row[6],
        ];
    }
    // dd($products);

    if(!empty($arr)){
        DB::table('products')->insert($arr);
    }

    return back()->with('success', 'Products Added');

Now, the file is being saved in public/excels and data being imported to datatable.


答:
You need to use SelectMany() for that effect.

```<code>var allReasons = array.SelectMany(i => i.Reasons.ToList()).ToList();
</code>```

Title: Linq list of interface, interface has member an array of strings, I want linq statement that aggregates all strings from array of objects

Body:
You need to use SelectMany() for that effect.

var allReasons = array.SelectMany(i => i.Reasons.ToList()).ToList();


问:
Pandas groupby to find mean count of categorical field
Working with a pandas dataframe, trying to get the mean count of one field grouped by another. I have the below dataframe

```<code>user_id    tag_number
----------------------
1             xx
1             xx
1             xy
2             xy
2             zz
2             zz
2             zz
</code>```

I am trying to get the average tag_number counts per unique tag_number grouped by user_id. I can do data.groupby(["user_id", "tag_number"]).size()
to get the following result

```<code>user_id  tag_number
-------------------------
1        xx            2
         xy            1
2        xy            1
         zz            3
</code>```

but what i am looking for is

```<code>user_id   avg_tag_number_count
------------------------------
1          1.5

2          2.0
</code>```

because for user 1 there are a total of 3 tag_number instances between 2 unique tag_numbers. And for user 2 there are a total of 4 tag_number instances between 2 unique tag_numbers.

答:
You need this:

```<code>data.groupby(["user_id", "tag_number"]).size().groupby(level=0).mean().reset_index().rename(columns={0: 'avg_tag_number_count'})
</code>```

Output:

```<code>   user_id  avg_tag_number_count
0        1                   1.5
1        2                   2.0
</code>```

Body:
Working with a pandas dataframe, trying to get the mean count of one field grouped by another. I have the below dataframe

user_id    tag_number
----------------------
1             xx
1             xx
1             xy
2             xy
2             zz
2             zz
2             zz

I am trying to get the average tag_number counts per unique tag_number grouped by user_id. I can do data.groupby(["user_id", "tag_number"]).size()
to get the following result

user_id  tag_number
-------------------------
1        xx            2
         xy            1
2        xy            1
         zz            3

but what i am looking for is

user_id   avg_tag_number_count
------------------------------
1          1.5

2          2.0

because for user 1 there are a total of 3 tag_number instances between 2 unique tag_numbers. And for user 2 there are a total of 4 tag_number instances between 2 unique tag_numbers.

Body:
You need this:

data.groupby(["user_id", "tag_number"]).size().groupby(level=0).mean().reset_index().rename(columns={0: 'avg_tag_number_count'})

Output:

   user_id  avg_tag_number_count
0        1                   1.5
1        2                   2.0


问:
GWT interaction with external standalone application
I work on a standalone Java application that is a command-and-control system for an assortment of hardware.  The C&C software basically runs from a command line, and controls the system hardware which is spread out all over the place.  It does not require a GUI to meet the business requirements.  I have written a small swing GUI just so I can see what the overall status is of the system, but again, that is not essential.

Going forward, we would like to have a Administrative web GUI with system status and something that would give a user some level of control over the hardware.  We were thinking that GWT might be a viable solution.  Our GWT app would have to have some sort of IPC with the C&C software.  I don't know how viable that is, I don't know that we want the C&C software bundled as a web app that has to run under application server.

I just don't have much experience with this.  I was thinking that the GWT client would interact through RPC with the GWT server, and the GWT server would have some sort of RPC (RMI???) with the C&C.

答: You can embed embedded tomcat or Jetty into your application and let it run a simple servlet/JSP - based or GWT-based web UI. In fact, when you debug/run your GWT application from Eclipse, it starts in an embedded Tomcat instance.</p>


问:
Count if with 2 conditions - Python
I'm having some trouble solving this, so I come here for your help.

I have a dataframe with many columns, and I want to count how many cells of a specific column meet the condition of another column. In Excel this would be count.if, but I can't figure it out exactly for my problem. Let me give you an example.

```<code>Names    Detail

John      B
John      B
John      S
Martin    S
Martin    B
Robert    S
</code>```

In this df for example there are 3 "B" and 3 "S" in total.

How can I get how many "B" and "S" there are for each name in column A?

Im trying to get a result dataframe like

```<code>         B      S
John     2      1
Martin   1      1
Robert   0      1
</code>```

I tried

```<code>b_var = sum(1 for i in df['Names'] if i == 'John')
s_var = sum(1 for k in df['Detail'] if k == 'B')
</code>```

and then make a for? but I don't know how to do both conditions at a time, or is it better a groupby approach?

Thanks!!

答:
```<code>df.pivot_table(index='Names', columns='Detail', aggfunc=len)
</code>```

Title: Count if with 2 conditions - Python

Body:
I'm having some trouble solving this, so I come here for your help.

I have a dataframe with many columns, and I want to count how many cells of a specific column meet the condition of another column. In Excel this would be count.if, but I can't figure it out exactly for my problem. Let me give you an example.

Names    Detail

John      B
John      B
John      S
Martin    S
Martin    B
Robert    S

In this df for example there are 3 "B" and 3 "S" in total.

How can I get how many "B" and "S" there are for each name in column A?

Im trying to get a result dataframe like

         B      S
John     2      1
Martin   1      1
Robert   0      1

I tried

b_var = sum(1 for i in df['Names'] if i == 'John')
s_var = sum(1 for k in df['Detail'] if k == 'B')

and then make a for? but I don't know how to do both conditions at a time, or is it better a groupby approach?

Thanks!!


问:
How to pass default for named parameters in javascript
I have a method in typescript as below using named parameters

```<code>public foo({x, y, z , m , n} : {x:string, y: number, z: number, m?:string, n?:number}) {
}
</code>```

parameters m and n will be provided from another object like

```<code>const default = { m : 'M', n :10, o:6 }
</code>```

Now I want to call foo like below and I want default parameters will be added without explicitly passing them in the call

```<code>  foo({x:'x', y: 5, z: 0})
</code>```

So my question is how to apply default in the body of foo or somehow intercepting foo before call and apply default

```<code>public foo({x, y, z , m , n} = {x:string, y: number, z: number, m?:string, n?:number}) {
   // for example how to apply default here

}
</code>```

Please note for simplicity I reduced number of parameters

Also I know these below solutions already I am looking for something with less boilerplate code

```<code>public foo({x, y, z , m , n} = {x:string, y: number, z: number, m?:string, n?:number}) {
   if (!m) {
     m = default.m;
   }
   if (!n) {
     n = default.n;
   }

}
</code>```

or

```<code>foo({...default, x:'x', y: 5, z: 0 });
</code>```

答:
You can just add a default value in the parameter itself like below:

```<code>public foo({x, y, z , m = 'a' , n = 10} = {x:string, y: number, z: number, m?:string, n?:number}) {
}
</code>```

If you pass a value, default value will be overridden. With this way, you dont even need an if to check the presence of the value.

and you can still call the method as:

foo({...default, x:'x', y: 5, z: 0 });

Body:
I have a method in typescript as below using named parameters

public foo({x, y, z , m , n} : {x:string, y: number, z: number, m?:string, n?:number}) {
}

parameters m and n will be provided from another object like

const default = { m : 'M', n :10, o:6 }

Now I want to call foo like below and I want default parameters will be added without explicitly passing them in the call

  foo({x:'x', y: 5, z: 0})

So my question is how to apply default in the body of foo or somehow intercepting foo before call and apply default

public foo({x, y, z , m , n} = {x:string, y: number, z: number, m?:string, n?:number}) {
   // for example how to apply default here

}

Please note for simplicity I reduced number of parameters

Also I know these below solutions already I am looking for something with less boilerplate code

public foo({x, y, z , m , n} = {x:string, y: number, z: number, m?:string, n?:number}) {
   if (!m) {
     m = default.m;
   }
   if (!n) {
     n = default.n;
   }

}

or

foo({...default, x:'x', y: 5, z: 0 });

Body:
You can just add a default value in the parameter itself like below:

public foo({x, y, z , m = 'a' , n = 10} = {x:string, y: number, z: number, m?:string, n?:number}) {
}

If you pass a value, default value will be overridden. With this way, you dont even need an if to check the presence of the value.

and you can still call the method as:

foo({...default, x:'x', y: 5, z: 0 });


问:
Median and mode in excel using multiple columns
I am working on a spreadsheet for my statistics class. It contains a column filled with a quantity and a column filled with a frequency for each quantity. Using these two columns and several formulas, the mean, mode, median, coefficient variation, quartiles, interquartile range, minimum and maximum values and standard deviation can be found.

The issue is that to shorten the list of quantities, the use of the frequencies column comes in. Take the quantity list of : 10, 12, 14, 15, 18, 18, 10.

Notice that 18 and 10 have been repeated. Instead of repeating those quantities in my quantities column, I increment the frequency of that quantity from 1 to 2. The reason for doing it this way is due to very large lists of quantity data. Meaning I might have 5000 quantities that could potentially be reduced to 20 quantities where each quantity will have a larger frequency.

The issue is that the built-in Median and Mode function use only 1 column or row and do not account for the frequency of each quantity.

My question is this: Is there a way to use both columns to calculate the median and mode? Below is an example of what I was explaining. Additionally, my column containing quantities and frequencies may not be filled from start to end, meaning there maybe empty entries.

```<code>Quantity  |  Frequency
  10      |     4
  12      |     6
  11      |     3
  15      |     1
  18      |     10

VS.

Quantity
10
10
10
10
12
12
12
12
12
12
11
11
11
15
18
18
18
18
18
18
18
18
18
18
</code>```

答:
Assuming that each Quantity only appears once alongside its Frequency, then you could use an INDEX MATCH on the MAX Frequency to find the Mode:

```<code>=INDEX(A2:A6,Match(Max(B2:B6), B2:B6, 0))
</code>```

This will, of course, only return the first number should there be multiple Quantities which share the same maximum frequency (such as if Quantity 12 also occurred with Frequency 10)

Further assuming that your Quantities are in Ascending Order, you can use Matrix Multiplication (MMULT) to calculate the running total for each row, and use AGGREGATE to get the smallest row where the running total greater-than-or-equal-to half the overall total.  This is the Median:

```<code>=AGGREGATE(15, 6, A2:A6/(MMULT(--(TRANSPOSE(ROW(B2:B6))<=ROW(B2:B6)), B2:B6)>=0.5*SUM(B2:B6)), 1)
</code>```

(For reference, MMULT(--(TRANSPOSE(ROW(B2:B6))<=ROW(B2:B6)), B2:B6) is the bit which works out the Running total)

Body:
I am working on a spreadsheet for my statistics class. It contains a column filled with a quantity and a column filled with a frequency for each quantity. Using these two columns and several formulas, the mean, mode, median, coefficient variation, quartiles, interquartile range, minimum and maximum values and standard deviation can be found.

The issue is that to shorten the list of quantities, the use of the frequencies column comes in. Take the quantity list of : 10, 12, 14, 15, 18, 18, 10.

Notice that 18 and 10 have been repeated. Instead of repeating those quantities in my quantities column, I increment the frequency of that quantity from 1 to 2. The reason for doing it this way is due to very large lists of quantity data. Meaning I might have 5000 quantities that could potentially be reduced to 20 quantities where each quantity will have a larger frequency.

The issue is that the built-in Median and Mode function use only 1 column or row and do not account for the frequency of each quantity.

My question is this: Is there a way to use both columns to calculate the median and mode? Below is an example of what I was explaining. Additionally, my column containing quantities and frequencies may not be filled from start to end, meaning there maybe empty entries.

Quantity  |  Frequency
  10      |     4
  12      |     6
  11      |     3
  15      |     1
  18      |     10

VS.

Quantity
10
10
10
10
12
12
12
12
12
12
11
11
11
15
18
18
18
18
18
18
18
18
18
18

Body:
Assuming that each Quantity only appears once alongside its Frequency, then you could use an INDEX MATCH on the MAX Frequency to find the Mode:

=INDEX(A2:A6,Match(Max(B2:B6), B2:B6, 0))

This will, of course, only return the first number should there be multiple Quantities which share the same maximum frequency (such as if Quantity 12 also occurred with Frequency 10)

Further assuming that your Quantities are in Ascending Order, you can use Matrix Multiplication (MMULT) to calculate the running total for each row, and use AGGREGATE to get the smallest row where the running total greater-than-or-equal-to half the overall total.  This is the Median:

=AGGREGATE(15, 6, A2:A6/(MMULT(--(TRANSPOSE(ROW(B2:B6))<=ROW(B2:B6)), B2:B6)>=0.5*SUM(B2:B6)), 1)

(For reference, MMULT(--(TRANSPOSE(ROW(B2:B6))<=ROW(B2:B6)), B2:B6) is the bit which works out the Running total)


问:
ARM Template - Creating a template for VirtualnetworkGateway combined in a single template
I have created a template which is meant to deploy a complete network solution, which includes 2-subnets, vnet, vnetgw and pubip. I am looking for a way to programmatically reference some of the resource id's such that it makes the template more dynamic and can be used as many times as possible. secondly, the templates generates an error on deployment which obviously is as a result of the the references i mentioned earlier. Pls see error below;

New-AzResourceGroupDeployment:  Line |    3 |
  New-AzResourceGroupDeployment -ResourceGroupName rg-vnet-dev -Templat
  …
       |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       | 19:05:58 - Resource Microsoft.Network/virtualNetworkGateways 'rgvnetdev-vnetgw' failed with message '{   "error": {
      "code": "InvalidTemplate",
      "message": "Unable to process template language expressions for resource
  '/subscriptions/77dd2569-6341-4c72-880d-ef59413db99e/resourceGroups/rg-vnet-dev/providers/Microsoft.Network/virtualNetworkGateways/rgvnetdev-vnetgw'
  at line '279' and column '9'. 'Unable to evaluate template language
  function 'resourceId': the type
  'Microsoft.Network/virtualNetworks/subnets' requires '2' resource name
  argument(s). Please see
  https://aka.ms/arm-template-expressions/#resourceid for usage
  details.'",
      "additionalInfo": [
        {
          "type": "TemplateViolation",
          "info": {
            "lineNumber": 279,
            "linePosition": 9,
            "path": ""
          }
        }
      ]   } }

I will be happy to share the code, if this would assist in resolving my issue. The error relates to referencing the vnet dependson for creating vnetgw.

答:
```<code>       {
       "type": "Microsoft.Network/virtualNetworkGateways",
       "apiVersion": "2019-12-01",
       "name": "[variables('vnetgwname')]",
       "location": "[parameters('Location')]",
       "dependsOn": [
           "[resourceId('Microsoft.Network/publicIPAddresses',variables('pubIp'))]",
           "[resourceId('Microsoft.Network/virtualNetworks',variables('VNetName'))]"
       ],
       "properties": {
           "ipConfigurations": [
               {
                   "name": "vnetgatewayconfig",
                   "properties": {
                       "publicIPAddress": {
                           "id": "[resourceId('Microsoft.Network/publicIPAddresses',variables('pubIp'))]"
                       },
                       "subnet": {
                           "id": "[resourceId('Microsoft.Network/virtualNetworks/subnets',variables('VNetName'),variables('Uniquegwsubnet'))]"
                       },
                       "privateIPAllocationMethod": "[parameters('publicIPAllocationMethod')]"
                   }
               }
           ],
           "sku": {
               "name": "[parameters('sku')]",
               "tier": "[parameters('sku')]"
           },
           "gatewayType": "[parameters('gatewayType')]",
           "vpnType": "[parameters('VpnType')]",
           "activeActive": false,
           "enableBgp": false,
           "vpnGatewayGeneration": "[parameters('vpnGatewayGeneration')]"
       }
   },
</code>```


问:
Wildfly: web service deployed but unavailable

Problem description:

I want to deploy a web service through Wildfly and it gets deployed, but I cannot access it through a web browser.

This is what I do:

I run standalone.sh

I deploy the project using mvn clean package wildfly:deploy

Then I try to access my webservice through a web browser at http://localhost:8080/lab-ear/Hello?wsdl but I get only: "404 - Not Found"

Fragment of maven logs while deploying.

Here are logs from Wildfly server when it gets initialized.

And here Wildfly logs during deploy.

Other details:

I've done another project where the web service worked, but there were other problems, so I started everything from scratch.

This image is the comparison of structures of these two projects. On the left the old project and on the right the new project.

The important thing is that in the new project I don't get the web directory.

Maybe related problem:

Wildfly : application deployed but not running

Also, is it required to use Intellij IDEA in such projects?

EDIT

In my EJB module I have a class Hello in package pl.edu.agh.soa

I tried to change from this:

```<code>@Stateless
@WebService
public class Hello {
...
</code>```

to:

```<code>@Stateless(name = "Hello")
@WebService(name = "HelloService")
public class Hello {
...
</code>```

But it also doesn't work.

答:
Intellij IDEA is not required at all.

I think your issue is the missing web directory. Without WEB-INF/web.xml the app server won't know what it is supposed to serve.

Body:
Problem description:

I want to deploy a web service through Wildfly and it gets deployed, but I cannot access it through a web browser.

This is what I do:

I run standalone.sh

I deploy the project using mvn clean package wildfly:deploy

Then I try to access my webservice through a web browser at http://localhost:8080/lab-ear/Hello?wsdl but I get only: "404 - Not Found"

Fragment of maven logs while deploying.

Here are logs from Wildfly server when it gets initialized.

And here Wildfly logs during deploy.

Other details:

I've done another project where the web service worked, but there were other problems, so I started everything from scratch.

This image is the comparison of structures of these two projects. On the left the old project and on the right the new project.

The important thing is that in the new project I don't get the web directory.

Maybe related problem:

Wildfly : application deployed but not running

Also, is it required to use Intellij IDEA in such projects?

EDIT

In my EJB module I have a class Hello in package pl.edu.agh.soa

I tried to change from this:

@Stateless
@WebService
public class Hello {
...

to:

@Stateless(name = "Hello")
@WebService(name = "HelloService")
public class Hello {
...

But it also doesn't work.


问:
How to get Application Name To Call from PID in Mac AppleScript
There is a script that lets you resize any app in mac. This is the code:

```<code>set theApp to "Application Name"
set appHeight to 1080
set appWidth to 1920

    tell application "Finder"
    set screenResolution to bounds of window of desktop
end tell

set screenWidth to item 3 of screenResolution
set screenHeight to item 4 of screenResolution

tell application theApp
      activate
      reopen
      set yAxis to (screenHeight - appHeight) / 2 as integer
      set xAxis to (screenWidth - appWidth) / 2 as integer
      set the bounds of the first window to {xAxis, yAxis, appWidth + xAxis, appHeight + yAxis}
      end tell
</code>```

I want to change the size of a java application opened by a launcher. When I insert the name of any app, it works. However when I insert the name of the app that I want to resize it doesn't work. I know the process id of the app that I want to resize. Is there a way I can change this line set theApp to "Application Name" to use PID instead of Application name?
Thanks.

答:
Not all apps are AppleScript scriptable and some that are do not support the bounds property, they use position  property and size property.  Also, sometimes you'll need System Events to position and size an app's window.

I use a keyboard shortcut assigned in FastScripts with the following example AppleScript code to automatically adjust the frontmost app's window. You can adjust the code to suite your needs.

If the frontmost app can't use the bounds property it silently errors, and then System Events does it.

tell application "System Events"
    set frontmostProcess to name of process 1 whose frontmost is true
end tell

try
    tell application frontmostProcess
        set bounds of window 1 to {0, 22, 1136, 844}
    end tell
on error
    tell application "System Events" to tell application process frontmostProcess
        set position of window 1 to {0, 22}
        set size of window 1 to {1136, 822}
    end tell
end try
```

Note: I am not affiliated with the developer of FastScript, just a satisfied user. It's also free for the first ten keyboard shortcuts.

Body:
There is a script that lets you resize any app in mac. This is the code:

set theApp to "Application Name"
set appHeight to 1080
set appWidth to 1920

    tell application "Finder"
    set screenResolution to bounds of window of desktop
end tell

set screenWidth to item 3 of screenResolution
set screenHeight to item 4 of screenResolution

tell application theApp
      activate
      reopen
      set yAxis to (screenHeight - appHeight) / 2 as integer
      set xAxis to (screenWidth - appWidth) / 2 as integer
      set the bounds of the first window to {xAxis, yAxis, appWidth + xAxis, appHeight + yAxis}
      end tell

I want to change the size of a java application opened by a launcher. When I insert the name of any app, it works. However when I insert the name of the app that I want to resize it doesn't work. I know the process id of the app that I want to resize. Is there a way I can change this line set theApp to "Application Name" to use PID instead of Application name?
Thanks.

Body:
Not all apps are AppleScript scriptable and some that are do not support the bounds property, they use position  property and size property.  Also, sometimes you'll need System Events to position and size an app's window.

I use a keyboard shortcut assigned in FastScripts with the following example AppleScript code to automatically adjust the frontmost app's window. You can adjust the code to suite your needs.

If the frontmost app can't use the bounds property it silently errors, and then System Events does it.

tell application "System Events"
    set frontmostProcess to name of process 1 whose frontmost is true
end tell

try
    tell application frontmostProcess
        set bounds of window 1 to {0, 22, 1136, 844}
    end tell
on error
    tell application "System Events" to tell application process frontmostProcess
        set position of window 1 to {0, 22}
        set size of window 1 to {1136, 822}
    end tell
end try

Note: I am not affiliated with the developer of FastScript, just a satisfied user. It's also free for the first ten keyboard shortcuts.


问:
Relative imports for the trillionth time
I have the following data structure:

```<code>project/
    folder_a/
        file.py
    folder_b/
        useful_functions.py
</code>```

I am running my file.py and attempting to import a set of functions I have written within useful_functions.py.

At first I tried the following:

```<code>from ..folder_b.useful_functions import function_a
</code>```

But got the following error:

```<code>ValueError: attempted relative import beyond top-level package
</code>```

I then removed the two dots at the beginning of the import statement which initially worked. I have since revisited this project with no changes and I am faced with a new error message. The following code:

```<code>from folder_b.useful_functions import function_a
</code>```

Gives me the following error message:

```<code>ModuleNotFoundError: No module named 'folder_b'
</code>```

I find it very strange that one time it works and later with no changes the import fails. I really would like to solve this with relative imports as I would like the code to work other machines with different absolute file paths.

Thanks in advance.

答:
Well for the trillionth time running a script directly inside a package is considered an antipattern. I do not know how spyder runs stuff but presumably does

```<code>python file.py # from inside folder_a
</code>```

This should be changed to

```<code>python -m folder_a.file # from inside project
</code>```

This would resolve relative imports among packages inside project folder alright and will not need any sys.path or PYTHONPATH hacks

Body:
I have the following data structure:

project/
    folder_a/
        file.py
    folder_b/
        useful_functions.py

I am running my file.py and attempting to import a set of functions I have written within useful_functions.py.

At first I tried the following:

from ..folder_b.useful_functions import function_a

But got the following error:

ValueError: attempted relative import beyond top-level package

I then removed the two dots at the beginning of the import statement which initially worked. I have since revisited this project with no changes and I am faced with a new error message. The following code:

from folder_b.useful_functions import function_a

Gives me the following error message:

ModuleNotFoundError: No module named 'folder_b'

I find it very strange that one time it works and later with no changes the import fails. I really would like to solve this with relative imports as I would like the code to work other machines with different absolute file paths.

Thanks in advance.

Body:
Well for the trillionth time running a script directly inside a package is considered an antipattern. I do not know how spyder runs stuff but presumably does

python file.py # from inside folder_a

This should be changed to

python -m folder_a.file # from inside project

This would resolve relative imports among packages inside project folder alright and will not need any sys.path or PYTHONPATH hacks


问:
Microsoft Graph API - collect data from someone who is not an admin
We are using https://graph.microsoft.com/v1.0/groups/{id}/members to fetch member details from a customer. If the member is an admin - they get a permission popup and on consent we are able to see member details such as their relevant users, group info and so on.

This does not happen when a non-admin member tries to login. It says: Need admin approval.

Is there a way to bypass this and get user details irrespective of admin consent?

Thanks,
Billy

答:
Admin consent required for https://graph.microsoft.com/v1.0/groups/{id}/members

Admin consent gives admins a secure way to grant access to applications that require admin approval. When a user tries to access an application but is unable to provide consent, they can send a request for admin approval.

You can try demon application, you get a token from Azure AD in its own name (without a user), and then calls the Microsoft Graph /users endpoint to get the list of users, which it then displays (as JSON blob).please refer this document


问:
BeautifulSoup get_text() method on span returning quotes as part of string
Im using BeauitfulSoup get_text() method on the span tag by calling my parse_text function as

```<code>date = parse_text(soup.find('span'))
</code>```

and then inserting the date next to some data in a dictionary to use with pandas as

```<code>data['date'] = [date] * number_rows
</code>```

i then create a pandas dataframe from the dictionary and call .to_csv on the dataframe, but in the csv file all the dates show as "May 27, 2020" instead of just May 27, 2020

here is the parse_text function and html

```<code>   parse_text(element):
       return element.get_text().replace('\n', ' ').strip()
</code>```

May 27, 2020```

答: quickly after posting this I realize pandas .to_csv is inserting the quotes because of the present comma in the string, as it is the delimiter for the file... facepalm*</p>

Body:
Im using BeauitfulSoup get_text() method on the span tag by calling my parse_text function as

date = parse_text(soup.find('span'))

and then inserting the date next to some data in a dictionary to use with pandas as

data['date'] = [date] * number_rows

i then create a pandas dataframe from the dictionary and call .to_csv on the dataframe, but in the csv file all the dates show as "May 27, 2020" instead of just May 27, 2020

here is the parse_text function and html

   parse_text(element):
       return element.get_text().replace('\n', ' ').strip()

May 27, 2020


问:
Is it possible to insert on the same table on which you are applying an after update trigger? Mysql
So I do have a problem of understanding here. I would really appreciate if you help to clear my confusion.
So i have 2 tables table_1 and table_2 , where both the tables have the same columns as 'id' pk auto increment and 'name' varchar(20) .
Lets say i already have an after insert trigger on table_1 where everything i insert something in table_1 it stores the same copy in table_2 as well.
Now i wanted to apply an update trigger on the same table (table_1) to control if someone tries to modify the name in table_1 , it should take the name from table_2 and insert the correct name back to table_1.
I hope i explained it well. I will share the after update trigger i made which did not work. I would be more than happy if you help. Thank u </p>

```<code>delimiter $$
CREATE TRIGGER `Practice`.`table_1_after_UPDATE` AFTER UPDATE ON `table_1` FOR EACH ROW
BEGIN
if  old.name != new.name  then
update table_1
set name = table_2.name
where id = table_2.id;
end if;
END$$
delimiter ;
</code>```

答:
CREATE TRIGGER `Practice`.`table_1_BEFORE_UPDATE`
BEFORE UPDATE
ON `table_1`
FOR EACH ROW
set NEW.name = OLD.name;
```

Body:
So I do have a problem of understanding here. I would really appreciate if you help to clear my confusion.
So i have 2 tables table_1 and table_2 , where both the tables have the same columns as 'id' pk auto increment and 'name' varchar(20) .
Lets say i already have an after insert trigger on table_1 where everything i insert something in table_1 it stores the same copy in table_2 as well.
Now i wanted to apply an update trigger on the same table (table_1) to control if someone tries to modify the name in table_1 , it should take the name from table_2 and insert the correct name back to table_1.
I hope i explained it well. I will share the after update trigger i made which did not work. I would be more than happy if you help. Thank u

delimiter $$
CREATE TRIGGER `Practice`.`table_1_after_UPDATE` AFTER UPDATE ON `table_1` FOR EACH ROW
BEGIN
if  old.name != new.name  then
update table_1
set name = table_2.name
where id = table_2.id;
end if;
END$$
delimiter ;


问:
Merging two almost identical strings
I have two objects, one which is a list of tuples with (int, str), like this:

```<code>first_input = [
    (0  ,  "Lorem ipsum dolor sit amet, consectetur"),
    (1  ,  " adipiscing elit"),
    (0  ,  ". In pellentesque\npharetra ex, at varius sem suscipit ac. "),
    (-1 ,  "Suspendisse luctus\ncondimentum velit a laoreet. "),
    (0  ,  "Donec dolor urna, tempus sed nulla vitae, dignissim varius neque.")
]
# Note that the strings contain newlines `\n` on purpose.
</code>```

The other object is a string, which is the result of a series of operations(*) which, by design, will result in a concatenation of all the strings above but with some additional newlines \n inserted.

(* : that can't be done while conserving the list of tuples structure, obviously)

For instance:

```<code>second_input = "Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit. In pellentesque\npharetra ex, at varius sem\nsuscipit ac. Suspendisse luctus\ncondimentum velit a laoreet. Donec dolor urna, tempus sed\nnulla vitae, dignissim varius neque."
# Note that there are 3 new newlines,  here ^ for instance
# but also in "sem\nsuscipit" and "sed\nnulla"
</code>```

My goal is to go back to the first structure, but keeping the additional newlines. So in my example, I would get:

```<code>expected_output = [
    (0  ,  "Lorem ipsum dolor sit amet,\nconsectetur"),  # new newline here
    (1  ,  " adipiscing elit"),
    (0  ,  ". In pellentesque\npharetra ex, at varius sem\nsuscipit ac. "), # new newline here
    (-1 ,  "Suspendisse luctus\ncondimentum velit a laoreet. "),
    (0  ,  "Donec dolor urna, tempus sed\nnulla vitae, dignissim varius neque.") # new newline here
]
</code>```

Do you have a smart way to do it, other than reconstructing the string with a character by character comparison?

(NB: I don't care in which of the two tuples it ends if a new \n is at the limit of a string. E.g. getting [(0, "foo\n"), (1, "bar")] or [(0, "foo"), (1, "\nbar")] doesn't matter.)

Edit: what I want to avoid, is to do something like this:

```<code>position=0
output = []
for tup in first_input:
    reconstructed_string = ""
    for letter in tup[1]:
        if letter == second_input[position]:
            reconstructed_string = reconstructed_string + letter
        else:
            reconstructed_string = reconstructed_string + second_input[position]
        position +=1
    output.append((tup[0], reconstructed_string))
# Note: this is hastily written to give you an idea, I have no idea if it would work properly, probably not
# Well, it does seem to work without bug, at least in my example. That's unexpected lol. Anyway, if you can think of a better solution...!
</code>```

That is, going through each character of the strings and compare them to reconstruct the strings character by character.

答:
The way I would do it - written in terrible code. I wrote this pretty hastily

```<code>import re
first_input = [
(0  ,  "Lorem ipsum dolor sit amet, consectetur"),
    (1  ,  " adipiscing elit"),
    (0  ,  ". In pellentesque\npharetra ex, at varius sem suscipit ac. "),
    (-1 ,  "Suspendisse luctus\ncondimentum velit a laoreet. "),
    (0  ,  "Donec dolor urna, tempus sed nulla vitae, dignissim varius neque.")
]
second_input = "Lorem ipsum dolor sit amet,\n consectetur adipiscing elit. In pellentesque\npharetra ex, at varius sem\n suscipit ac. Suspendisse luctus\ncondimentum velit a laoreet. Donec dolor urna, tempus sed\n nulla vitae, dignissim varius neque."

first_sanitized = [x[1].replace('\n', '') for x in first_input]
second_sanitized = second_input.replace('\n', '')
newline_positions = [m.start() for m in re.finditer('\n' ,second_input, re.M)]
new_output = []
i = 0
print(second_sanitized)
newlines_so_far = 0
for first_str in first_sanitized:
   print(first_str)
   index = second_sanitized.index(first_str)
   number_of_newlines_in_between = sum([1 for x in newline_positions if (x > index and x < index + len(first_input[i][1]))])
   new_string = second_input[index : (index + len(first_input[i][1]) + number_of_newlines_in_between + newlines_so_far)]
   newlines_so_far += number_of_newlines_in_between
   new_element = (first_input[i][0], new_string)
   new_output.append(new_element)
   i = i + 1
</code>```

Title: Merging two almost identical strings

Body:
I have two objects, one which is a list of tuples with (int, str), like this:

first_input = [
    (0  ,  "Lorem ipsum dolor sit amet, consectetur"),
    (1  ,  " adipiscing elit"),
    (0  ,  ". In pellentesque\npharetra ex, at varius sem suscipit ac. "),
    (-1 ,  "Suspendisse luctus\ncondimentum velit a laoreet. "),
    (0  ,  "Donec dolor urna, tempus sed nulla vitae, dignissim varius neque.")
]
# Note that the strings contain newlines `\n` on purpose.

The other object is a string, which is the result of a series of operations(*) which, by design, will result in a concatenation of all the strings above but with some additional newlines \n inserted.

(* : that can't be done while conserving the list of tuples structure, obviously)

For instance:

second_input = "Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit. In pellentesque\npharetra ex, at varius sem\nsuscipit ac. Suspendisse luctus\ncondimentum velit a laoreet. Donec dolor urna, tempus sed\nnulla vitae, dignissim varius neque."
# Note that there are 3 new newlines,  here ^ for instance
# but also in "sem\nsuscipit" and "sed\nnulla"

My goal is to go back to the first structure, but keeping the additional newlines. So in my example, I would get:

expected_output = [
    (0  ,  "Lorem ipsum dolor sit amet,\nconsectetur"),  # new newline here
    (1  ,  " adipiscing elit"),
    (0  ,  ". In pellentesque\npharetra ex, at varius sem\nsuscipit ac. "), # new newline here
    (-1 ,  "Suspendisse luctus\ncondimentum velit a laoreet. "),
    (0  ,  "Donec dolor urna, tempus sed\nnulla vitae, dignissim varius neque.") # new newline here
]

Do you have a smart way to do it, other than reconstructing the string with a character by character comparison?

(NB: I don't care in which of the two tuples it ends if a new \n is at the limit of a string. E.g. getting [(0, "foo\n"), (1, "bar")] or [(0, "foo"), (1, "\nbar")] doesn't matter.)

Edit: what I want to avoid, is to do something like this:

position=0
output = []
for tup in first_input:
    reconstructed_string = ""
    for letter in tup[1]:
        if letter == second_input[position]:
            reconstructed_string = reconstructed_string + letter
        else:
            reconstructed_string = reconstructed_string + second_input[position]
        position +=1
    output.append((tup[0], reconstructed_string))
# Note: this is hastily written to give you an idea, I have no idea if it would work properly, probably not
# Well, it does seem to work without bug, at least in my example. That's unexpected lol. Anyway, if you can think of a better solution...!

That is, going through each character of the strings and compare them to reconstruct the strings character by character.

Body:
The way I would do it - written in terrible code. I wrote this pretty hastily

import re
first_input = [
(0  ,  "Lorem ipsum dolor sit amet, consectetur"),
    (1  ,  " adipiscing elit"),
    (0  ,  ". In pellentesque\npharetra ex, at varius sem suscipit ac. "),
    (-1 ,  "Suspendisse luctus\ncondimentum velit a laoreet. "),
    (0  ,  "Donec dolor urna, tempus sed nulla vitae, dignissim varius neque.")
]
second_input = "Lorem ipsum dolor sit amet,\n consectetur adipiscing elit. In pellentesque\npharetra ex, at varius sem\n suscipit ac. Suspendisse luctus\ncondimentum velit a laoreet. Donec dolor urna, tempus sed\n nulla vitae, dignissim varius neque."

first_sanitized = [x[1].replace('\n', '') for x in first_input]
second_sanitized = second_input.replace('\n', '')
newline_positions = [m.start() for m in re.finditer('\n' ,second_input, re.M)]
new_output = []
i = 0
print(second_sanitized)
newlines_so_far = 0
for first_str in first_sanitized:
   print(first_str)
   index = second_sanitized.index(first_str)
   number_of_newlines_in_between = sum([1 for x in newline_positions if (x > index and x < index + len(first_input[i][1]))])
   new_string = second_input[index : (index + len(first_input[i][1]) + number_of_newlines_in_between + newlines_so_far)]
   newlines_so_far += number_of_newlines_in_between
   new_element = (first_input[i][0], new_string)
   new_output.append(new_element)
   i = i + 1


问:
Fri May 29 2020 06:35:59 GMT+0530 (India Standard Time) i want India Standard Time as IST in react js
i want to get timezone name like India Standard Time as IST from Fri May 29 2020 06:35:59 GMT+0530 (India Standard Time)

答:
moment().tz('Asia/Colombo').format('MMMM Do YYYY, h:mm:ss a Z[(IST)]');```

You can format IST using moment JS timezones. https://momentjs.com/timezone/docs/

Body:
moment().tz('Asia/Colombo').format('MMMM Do YYYY, h:mm:ss a Z[(IST)]');

You can format IST using moment JS timezones. https://momentjs.com/timezone/docs/


问:
Slicing in glom?
In short:
How can I slice in glom? That is, being able to specify that I want to extract from several indices (e.g. y = x[(2, 5, 11)]), not just a single one (e.g. y = x[2]).

Simple example: Say I have this data:

d = {'_result': [[1, 'a'], [2, 'b'], [3, 'c']]}
```

<p>To extract a named zip(*) of the "_result" list of lists, I could do this:</p>

<pre class="lang-py prettyprint-override"><code>from glom import Spec
extract = Spec(('_result',
                  lambda x: list(zip(*x)),
                  lambda x: {'x': x[0], 'y': x[1]})).glom
</code>```

And I'd get what I want:

>>> extract(d)
{'x': (1, 2, 3), 'y': ('a', 'b', 'c')}
```

<p>But I'd like to be able to do something like...</p>

<pre class="lang-py prettyprint-override"><code>extract = Spec(('_result', {'x': '*.0', 'y': '*.1'})).glom
</code>```

or

extract = Spec(('_result', {'x': '[:].0', 'y': '[:].1'})).glom
```

<p><strong>An even more advanced wish...</strong></p>

<p>I could imagine such syntactic sugar as being able to specify paths like</p>

<pre class="lang-py prettyprint-override"><code>"a.[2:3, -5:].{'foo', 'bar'}.name"
</code>```

could come in handy. Even (and possibly safer) if it were by an explicit glom.Path definition, such as

from glom import Path
path = Path('a',
            ((slice(2, 3, None), slice(-5, None, None)),),
            {'foo', 'bar'},
            'name')
```

Where in my (probably not best choice) mini-language, the {'foo', 'bar'} means we're extracting the values for both of those keys.

答:
```<code>>>> d = [[1, 'a'], [2, 'b'], [3, 'c']]
>>> glom(d, {'x': [T[0]], 'y': [T[1]]})
{'x': [1, 2, 3], 'y': ['a', 'b', 'c']}
</code>```

glom co-creator here :-)

T has got you covered. Strings are parsed and converted into Path instances.  Paths are convenient and Ts are precise.

If you want to mix them together, you can either join them with a tuple or use the explicit Path constructor.

```<code>>>> Path('a.b', T[1:3])
Path('a.b', T[slice(1, 3, None)])
</code>```

Title: Slicing in glom?

Body:
In short:
How can I slice in glom? That is, being able to specify that I want to extract from several indices (e.g. y = x[(2, 5, 11)]), not just a single one (e.g. y = x[2]).

Simple example: Say I have this data:

d = {'_result': [[1, 'a'], [2, 'b'], [3, 'c']]}

To extract a named zip(*) of the "_result" list of lists, I could do this:

from glom import Spec
extract = Spec(('_result',
                  lambda x: list(zip(*x)),
                  lambda x: {'x': x[0], 'y': x[1]})).glom

And I'd get what I want:

>>> extract(d)
{'x': (1, 2, 3), 'y': ('a', 'b', 'c')}

But I'd like to be able to do something like...

extract = Spec(('_result', {'x': '*.0', 'y': '*.1'})).glom

or

extract = Spec(('_result', {'x': '[:].0', 'y': '[:].1'})).glom

An even more advanced wish...

I could imagine such syntactic sugar as being able to specify paths like

"a.[2:3, -5:].{'foo', 'bar'}.name"

could come in handy. Even (and possibly safer) if it were by an explicit glom.Path definition, such as

from glom import Path
path = Path('a',
            ((slice(2, 3, None), slice(-5, None, None)),),
            {'foo', 'bar'},
            'name')

Where in my (probably not best choice) mini-language, the {'foo', 'bar'} means we're extracting the values for both of those keys.

Body:
>>> d = [[1, 'a'], [2, 'b'], [3, 'c']]
>>> glom(d, {'x': [T[0]], 'y': [T[1]]})
{'x': [1, 2, 3], 'y': ['a', 'b', 'c']}

glom co-creator here :-)

T has got you covered. Strings are parsed and converted into Path instances.  Paths are convenient and Ts are precise.

If you want to mix them together, you can either join them with a tuple or use the explicit Path constructor.

>>> Path('a.b', T[1:3])
Path('a.b', T[slice(1, 3, None)])