问:
my app shows RecyclerView but does now show it's items
Actually my app shows RecyclerView but does now show it's items .
After that I input data in fields and click on btn_add, they are saved in database successfully ,but when I click on Btn-show button in my app to show them, everything works right and it shows recyclerview, but it only shows the "id"item and the other items are not showed.

SecondActivity.java

```<code>    class SecondActivity : AppCompatActivity() {

    private var dbHandle:DatabaseHandler?=null

    lateinit var btn_show:Button
    lateinit var rec:RecyclerView
    lateinit var btn_add:Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)

        dbHandle = DatabaseHandler(this)

        btn_show=findViewById(R.id.show)
        rec=findViewById(R.id.rec)
        btn_add=findViewById(R.id.add)
        var edit_name=findViewById<EditText>(R.id.edit_name)
        var edit_age =findViewById<EditText>(R.id.edit_age)
        var edit_heigth=findViewById<EditText>(R.id.edit_heigth)
        var edit_city=findViewById<EditText>(R.id.edit_city)
        var edit_b_day=findViewById<EditText>(R.id.edit_b_day)
        var edit_b_city=findViewById<EditText>(R.id.edit_b_city)
        var edit_education=findViewById<EditText>(R.id.edit_education)

        val actors=Actors()
        actors.Name=edit_name.text.toString()
        actors.Age=edit_age.text.toString()
        actors.heigth=edit_heigth.text.toString()
        actors.city=edit_city.text.toString()
        actors.bdate=edit_b_day.text.toString()
        actors.bcity=edit_b_city.text.toString()
        actors.education=edit_education.text.toString()

        btn_add.setOnClickListener {
            var success = false
            success=dbHandle!!.addActors(actors)
            Toast.makeText(this,"result: $success", Toast.LENGTH_SHORT).show()
        }

        btn_show.setOnClickListener {
            rec.layoutManager = LinearLayoutManager(this)
            val myList= dbHandle!!.getAllActorsList()
            rec.adapter=RecyclerAdapter(myList,this)}

    }
</code>```

my class:

```<code>    var Name: String = ""
    var Age: String = ""
    var heigth: String = ""
    var city: String = ""
    var bdate:String = ""
    var bcity: String = ""
    var education: String =""

    constructor()
    constructor(
        id: Int?,
        Name: String,
        Age: String,
        heigth: String,
        city: String,
        b_date: String,
        b_city: String,
        education: String,
    ) {
        this.id = id
        this.Name = Name
        this.Age = Age
        this.heigth = heigth
        this.city = city
        this.bdate = b_date
        this.bcity = b_city
        this.education = education
    }

    constructor(
        Name: String,
        Age: String,
        heigth: String,
        city: String,
        b_date: String,
        b_city: String,
        education: String,
    ) {
        this.Name = Name
        this.Age = Age
        this.heigth = heigth
        this.city = city
        this.bdate = b_date
        this.bcity = b_city
        this.education = education
</code>```

RecyclerAdapter:

```<code>    class RecyclerAdapter( val items:ArrayList<Actors>, val context1: Context):RecyclerView.Adapter<viewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): viewHolder {

        return viewHolder(LayoutInflater.from(context1).inflate(R.layout.recycler_item,parent,false))

    }

    override fun onBindViewHolder(holder: viewHolder, position: Int) {

        holder!!.name.text = items.get(position).Name
        holder!!.age.text = items.get(position).Age
        holder!!.id.text = items.get(position).id.toString()
        holder!!.height.text = items.get(position).heigth
        holder!!.city.text = items.get(position).city
        holder!!.bdate.text = items.get(position).bdate
        holder!!.bcity.text = items.get(position).bcity
        holder!!.education.text = items.get(position).education

        holder.itemView.setOnClickListener {
            Toast.makeText(context1, "position:$position....",Toast.LENGTH_SHORT).show()

        }

    }

    override fun getItemCount(): Int {
        return items.size
    }
}

class viewHolder(view: View):RecyclerView.ViewHolder(view){

    val name = view.findViewById<TextView>(R.id.name)
    var age =view.findViewById<TextView>(R.id.age)
    val height = view.findViewById<TextView>(R.id.height)
    val id = view.findViewById<TextView>(R.id.id)
    var city =view.findViewById<TextView>(R.id.city)
    val bdate = view.findViewById<TextView>(R.id.b_date)
    var bcity =view.findViewById<TextView>(R.id.b_city)
    val education = view.findViewById<TextView>(R.id.education)
</code>```

DatabseHandler class:

```<code>
    class DatabaseHandler(context: Context):SQLiteOpenHelper(context,DB_Name,null,DB_Version){

    companion object{

        private val DB_Name = "DB"
        private val DB_Version=1
        private val TABLE_NAME="actors"
        private val ID ="id"
        private val Name = "Name"
        private val Age = "Age"
        private val Heigth="Height"
        private val City = "City"
        private val b_date ="bDate"
        private val b_city="bCity"
        private val Education = "Education"
    }

    override fun onCreate(p0: SQLiteDatabase?) {

        var CREATE_TABLE = "CREATE TABLE $TABLE_NAME" + "($ID INTEGER PRIMARY KEY, $Name TEXT,$Age TEXT, $Heigth TEXT, $City TEXT, $b_date TEXT, $b_city TEXT,$Education TEXT)"
        p0?.execSQL(CREATE_TABLE)
    }

    fun addActors(actors:Actors): Boolean {

        val po = this.writableDatabase
        val values = ContentValues()
        values.put(Name, actors.Name)
        values.put(Age, actors.Age)
        values.put(Heigth,actors.heigth)
        values.put(City, actors.city)
        values.put(b_date, actors.bdate)
        values.put(b_city, actors.bcity)
        values.put(Education, actors.education)

        var success=po.insert(TABLE_NAME,null,values)
        po.close()
        return (Integer.parseInt("$success")!=-1)

    }

    @SuppressLint("Range")
    fun getAllActorsList():ArrayList<Actors>{

        val list =ArrayList<Actors>()
        val p0=readableDatabase
        var selectAll = "SELECT * FROM $TABLE_NAME"
        var cursor = p0.rawQuery(selectAll,null)

        if (cursor!=null){

            if (cursor.moveToFirst()){
                do{
                    val id = cursor.getString(cursor.getColumnIndex(ID))
                    val name = cursor.getString(cursor.getColumnIndex(Name))
                    val age = cursor.getString(cursor.getColumnIndex(Age))
                    val height = cursor.getString(cursor.getColumnIndex(Heigth))
                    val city = cursor.getString(cursor.getColumnIndex(City))
                    val bdate = cursor.getString(cursor.getColumnIndex(b_date))
                    val bcity = cursor.getString(cursor.getColumnIndex(b_city))
                    val education = cursor.getString(cursor.getColumnIndex(Education))

                    list.add(Actors(id.toInt(),name,age,height,city,bdate,bcity,education))
                }
                    while (cursor.moveToNext())
            }
        }
        cursor.close()
        p0.close()
        return list
    }
    override fun onUpgrade(p0: SQLiteDatabase?, p1: Int, p2: Int) {
        TODO("Not yet implemented")
    }
</code>```

activity_second.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SecondActivity"
    android:orientation="vertical">

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="v">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit_id"
        tools:ignore="Autofill,LabelFor,TextFields"
         />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit_name"
        tools:ignore="Autofill,LabelFor,TextFields" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit_age"

        />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit_heigth"
       />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit_city"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit_b_day"
        />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit_b_city"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit_education"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/add"
        android:text="btn_add"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/show"
        android:text="btn_show"/>

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/rec"/>

</LinearLayout>
</code>```

Recycler_item.xml

```<code>    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    xmlns:android="http://schemas.android.com/apk/res/android">

<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/id"
        android:layout_marginLeft="4dp"
        android:textSize="20sp"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/name"
        android:textColor="@color/black"
        android:textSize="20sp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="4dp"
        android:padding="20dp"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/height"
        android:textSize="18sp"
        android:paddingLeft="20dp"
        android:layout_marginLeft="10dp"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/age"
        android:textSize="18sp"
        android:paddingLeft="20dp"
        android:layout_marginLeft="10dp"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/city"
        android:layout_marginLeft="4dp"
        android:textSize="20sp"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/b_date"
        android:textColor="@color/black"
        android:textSize="20sp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="4dp"
        android:padding="20dp"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/b_city"
        android:textSize="18sp"
        android:paddingLeft="20dp"
        android:layout_marginLeft="10dp"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/education"
        android:textSize="18sp"

        android:paddingLeft="20dp"
        android:layout_marginLeft="10dp"/>
    </LinearLayout>

</androidx.cardview.widget.CardView>

</RelativeLayout>

</code>```

答:
Save your data by clicking the Add button. Try it this way.</p>
```<code>btn_add.setOnClickListener {
      val actors = Actors()
      actors.Name = edit_name.text.toString()
      actors.Age = edit_age.text.toString()
      actors.heigth = edit_heigth.text.toString()
      actors.city = edit_city.text.toString()
      actors.bdate = edit_b_day.text.toString()
      actors.bcity = edit_b_city.text.toString()
      actors.education = edit_education.text.toString()

      var success = false
      success = dbHandle!!.addActors(actors)
      Toast.makeText(this, "result: $success", Toast.LENGTH_SHORT).show()
    }
</code>```

Body:
Actually my app shows RecyclerView but does now show it's items .
After that I input data in fields and click on btn_add, they are saved in database successfully ,but when I click on Btn-show button in my app to show them, everything works right and it shows recyclerview, but it only shows the "id"item and the other items are not showed.

SecondActivity.java

    class SecondActivity : AppCompatActivity() {

    private var dbHandle:DatabaseHandler?=null

    lateinit var btn_show:Button
    lateinit var rec:RecyclerView
    lateinit var btn_add:Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)

        dbHandle = DatabaseHandler(this)

        btn_show=findViewById(R.id.show)
        rec=findViewById(R.id.rec)
        btn_add=findViewById(R.id.add)
        var edit_name=findViewById<EditText>(R.id.edit_name)
        var edit_age =findViewById<EditText>(R.id.edit_age)
        var edit_heigth=findViewById<EditText>(R.id.edit_heigth)
        var edit_city=findViewById<EditText>(R.id.edit_city)
        var edit_b_day=findViewById<EditText>(R.id.edit_b_day)
        var edit_b_city=findViewById<EditText>(R.id.edit_b_city)
        var edit_education=findViewById<EditText>(R.id.edit_education)

        val actors=Actors()
        actors.Name=edit_name.text.toString()
        actors.Age=edit_age.text.toString()
        actors.heigth=edit_heigth.text.toString()
        actors.city=edit_city.text.toString()
        actors.bdate=edit_b_day.text.toString()
        actors.bcity=edit_b_city.text.toString()
        actors.education=edit_education.text.toString()

        btn_add.setOnClickListener {
            var success = false
            success=dbHandle!!.addActors(actors)
            Toast.makeText(this,"result: $success", Toast.LENGTH_SHORT).show()
        }

        btn_show.setOnClickListener {
            rec.layoutManager = LinearLayoutManager(this)
            val myList= dbHandle!!.getAllActorsList()
            rec.adapter=RecyclerAdapter(myList,this)}

    }

my class:

    var Name: String = ""
    var Age: String = ""
    var heigth: String = ""
    var city: String = ""
    var bdate:String = ""
    var bcity: String = ""
    var education: String =""

    constructor()
    constructor(
        id: Int?,
        Name: String,
        Age: String,
        heigth: String,
        city: String,
        b_date: String,
        b_city: String,
        education: String,
    ) {
        this.id = id
        this.Name = Name
        this.Age = Age
        this.heigth = heigth
        this.city = city
        this.bdate = b_date
        this.bcity = b_city
        this.education = education
    }

    constructor(
        Name: String,
        Age: String,
        heigth: String,
        city: String,
        b_date: String,
        b_city: String,
        education: String,
    ) {
        this.Name = Name
        this.Age = Age
        this.heigth = heigth
        this.city = city
        this.bdate = b_date
        this.bcity = b_city
        this.education = education

RecyclerAdapter:

    class RecyclerAdapter( val items:ArrayList<Actors>, val context1: Context):RecyclerView.Adapter<viewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): viewHolder {

        return viewHolder(LayoutInflater.from(context1).inflate(R.layout.recycler_item,parent,false))

    }

    override fun onBindViewHolder(holder: viewHolder, position: Int) {

        holder!!.name.text = items.get(position).Name
        holder!!.age.text = items.get(position).Age
        holder!!.id.text = items.get(position).id.toString()
        holder!!.height.text = items.get(position).heigth
        holder!!.city.text = items.get(position).city
        holder!!.bdate.text = items.get(position).bdate
        holder!!.bcity.text = items.get(position).bcity
        holder!!.education.text = items.get(position).education

        holder.itemView.setOnClickListener {
            Toast.makeText(context1, "position:$position....",Toast.LENGTH_SHORT).show()

        }

    }

    override fun getItemCount(): Int {
        return items.size
    }
}

class viewHolder(view: View):RecyclerView.ViewHolder(view){

    val name = view.findViewById<TextView>(R.id.name)
    var age =view.findViewById<TextView>(R.id.age)
    val height = view.findViewById<TextView>(R.id.height)
    val id = view.findViewById<TextView>(R.id.id)
    var city =view.findViewById<TextView>(R.id.city)
    val bdate = view.findViewById<TextView>(R.id.b_date)
    var bcity =view.findViewById<TextView>(R.id.b_city)
    val education = view.findViewById<TextView>(R.id.education)

DatabseHandler class:

    class DatabaseHandler(context: Context):SQLiteOpenHelper(context,DB_Name,null,DB_Version){

    companion object{

        private val DB_Name = "DB"
        private val DB_Version=1
        private val TABLE_NAME="actors"
        private val ID ="id"
        private val Name = "Name"
        private val Age = "Age"
        private val Heigth="Height"
        private val City = "City"
        private val b_date ="bDate"
        private val b_city="bCity"
        private val Education = "Education"
    }

    override fun onCreate(p0: SQLiteDatabase?) {

        var CREATE_TABLE = "CREATE TABLE $TABLE_NAME" + "($ID INTEGER PRIMARY KEY, $Name TEXT,$Age TEXT, $Heigth TEXT, $City TEXT, $b_date TEXT, $b_city TEXT,$Education TEXT)"
        p0?.execSQL(CREATE_TABLE)
    }

    fun addActors(actors:Actors): Boolean {

        val po = this.writableDatabase
        val values = ContentValues()
        values.put(Name, actors.Name)
        values.put(Age, actors.Age)
        values.put(Heigth,actors.heigth)
        values.put(City, actors.city)
        values.put(b_date, actors.bdate)
        values.put(b_city, actors.bcity)
        values.put(Education, actors.education)

        var success=po.insert(TABLE_NAME,null,values)
        po.close()
        return (Integer.parseInt("$success")!=-1)

    }

    @SuppressLint("Range")
    fun getAllActorsList():ArrayList<Actors>{

        val list =ArrayList<Actors>()
        val p0=readableDatabase
        var selectAll = "SELECT * FROM $TABLE_NAME"
        var cursor = p0.rawQuery(selectAll,null)

        if (cursor!=null){

            if (cursor.moveToFirst()){
                do{
                    val id = cursor.getString(cursor.getColumnIndex(ID))
                    val name = cursor.getString(cursor.getColumnIndex(Name))
                    val age = cursor.getString(cursor.getColumnIndex(Age))
                    val height = cursor.getString(cursor.getColumnIndex(Heigth))
                    val city = cursor.getString(cursor.getColumnIndex(City))
                    val bdate = cursor.getString(cursor.getColumnIndex(b_date))
                    val bcity = cursor.getString(cursor.getColumnIndex(b_city))
                    val education = cursor.getString(cursor.getColumnIndex(Education))

                    list.add(Actors(id.toInt(),name,age,height,city,bdate,bcity,education))
                }
                    while (cursor.moveToNext())
            }
        }
        cursor.close()
        p0.close()
        return list
    }
    override fun onUpgrade(p0: SQLiteDatabase?, p1: Int, p2: Int) {
        TODO("Not yet implemented")
    }

activity_second.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SecondActivity"
    android:orientation="vertical">

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="v">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit_id"
        tools:ignore="Autofill,LabelFor,TextFields"
         />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit_name"
        tools:ignore="Autofill,LabelFor,TextFields" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit_age"

        />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit_heigth"
       />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit_city"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit_b_day"
        />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit_b_city"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit_education"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/add"
        android:text="btn_add"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/show"
        android:text="btn_show"/>

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/rec"/>

</LinearLayout>

Recycler_item.xml

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    xmlns:android="http://schemas.android.com/apk/res/android">

<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/id"
        android:layout_marginLeft="4dp"
        android:textSize="20sp"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/name"
        android:textColor="@color/black"
        android:textSize="20sp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="4dp"
        android:padding="20dp"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/height"
        android:textSize="18sp"
        android:paddingLeft="20dp"
        android:layout_marginLeft="10dp"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/age"
        android:textSize="18sp"
        android:paddingLeft="20dp"
        android:layout_marginLeft="10dp"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/city"
        android:layout_marginLeft="4dp"
        android:textSize="20sp"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/b_date"
        android:textColor="@color/black"
        android:textSize="20sp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="4dp"
        android:padding="20dp"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/b_city"
        android:textSize="18sp"
        android:paddingLeft="20dp"
        android:layout_marginLeft="10dp"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/education"
        android:textSize="18sp"

        android:paddingLeft="20dp"
        android:layout_marginLeft="10dp"/>
    </LinearLayout>

</androidx.cardview.widget.CardView>

</RelativeLayout>

Body:
Save your data by clicking the Add button. Try it this way.

btn_add.setOnClickListener {
      val actors = Actors()
      actors.Name = edit_name.text.toString()
      actors.Age = edit_age.text.toString()
      actors.heigth = edit_heigth.text.toString()
      actors.city = edit_city.text.toString()
      actors.bdate = edit_b_day.text.toString()
      actors.bcity = edit_b_city.text.toString()
      actors.education = edit_education.text.toString()

      var success = false
      success = dbHandle!!.addActors(actors)
      Toast.makeText(this, "result: $success", Toast.LENGTH_SHORT).show()
    }


来源: stackexchange

问:
Updating multiple columns using apply function on a single column. The apply function returns two lists
I have a function returning two lists while applying it on a column. I want to map each list on a separate column, while calling the function only once, as I have millions of input rows:

I have tried below code however not getting the desired output:

```<code>def NERTag_ent(a):
    n=nl.ner(a)
    pr=[x[0] for x in n if x[1]=='PERSON']
    org=[y[0] for y in n if y[0]=='ORGANIZATION']
    return(tuple((pr,org))

df['Per'],df['Org']=df['n1'].apply(NERTag_ent)
</code>```

df['Per'] column should contain all the person and df['Org'] should contain all organisation.

答:
This should achieve what you want:</p>
```<code>import pandas

df = pandas.DataFrame(data=[[0, 1, 2], [1, 2, 3]], columns=['a', 'b', 'c'])

def process(val):
    return (val + 1, val + 2)

df[['d', 'e']] = df['c'].apply(process)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a function returning two lists while applying it on a column. I want to map each list on a separate column, while calling the function only once, as I have millions of input rows:

I have tried below code however not getting the desired output:

def NERTag_ent(a):
    n=nl.ner(a)
    pr=[x[0] for x in n if x[1]=='PERSON']
    org=[y[0] for y in n if y[0]=='ORGANIZATION']
    return(tuple((pr,org))

df['Per'],df['Org']=df['n1'].apply(NERTag_ent)

df['Per'] column should contain all the person and df['Org'] should contain all organisation.

Body:
This should achieve what you want:

import pandas

df = pandas.DataFrame(data=[[0, 1, 2], [1, 2, 3]], columns=['a', 'b', 'c'])

def process(val):
    return (val + 1, val + 2)

df[['d', 'e']] = df['c'].apply(process)


问:
Cypress Get Attribute value and store in Variable
I want to get the Attribute value and store in a variable how we can achieve this in cypress

In my case I want to get the complete class value and store it in variable.

This code just give me the attribute class value but how I can store the fetch value in variable

cy.get('div[class*="ui-growl-item-container ui-state-highlight ui-corner-all ui-shadow ui-growl-message"]').invoke('attr', 'class')
```

答:
Here is how I got the value of for attribute in a label tag which had text "Eat" inside.</p>
```<code>cy.contains('Eat').then(($label) => {
    const id = $label.attr('for');
}
</code>```

Body:
Here is how I got the value of for attribute in a label tag which had text "Eat" inside.

cy.contains('Eat').then(($label) => {
    const id = $label.attr('for');
}


问:
Using ClosedXML how to adjust row height to content?
I create cell with text. After that I set WrapText property and column width.

```<code>var cell = worksheet.Cell("A1");
cell.Style.Alignment.WrapText = true;
cell.SetValue("This is very long text");
worksheet.Column(1).Width = 10;
worksheet.Rows().AdjustToContents();
</code>```

The text has been moved by words, but row height is not changed. How to adjust row height to cell content?

答:
I think this is a bug of ClosedXML.
enter link description here

```<code>ws.Row(1).AdjustToContents();
ws.Row(1).ClearHeight();
</code>```

In my case it works.
Version: 0.95.4

ContentLicense: CC BY-SA 3.0

Body:
I create cell with text. After that I set WrapText property and column width.

var cell = worksheet.Cell("A1");
cell.Style.Alignment.WrapText = true;
cell.SetValue("This is very long text");
worksheet.Column(1).Width = 10;
worksheet.Rows().AdjustToContents();

The text has been moved by words, but row height is not changed. How to adjust row height to cell content?

Body:
I think this is a bug of ClosedXML.
enter link description here

ws.Row(1).AdjustToContents();
ws.Row(1).ClearHeight();

In my case it works.
Version: 0.95.4


问:
Send form information to another component
I designed a flash card and I want to change the text of the card when I click on the button, but I do not know how to send the form information to the App component to update the state.
App component

```<code>function App() {
      const [flashCard, setFlashCard] = useState({
        word: "test",
        persianEquivalent: "test",
      });
      const setFlashCardHandler = (e) => {
        setFlashCard({ flashCard: e });
      };
      return (
        <div className="container">
          <Form setFlashCard={setFlashCardHandler} />
          <FlashCard flashCard={flashCard} />
        </div>
      );
    }

export default App;
</code>```

Form component:

```<code>  function Form({ setFlashCard }) {
      const [valueEn, setValueEn] = useState();
      const [valuePer, setValuePer] = useState();
      const setValueHandlerEn = (e) => {
        setValueEn(e.target.value);
      };
      const setValueHandlerPer = (e) => {
        setValuePer(e.target.value);
      };
      const setFlashCardHandler = (e) => {
        e.preventDefault();
        setFlashCard((e)=>{valueEn=e.target[0].value});
      };
      return (
        <form onSubmit={setFlashCardHandler}>
          <input
            id="word-input"
            placeholder="world"
            value={valueEn}
            onChange={setValueHandlerEn}
          />
          <input
            id="persian-equivalent-input"
            placeholder="Equivalent"
            value={valuePer}
            onChange={setValueHandlerPer}
          />
          <button id="submit-btn">send</button>
        </form>
      );
    }

    export default Form;
</code>```

答:
Please add new updateFlashCard props to to component.

Like:

```<code><Form updateFlashCard={(e) => setFlashCard(e)}/>
</code>```

And change value in updateFlashCard state from form component

Like:

```<code>function Form({ updateFlashCard }) {
      const [valueEn, setValueEn] = useState();
      const [valuePer, setValuePer] = useState();
      const setValueHandlerEn = (e) => {
        setValueEn(e.target.value);
      };
      const setValueHandlerPer = (e) => {
        setValuePer(e.target.value);
      };
      const setFlashCardHandler = (e) => {
        e.preventDefault();

        updateFlashCard(e.target[0].value) // update from here

      };
      return (
        <form onSubmit={setFlashCardHandler}>
          <input
            id="word-input"
            placeholder="world"
            value={valueEn}
            onChange={setValueHandlerEn}
          />
          <input
            id="persian-equivalent-input"
            placeholder="Equivalent"
            value={valuePer}
            onChange={setValueHandlerPer}
          />
          <button id="submit-btn">send</button>
        </form>
      );
    }

    export default Form;
</code>```

Body:
I designed a flash card and I want to change the text of the card when I click on the button, but I do not know how to send the form information to the App component to update the state.
App component

function App() {
      const [flashCard, setFlashCard] = useState({
        word: "test",
        persianEquivalent: "test",
      });
      const setFlashCardHandler = (e) => {
        setFlashCard({ flashCard: e });
      };
      return (

          <Form setFlashCard={setFlashCardHandler} />
          <FlashCard flashCard={flashCard} />

      );
    }

export default App;

Form component:

  function Form({ setFlashCard }) {
      const [valueEn, setValueEn] = useState();
      const [valuePer, setValuePer] = useState();
      const setValueHandlerEn = (e) => {
        setValueEn(e.target.value);
      };
      const setValueHandlerPer = (e) => {
        setValuePer(e.target.value);
      };
      const setFlashCardHandler = (e) => {
        e.preventDefault();
        setFlashCard((e)=>{valueEn=e.target[0].value});
      };
      return (
        <form onSubmit={setFlashCardHandler}>
          <input
            id="word-input"
            placeholder="world"
            value={valueEn}
            onChange={setValueHandlerEn}
          />
          <input
            id="persian-equivalent-input"
            placeholder="Equivalent"
            value={valuePer}
            onChange={setValueHandlerPer}
          />
          <button id="submit-btn">send</button>
        </form>
      );
    }

    export default Form;

Body:
Please add new updateFlashCard props to to component.

Like:

<Form updateFlashCard={(e) => setFlashCard(e)}/>

And change value in updateFlashCard state from form component

Like:

function Form({ updateFlashCard }) {
      const [valueEn, setValueEn] = useState();
      const [valuePer, setValuePer] = useState();
      const setValueHandlerEn = (e) => {
        setValueEn(e.target.value);
      };
      const setValueHandlerPer = (e) => {
        setValuePer(e.target.value);
      };
      const setFlashCardHandler = (e) => {
        e.preventDefault();

        updateFlashCard(e.target[0].value) // update from here

      };
      return (
        <form onSubmit={setFlashCardHandler}>
          <input
            id="word-input"
            placeholder="world"
            value={valueEn}
            onChange={setValueHandlerEn}
          />
          <input
            id="persian-equivalent-input"
            placeholder="Equivalent"
            value={valuePer}
            onChange={setValueHandlerPer}
          />
          <button id="submit-btn">send</button>
        </form>
      );
    }

    export default Form;


问:
gridview setNotifiedDataSetChanged() not updating gridview smoothly?
I try to update gridview background color smoothly but it does not work somoothly.
when i scrool gridview at that time it get changed; plz guide me how to do it, below is my code, Thanks you.

```<code>TableGridViewAdapter gridadapter;
 GridView gridview;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

            textViewUname = (TextView) this.findViewById(R.id.userName);
            textViewUname.setText("Welcome , " + HomeActivity.name);

             gridview = (GridView) findViewById(R.id.gridview);
             gridadapter=new TableGridViewAdapter(this);
             gridview.setAdapter(gridadapter);
            //adapter.notifyDataSetChanged();

             UpdateGridview updateGridview=new UpdateGridview();
             updateGridview.execute(TableActivity.this);

            // code for onClick gridview items , It take to that Activity
            gridview.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View v,
                        int position, long id) {
                    ConText.currentPos = position;
                    Intent i = new Intent(TableActivity.this,
                            OrderListActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                            | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                    finish();

                }

            });
        }
    }

}
</code>```

here i tryed to refreshing view in every 20sec

```<code>  private class UpdateGridview extends AsyncTask<Context, Integer, String>
       {
        @Override
        protected String doInBackground( Context... params )
        {

                int i = 0;
                while( i <10)
                {
                        try{

                               gridadapter.notifyDataSetChanged();
                              // gridadapter.refreshItems(gridadapter);
                               gridview.invalidate();

                              //TableGridViewAdapter.refreshItems(gridadapter);
                               Thread.sleep( 20000 );
                               System.out.println("i  called notifyDataSetChanged()=======================");
                                i++;
                        } catch( Exception e ){
                                Log.i("makemachine", e.getMessage() );
                        }
                }
                return "COMPLETE!";
        }

// -- gets called just before thread begins
        @Override
        protected void onPreExecute()
        {
                Log.i( "makemachine", "onPreExecute()" );
                super.onPreExecute();

        }

        @Override
        protected void onProgressUpdate(Integer... values)
        {
                super.onProgressUpdate(values);

        }

        // -- called if the cancel button is pressed
        @Override
        protected void onCancelled()
        {
                super.onCancelled();
               Log.i( "makemachine", "onCancelled()" );

        }

        // -- called as soon as doInBackground method completes
        // -- notice that the third param gets passed to this method
        @Override
        protected void onPostExecute( String result )
        {
                super.onPostExecute(result);
                Log.i( "makemachine", "onPostExecute(): " + result );

        }
</code>```

}

}

答:
Try like this:</p>

```<code>private final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if(msg.arg1 == 1){
                gridadapter.notifyDataSetChanged();
            }
        }
   };

private class UpdateGridview extends AsyncTask<Context, Integer, String>
       {
        @Override
        protected String doInBackground( Context... params )
        {

                int i = 0;
                while( i <10)
                {
                        try{

                              // gridadapter.notifyDataSetChanged();
                              // gridadapter.refreshItems(gridadapter);
                               //gridview.invalidate();
                                 Message msg = handler.obtainMessage();
                                 msg.arg1 = 1;
                                 handler.sendMessage(msg);
                              //TableGridViewAdapter.refreshItems(gridadapter);
                               Thread.sleep( 20000 );
                               System.out.println("i  called notifyDataSetChanged()=======================");
                                i++;
                        } catch( Exception e ){
                                Log.i("makemachine", e.getMessage() );
                        }
                }
                return "COMPLETE!";
        }

// -- gets called just before thread begins
        @Override
        protected void onPreExecute()
        {
                Log.i( "makemachine", "onPreExecute()" );
                super.onPreExecute();

        }

        @Override
        protected void onProgressUpdate(Integer... values)
        {
                super.onProgressUpdate(values);

        }

        // -- called if the cancel button is pressed
        @Override
        protected void onCancelled()
        {
                super.onCancelled();
               Log.i( "makemachine", "onCancelled()" );

        }

        // -- called as soon as doInBackground method completes
        // -- notice that the third param gets passed to this method
        @Override
        protected void onPostExecute( String result )
        {
                super.onPostExecute(result);
                Log.i( "makemachine", "onPostExecute(): " + result );

        }
}

}
</code>```

Body:
I try to update gridview background color smoothly but it does not work somoothly.
when i scrool gridview at that time it get changed; plz guide me how to do it, below is my code, Thanks you.

TableGridViewAdapter gridadapter;
 GridView gridview;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

            textViewUname = (TextView) this.findViewById(R.id.userName);
            textViewUname.setText("Welcome , " + HomeActivity.name);

             gridview = (GridView) findViewById(R.id.gridview);
             gridadapter=new TableGridViewAdapter(this);
             gridview.setAdapter(gridadapter);
            //adapter.notifyDataSetChanged();

             UpdateGridview updateGridview=new UpdateGridview();
             updateGridview.execute(TableActivity.this);

            // code for onClick gridview items , It take to that Activity
            gridview.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View v,
                        int position, long id) {
                    ConText.currentPos = position;
                    Intent i = new Intent(TableActivity.this,
                            OrderListActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                            | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                    finish();

                }

            });
        }
    }

}

here i tryed to refreshing view in every 20sec

  private class UpdateGridview extends AsyncTask<Context, Integer, String>
       {
        @Override
        protected String doInBackground( Context... params )
        {

                int i = 0;
                while( i <10)
                {
                        try{

                               gridadapter.notifyDataSetChanged();
                              // gridadapter.refreshItems(gridadapter);
                               gridview.invalidate();

                              //TableGridViewAdapter.refreshItems(gridadapter);
                               Thread.sleep( 20000 );
                               System.out.println("i  called notifyDataSetChanged()=======================");
                                i++;
                        } catch( Exception e ){
                                Log.i("makemachine", e.getMessage() );
                        }
                }
                return "COMPLETE!";
        }

// -- gets called just before thread begins
        @Override
        protected void onPreExecute()
        {
                Log.i( "makemachine", "onPreExecute()" );
                super.onPreExecute();

        }

        @Override
        protected void onProgressUpdate(Integer... values)
        {
                super.onProgressUpdate(values);

        }

        // -- called if the cancel button is pressed
        @Override
        protected void onCancelled()
        {
                super.onCancelled();
               Log.i( "makemachine", "onCancelled()" );

        }

        // -- called as soon as doInBackground method completes
        // -- notice that the third param gets passed to this method
        @Override
        protected void onPostExecute( String result )
        {
                super.onPostExecute(result);
                Log.i( "makemachine", "onPostExecute(): " + result );

        }

}

}

Body:
Try like this:

private final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if(msg.arg1 == 1){
                gridadapter.notifyDataSetChanged();
            }
        }
   };

private class UpdateGridview extends AsyncTask<Context, Integer, String>
       {
        @Override
        protected String doInBackground( Context... params )
        {

                int i = 0;
                while( i <10)
                {
                        try{

                              // gridadapter.notifyDataSetChanged();
                              // gridadapter.refreshItems(gridadapter);
                               //gridview.invalidate();
                                 Message msg = handler.obtainMessage();
                                 msg.arg1 = 1;
                                 handler.sendMessage(msg);
                              //TableGridViewAdapter.refreshItems(gridadapter);
                               Thread.sleep( 20000 );
                               System.out.println("i  called notifyDataSetChanged()=======================");
                                i++;
                        } catch( Exception e ){
                                Log.i("makemachine", e.getMessage() );
                        }
                }
                return "COMPLETE!";
        }

// -- gets called just before thread begins
        @Override
        protected void onPreExecute()
        {
                Log.i( "makemachine", "onPreExecute()" );
                super.onPreExecute();

        }

        @Override
        protected void onProgressUpdate(Integer... values)
        {
                super.onProgressUpdate(values);

        }

        // -- called if the cancel button is pressed
        @Override
        protected void onCancelled()
        {
                super.onCancelled();
               Log.i( "makemachine", "onCancelled()" );

        }

        // -- called as soon as doInBackground method completes
        // -- notice that the third param gets passed to this method
        @Override
        protected void onPostExecute( String result )
        {
                super.onPostExecute(result);
                Log.i( "makemachine", "onPostExecute(): " + result );

        }
}

}


问:
How to schedule multiple time specific local notifications in flutter
I am developing water drinking reminder app with flutter.
I want to schedule a list of time specified local notifications that user can add to this list and delete from this list. like this

Any help would appreciate, Thanks.

答:
Try Awesome Notifications.

It has many features including seconds precision scheduled notifications.

Sample Snippet:

```<code>Future<void> scheduleNewNotification() async {

        await AwesomeNotifications().createNotification(
            content: NotificationContent(
                id: -1, // -1 is replaced by a random number
                channelKey: 'alerts',
                title: "Huston! The eagle has landed!",
                body:
                    "A small step for a man, but a giant leap to Flutter's community!",
                bigPicture: 'https://storage.googleapis.com/cms-storage-bucket/d406c736e7c4c57f5f61.png',
                largeIcon: 'https://storage.googleapis.com/cms-storage-bucket/0dbfcc7a59cd1cf16282.png',
                //'asset://assets/images/balloons-in-sky.jpg',
                notificationLayout: NotificationLayout.BigPicture,
                payload: {
                  'notificationId': '1234567890'
                }),
            actionButtons: [
              NotificationActionButton(key: 'REDIRECT', label: 'Redirect'),
              NotificationActionButton(
                  key: 'DISMISS',
                  label: 'Dismiss',
                  actionType: ActionType.DismissAction,
                  isDangerousOption: true)
            ],
            schedule: NotificationCalendar.fromDate(
                date: DateTime.now().add(const Duration(seconds: 10))));
      }
</code>```

Body:
Try Awesome Notifications.

It has many features including seconds precision scheduled notifications.

Sample Snippet:

Future<void> scheduleNewNotification() async {

        await AwesomeNotifications().createNotification(
            content: NotificationContent(
                id: -1, // -1 is replaced by a random number
                channelKey: 'alerts',
                title: "Huston! The eagle has landed!",
                body:
                    "A small step for a man, but a giant leap to Flutter's community!",
                bigPicture: 'https://storage.googleapis.com/cms-storage-bucket/d406c736e7c4c57f5f61.png',
                largeIcon: 'https://storage.googleapis.com/cms-storage-bucket/0dbfcc7a59cd1cf16282.png',
                //'asset://assets/images/balloons-in-sky.jpg',
                notificationLayout: NotificationLayout.BigPicture,
                payload: {
                  'notificationId': '1234567890'
                }),
            actionButtons: [
              NotificationActionButton(key: 'REDIRECT', label: 'Redirect'),
              NotificationActionButton(
                  key: 'DISMISS',
                  label: 'Dismiss',
                  actionType: ActionType.DismissAction,
                  isDangerousOption: true)
            ],
            schedule: NotificationCalendar.fromDate(
                date: DateTime.now().add(const Duration(seconds: 10))));
      }


问:
How do I roll a list or numpy array until a certain condition is met?
I have a numpy array

import numpy as np
arr = np.array([70, 80, 90, 100, 110, 120, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                 11, 12, 1, 2, 3, 4, 5, 6])
```
<p>Here, for example, I want to roll the array until one (of the 1s) is at the start and then record what the shift was, but you could image some other arbitrary condition on the roll.</p>
<pre class="lang-py prettyprint-override"><code>arr_expected = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 70, 80, 90, 100, 110, 120])
shift_of_arr = ?
</code>```

How do I roll the array until some condition is met?

Can it be done without a for loop and if so how?

For context: These are monotonically increasing values, but not necessarily with the same interval.

Thanks as ever!

答:
NB. I slightly modified your input to make it non ambiguous (added 10 to the first values to be able to see the direction of rolling). Obviously the answer would work the same on the original data.

You can use numpy.argmax on a boolean array to get the position of the first 1, then use numpy.roll:

```<code>arr = np.array([70, 80, 90, 100, 110, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                 11, 12, 1, 2, 3, 4, 5, 6])

n = np.argmax(arr==1) # 6
arr2 = np.roll(arr, -n)
</code>```

output:

```<code>array([  1,   2,   3,   4,   5,   6,   7,   8,   9,  10,  11,  12,   1,
         2,   3,   4,   5,   6,  70,  80,  90, 100, 110])
</code>```

Body:
I have a numpy array

import numpy as np
arr = np.array([70, 80, 90, 100, 110, 120, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                 11, 12, 1, 2, 3, 4, 5, 6])

Here, for example, I want to roll the array until one (of the 1s) is at the start and then record what the shift was, but you could image some other arbitrary condition on the roll.

arr_expected = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 70, 80, 90, 100, 110, 120])
shift_of_arr = ?

How do I roll the array until some condition is met?

Can it be done without a for loop and if so how?

For context: These are monotonically increasing values, but not necessarily with the same interval.

Thanks as ever!

Body:
NB. I slightly modified your input to make it non ambiguous (added 10 to the first values to be able to see the direction of rolling). Obviously the answer would work the same on the original data.

You can use numpy.argmax on a boolean array to get the position of the first 1, then use numpy.roll:

arr = np.array([70, 80, 90, 100, 110, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                 11, 12, 1, 2, 3, 4, 5, 6])

n = np.argmax(arr==1) # 6
arr2 = np.roll(arr, -n)

output:

array([  1,   2,   3,   4,   5,   6,   7,   8,   9,  10,  11,  12,   1,
         2,   3,   4,   5,   6,  70,  80,  90, 100, 110])


问:
Ranking date column in pyspark
I have the following data frame in pyspark:

```<code>>>> df.show()
+----------+------+
|  date_col|counts|
+----------+------+
|2022-02-05|350647|
|2022-02-06|313091|
+----------+------+
</code>```

I want to create a resultant data frame which ranks the date_col in increasing order:

```<code>>>> df.show()
+----------+------+---------+
|  date_col|counts|order_col|
+----------+------+---------+
|2022-02-05|350647|        2|
|2022-02-06|313091|        1|
+----------+------+---------+
</code>```

How can we achieve this?

Following script can be used to created dataframe df:

```<code>from datetime import datetime, date
from pyspark.sql import Row
from pyspark.sql import SparkSession
df = spark.createDataFrame([
    Row(date_col=date(2022, 02, 05), count=350647 ),
    Row(date_col=date(2022, 02, 06), count=313091 ),
])
df.show()
</code>```

Title: Ranking date column in pyspark

Body:
I have the following data frame in pyspark:

>>> df.show()
+----------+------+
|  date_col|counts|
+----------+------+
|2022-02-05|350647|
|2022-02-06|313091|
+----------+------+

I want to create a resultant data frame which ranks the date_col in increasing order:

>>> df.show()
+----------+------+---------+
|  date_col|counts|order_col|
+----------+------+---------+
|2022-02-05|350647|        2|
|2022-02-06|313091|        1|
+----------+------+---------+

How can we achieve this?

Following script can be used to created dataframe df:

from datetime import datetime, date
from pyspark.sql import Row
from pyspark.sql import SparkSession
df = spark.createDataFrame([
    Row(date_col=date(2022, 02, 05), count=350647 ),
    Row(date_col=date(2022, 02, 06), count=313091 ),
])
df.show()

Body:
You can easily do this with Rank , in conjunction with Window

Data Preparation

from pyspark import SparkContext
from pyspark.sql import SQLContext
import pyspark.sql.functions as F
from pyspark.sql import Window

sc = SparkContext.getOrCreate()
sql = SQLContext(sc)

d = {
        'date_col':['2022-02-05', '2022-02-06', '2022-02-07', '2022-02-08'],
        'counts':[350647, 313091, 317791, 312145],
    }

sparkDF = sql.createDataFrame(pd.DataFrame(d))

sparkDF.show()

+----------+------+
|  date_col|counts|
+----------+------+
|2022-02-05|350647|
|2022-02-06|313091|
|2022-02-07|317791|
|2022-02-08|312145|
+----------+------+

Rank

window = Window.orderBy(F.col('date_col').desc())

sparkDF = sparkDF.withColumn('order_col',F.rank().over(window))

sparkDF.show()

+----------+------+---------+
|  date_col|counts|order_col|
+----------+------+---------+
|2022-02-08|312145|        1|
|2022-02-07|317791|        2|
|2022-02-06|313091|        3|
|2022-02-05|350647|        4|
+----------+------+---------+

Rank - SparkSQL

sql.sql(
    """
    SELECT
         date_col
        ,counts
        ,RANK() OVER( ORDER BY date_col DESC) as order_col
    FROM TB1
    """
).show()

+----------+------+---------+
|  date_col|counts|order_col|
+----------+------+---------+
|2022-02-08|312145|        1|
|2022-02-07|317791|        2|
|2022-02-06|313091|        3|
|2022-02-05|350647|        4|
+----------+------+---------+


问:
Imported excel sheet has a date column that follows two different formats (MM-DD-YYYY) and (DD-MM-YYYY) at the same time. How do I fix this?
I have an imported excel file that has date column that shows date and time as shown below .

The weird thing is the dates follow two different formats at the same time. How do I force excel to follow either one of the two formats?

答:
You can Do the following procedure which is easiest and best for you

Select Column A

Press CTRL+1 OR Go to Custom Formatting

go to Custom in the most last option

in the bar, copy this format

```<code>dd-mm-yyyy hh:mm:ss
</code>```

or if you want the time in AM/PM then copy following format

```<code>dd-mm-yyyy hh:mm:ss AM/PM
</code>```

Press Enter, and everything will be in the same format

Body:
You can Do the following procedure which is easiest and best for you

Select Column A

Press CTRL+1 OR Go to Custom Formatting

go to Custom in the most last option

in the bar, copy this format

dd-mm-yyyy hh:mm:ss

or if you want the time in AM/PM then copy following format

dd-mm-yyyy hh:mm:ss AM/PM

Press Enter, and everything will be in the same format


问:
How to compare 2 stage files and find out unique values from stage file 1 in OIC XSLT Mapper?
I have two stage files where I have to compare Job_Title from file 1 with JOB_NAME of file 2, I have to display the unique Job_Title values from file 1. My code is working as expected

File 1:

'

```<code><ReadResponse xmlns="http://xmlns.oracle.com/cloud/adapter/stagefile/ReadFilteredInputFile_REQUEST/types">
  <Records xmlns="http://TargetNamespace.com/fileReference/ReadFilteredInputFile">
    <Record>
      <Last_Name>Abbassi</Last_Name>
      <First_Name>Bob</First_Name>
      <Work_Contact_Work_Email>babbassi@xyz.com</Work_Contact_Work_Email>
      <Hire_Date>6/25/2012</Hire_Date>
      <Job_Title_Description>ASSOCIATE DIRECTOR</Job_Title_Description>
      <Job_Title_Code>ADIR</Job_Title_Code>
      <Home_Department_Description>Finance</Home_Department_Description>
      <Home_Department>121</Home_Department>
      <Rehire_Date></Rehire_Date>
      <Termination_Date></Termination_Date>
      <Position_ID>DXM001019</Position_ID>
      <Position_Status>Active</Position_Status>
      <Reports_To_Position_ID>DXM001077</Reports_To_Position_ID>
      <Reports_To_Name>Lee, Todd</Reports_To_Name>
      <This_is_a_Management_position>No</This_is_a_Management_position>
      <Job_Title>Associate Director, FP&A</Job_Title>
    </Record>
    <Record>
      <Last_Name>Abejuela</Last_Name>
      <First_Name>Jowdy</First_Name>
      <Work_Contact_Work_Email>jabejuela@xyz.com</Work_Contact_Work_Email>
      <Hire_Date>12/9/2019</Hire_Date>
      <Job_Title_Description>SENIOR MANAGER</Job_Title_Description>
      <Job_Title_Code>SRMG</Job_Title_Code>
      <Home_Department_Description>Quality General</Home_Department_Description>
      <Home_Department>461</Home_Department>
      <Rehire_Date></Rehire_Date>
      <Termination_Date></Termination_Date>
      <Position_ID>DXM001514</Position_ID>
      <Position_Status>Active</Position_Status>
      <Reports_To_Position_ID>DXM001629</Reports_To_Position_ID>
      <Reports_To_Name>Golden, Kihlon</Reports_To_Name>
      <This_is_a_Management_position>No</This_is_a_Management_position>
      <Job_Title>Senior Manager, QA</Job_Title>
    </Record>
    <Record>
      <Last_Name>Acosta</Last_Name>
      <First_Name>Andrea</First_Name>
      <Work_Contact_Work_Email>aacosta@xyz.com</Work_Contact_Work_Email>
      <Hire_Date>5/18/2020</Hire_Date>
      <Job_Title_Description>RESEARCH ASSOCIATE</Job_Title_Description>
      <Job_Title_Code>RA</Job_Title_Code>
      <Home_Department_Description>Analytical</Home_Department_Description>
      <Home_Department>442</Home_Department>
      <Rehire_Date></Rehire_Date>
      <Termination_Date></Termination_Date>
      <Position_ID>DXM001536</Position_ID>
      <Position_Status>Active</Position_Status>
      <Reports_To_Position_ID>DXM001026</Reports_To_Position_ID>
      <Reports_To_Name>Kuehne, Henriette</Reports_To_Name>
      <This_is_a_Management_position>No</This_is_a_Management_position>
      <Job_Title>Research Associate</Job_Title>
    </Record>
  </Records>
</ReadResponse>
</code>```

'

File 2:
'

```<code><ReadResponse xmlns="http://xmlns.oracle.com/cloud/adapter/stagefile/ReadDecodedOTBIJobsResponse_REQUEST/types">
  <JobSet xmlns="http://TargetNamespace.com/fileReference/ReadDecodedOTBIJobsResponse">
    <Job>
      <JOB_ID>300000004123258</JOB_ID>
      <JOB_CODE>0002</JOB_CODE>
      <JOB_NAME>Senior Manager, QA</JOB_NAME>
    </Job>
    <Job>
      <JOB_ID>300000004123195</JOB_ID>
      <JOB_CODE>0001</JOB_CODE>
      <JOB_NAME>Associate Director, FP&A</JOB_NAME>
    </Job>
  </JobSet>
</ReadResponse>
</code>```

'
Expected output:
'

```<code><JobSet>
    <Job>
      <Job_Title>Research Associate</JobTitle>
    </Job>
  </JobSet>
</code>```

'

My code:

```<code><ns50:NewJobSet>
<xsl:for-each select="$ReadFilteredInputFile/nsmpr8:ReadResponse/nsmpr3:Records/nsmpr3:Record">
<xsl:variable name="jobTitle" select="nsmpr3:Job_Title"/>
<xsl:for-each select="$ReadDecodedOTBIJobsResponse/nsmpr7:ReadResponse/ns37:JobSet/ns37:Job">
<xsl:variable name="jobName" select="ns37:JOB_NAME"/>
<xsl:choose>
<xsl:when test="ns37:JOB_NAME = $jobTitle"/>
<xsl:otherwise>
<ns50:NewJob>
<ns50:Job_Title>
<xsl:value-of select="$jobName"/>
</ns50:Job_Title>
</ns50:NewJob>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:for-each>
</ns50:NewJobSet>
</code>```

My code is returning duplicates incase if there any matching records between two file, Could anyone please help to fix this ?

答:
I would use a key

```<code><xsl:key name="jobs" match="Job" use="JOB_NAME" xpath-default-namespace="http://TargetNamespace.com/fileReference/ReadDecodedOTBIJobsResponse"/>
</code>```

and then check e.g.

```<code>  <xsl:template match="Record/Job_Title[not(key('jobs', ., $jobs))]" xpath-default-namespace="http://TargetNamespace.com/fileReference/ReadFilteredInputFile">
    <Job_Title>
      <xsl:value-of select="."/>
    </Job_Title>
  </xsl:template>
</code>```

where $jobs is the variable holding your second document.

And an empty template for those elements that have references in the second file e.g. <xsl:template match="Record/Job_Title[key('jobs', ., $jobs)]" xpath-default-namespace="http://TargetNamespace.com/fileReference/ReadFilteredInputFile"/>

Body:
I have two stage files where I have to compare Job_Title from file 1 with JOB_NAME of file 2, I have to display the unique Job_Title values from file 1. My code is working as expected

File 1:

'

<ReadResponse xmlns="http://xmlns.oracle.com/cloud/adapter/stagefile/ReadFilteredInputFile_REQUEST/types">
  <Records xmlns="http://TargetNamespace.com/fileReference/ReadFilteredInputFile">
    <Record>
      <Last_Name>Abbassi</Last_Name>
      <First_Name>Bob</First_Name>
      <Work_Contact_Work_Email>babbassi@xyz.com</Work_Contact_Work_Email>
      <Hire_Date>6/25/2012</Hire_Date>
      <Job_Title_Description>ASSOCIATE DIRECTOR</Job_Title_Description>
      <Job_Title_Code>ADIR</Job_Title_Code>
      <Home_Department_Description>Finance</Home_Department_Description>
      <Home_Department>121</Home_Department>
      <Rehire_Date></Rehire_Date>
      <Termination_Date></Termination_Date>
      <Position_ID>DXM001019</Position_ID>
      <Position_Status>Active</Position_Status>
      <Reports_To_Position_ID>DXM001077</Reports_To_Position_ID>
      <Reports_To_Name>Lee, Todd</Reports_To_Name>
      <This_is_a_Management_position>No</This_is_a_Management_position>
      <Job_Title>Associate Director, FP&A</Job_Title>
    </Record>
    <Record>
      <Last_Name>Abejuela</Last_Name>
      <First_Name>Jowdy</First_Name>
      <Work_Contact_Work_Email>jabejuela@xyz.com</Work_Contact_Work_Email>
      <Hire_Date>12/9/2019</Hire_Date>
      <Job_Title_Description>SENIOR MANAGER</Job_Title_Description>
      <Job_Title_Code>SRMG</Job_Title_Code>
      <Home_Department_Description>Quality General</Home_Department_Description>
      <Home_Department>461</Home_Department>
      <Rehire_Date></Rehire_Date>
      <Termination_Date></Termination_Date>
      <Position_ID>DXM001514</Position_ID>
      <Position_Status>Active</Position_Status>
      <Reports_To_Position_ID>DXM001629</Reports_To_Position_ID>
      <Reports_To_Name>Golden, Kihlon</Reports_To_Name>
      <This_is_a_Management_position>No</This_is_a_Management_position>
      <Job_Title>Senior Manager, QA</Job_Title>
    </Record>
    <Record>
      <Last_Name>Acosta</Last_Name>
      <First_Name>Andrea</First_Name>
      <Work_Contact_Work_Email>aacosta@xyz.com</Work_Contact_Work_Email>
      <Hire_Date>5/18/2020</Hire_Date>
      <Job_Title_Description>RESEARCH ASSOCIATE</Job_Title_Description>
      <Job_Title_Code>RA</Job_Title_Code>
      <Home_Department_Description>Analytical</Home_Department_Description>
      <Home_Department>442</Home_Department>
      <Rehire_Date></Rehire_Date>
      <Termination_Date></Termination_Date>
      <Position_ID>DXM001536</Position_ID>
      <Position_Status>Active</Position_Status>
      <Reports_To_Position_ID>DXM001026</Reports_To_Position_ID>
      <Reports_To_Name>Kuehne, Henriette</Reports_To_Name>
      <This_is_a_Management_position>No</This_is_a_Management_position>
      <Job_Title>Research Associate</Job_Title>
    </Record>
  </Records>
</ReadResponse>

'

File 2:
'

<ReadResponse xmlns="http://xmlns.oracle.com/cloud/adapter/stagefile/ReadDecodedOTBIJobsResponse_REQUEST/types">
  <JobSet xmlns="http://TargetNamespace.com/fileReference/ReadDecodedOTBIJobsResponse">
    <Job>
      <JOB_ID>300000004123258</JOB_ID>
      <JOB_CODE>0002</JOB_CODE>
      <JOB_NAME>Senior Manager, QA</JOB_NAME>
    </Job>
    <Job>
      <JOB_ID>300000004123195</JOB_ID>
      <JOB_CODE>0001</JOB_CODE>
      <JOB_NAME>Associate Director, FP&A</JOB_NAME>
    </Job>
  </JobSet>
</ReadResponse>

'
Expected output:
'

<JobSet>
    <Job>
      <Job_Title>Research Associate</JobTitle>
    </Job>
  </JobSet>

'

My code:

<ns50:NewJobSet>
<xsl:for-each select="$ReadFilteredInputFile/nsmpr8:ReadResponse/nsmpr3:Records/nsmpr3:Record">
<xsl:variable name="jobTitle" select="nsmpr3:Job_Title"/>
<xsl:for-each select="$ReadDecodedOTBIJobsResponse/nsmpr7:ReadResponse/ns37:JobSet/ns37:Job">
<xsl:variable name="jobName" select="ns37:JOB_NAME"/>
<xsl:choose>
<xsl:when test="ns37:JOB_NAME = $jobTitle"/>
<xsl:otherwise>
<ns50:NewJob>
<ns50:Job_Title>
<xsl:value-of select="$jobName"/>
</ns50:Job_Title>
</ns50:NewJob>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:for-each>
</ns50:NewJobSet>

My code is returning duplicates incase if there any matching records between two file, Could anyone please help to fix this ?

Body:
I would use a key

<xsl:key name="jobs" match="Job" use="JOB_NAME" xpath-default-namespace="http://TargetNamespace.com/fileReference/ReadDecodedOTBIJobsResponse"/>

and then check e.g.

  <xsl:template match="Record/Job_Title[not(key('jobs', ., $jobs))]" xpath-default-namespace="http://TargetNamespace.com/fileReference/ReadFilteredInputFile">
    <Job_Title>
      <xsl:value-of select="."/>
    </Job_Title>
  </xsl:template>

where $jobs is the variable holding your second document.

And an empty template for those elements that have references in the second file e.g. <xsl:template match="Record/Job_Title[key('jobs', ., $jobs)]" xpath-default-namespace="http://TargetNamespace.com/fileReference/ReadFilteredInputFile"/>


问:
Error by changing all the date format in R
I'm trying to change the format from all the dates in one column. I tried it with strftime, as.Date and with parse_date, all giving me some sort of issue. The column includes 2200 different times currently expressed in the following format: Feb-03-2022, it should be expressed as: "%B %d %Y", how could I modify all dates?

```<code>ethereum <- read_csv('ethereum_2022-01-04_2022-02-03.csv')
head(ethereum)
# Changing date format in the dataset
ethereum$Date <- parse_date(ethereum$`Date`, "%d-%b-%y")
head(ethereum$Date)
# Naming the datatype and the timeseries
ds<- ethereum$Date
y<- ethereum$`Close`
df<- data.frame(ds,y)
View(df)

</code>```

When I try with this code, I get the following error:

```<code>Warning: 2200 parsing failures.
row col           expected      actual
  1  -- date like %d-%b-%y Feb-03-2022
  2  -- date like %d-%b-%y Feb-02-2022
  3  -- date like %d-%b-%y Feb-01-2022
  4  -- date like %d-%b-%y Jan-31-2022
  5  -- date like %d-%b-%y Jan-30-2022
... ... .................. ...........
See problems(...) for more details.
</code>```

答:
You can convert the vector to the date format and then apply any desired formatting.

```<code>vec_str <- c("Feb-03-2022", "Feb-02-2022", "Jan-31-2022", "Jan-30-2022")
vec_dates <- as.Date(x = vec_str, format = "%b-%d-%Y")
vec_dates_str <- format(vec_dates, "%B %d %y")
vec_dates_str
# [1] "February 03 22" "February 02 22" "January 31 22"  "January 30 22"
</code>```

For convenience of applying in data frame you can wrap this behaviour in a function:

```<code>my_date_transform <- function(x,date_in_format = "%b-%d-%Y",
                              date_out_format = "%B-%d-%Y") {
    x_dates <- as.Date(x = x, format = date_in_format)
    format(x = vec_dates, date_out_format)
  }

my_date_transform(x = vec_str)
</code>```

Example

```<code>sample_data <- data.frame(original_date_str = vec_str)
sample_data$new_date_format <- my_date_transform(sample_data$original_date_str)
sample_data
# >> sample_data
# original_date_str  new_date_format
# 1       Feb-03-2022 February-03-2022
# 2       Feb-02-2022 February-02-2022
# 3       Jan-31-2022  January-31-2022
# 4       Jan-30-2022  January-30-2022
</code>```

You can then apply your function to a data frame

Body:
I'm trying to change the format from all the dates in one column. I tried it with strftime, as.Date and with parse_date, all giving me some sort of issue. The column includes 2200 different times currently expressed in the following format: Feb-03-2022, it should be expressed as: "%B %d %Y", how could I modify all dates?

ethereum <- read_csv('ethereum_2022-01-04_2022-02-03.csv')
head(ethereum)
# Changing date format in the dataset
ethereum$Date <- parse_date(ethereum$`Date`, "%d-%b-%y")
head(ethereum$Date)
# Naming the datatype and the timeseries
ds<- ethereum$Date
y<- ethereum$`Close`
df<- data.frame(ds,y)
View(df)

When I try with this code, I get the following error:

Warning: 2200 parsing failures.
row col           expected      actual
  1  -- date like %d-%b-%y Feb-03-2022
  2  -- date like %d-%b-%y Feb-02-2022
  3  -- date like %d-%b-%y Feb-01-2022
  4  -- date like %d-%b-%y Jan-31-2022
  5  -- date like %d-%b-%y Jan-30-2022
... ... .................. ...........
See problems(...) for more details.

Body:
You can convert the vector to the date format and then apply any desired formatting.

vec_str <- c("Feb-03-2022", "Feb-02-2022", "Jan-31-2022", "Jan-30-2022")
vec_dates <- as.Date(x = vec_str, format = "%b-%d-%Y")
vec_dates_str <- format(vec_dates, "%B %d %y")
vec_dates_str
# [1] "February 03 22" "February 02 22" "January 31 22"  "January 30 22"

For convenience of applying in data frame you can wrap this behaviour in a function:

my_date_transform <- function(x,date_in_format = "%b-%d-%Y",
                              date_out_format = "%B-%d-%Y") {
    x_dates <- as.Date(x = x, format = date_in_format)
    format(x = vec_dates, date_out_format)
  }

my_date_transform(x = vec_str)

Example

sample_data <- data.frame(original_date_str = vec_str)
sample_data$new_date_format <- my_date_transform(sample_data$original_date_str)
sample_data
# >> sample_data
# original_date_str  new_date_format
# 1       Feb-03-2022 February-03-2022
# 2       Feb-02-2022 February-02-2022
# 3       Jan-31-2022  January-31-2022
# 4       Jan-30-2022  January-30-2022

You can then apply your function to a data frame


问:
Helm parallel execution causing release in pending install state
I have a CircleCI workflow, where on any merge to the master branch it builds the code, creates Docker image, and runs helm upgrade to update the latest build to the k8s cluster.

I am facing issues with helm where two merges happened on the master branch often and CircleCI tries to run two helm upgrades simultaneously and the helm starts behaving weirdly.

Many of the time releases struck in the pending-install state and I have to manually rollback. Even after rollback, many orphan k8s objects were left behind and I need to delete them manually.

I read the helm code and found there is a mutex lock that will prevent the parallel release. I doubt since helm mutex does not maintain explicit lock (remote lock) and my CircleCI is running the helm upgrade in 2 different sessions (2 different shells) the helm is not aware of the release in progress and causing this issue.

I am not sure how to handle this use case or if anyone has faced this issue in the past where helm left the orphan objects behind (mainly, cronjobs and ingress)?

A workaround I can think of is to stop the parallel build by checking helm status before running the helm upgrade, which is not idle.

K8S version - 1.21

Helm version - 3.7.2

答:
The problem you describe is mainly related to Helm. You rightly note that workaround can be found:

A workaround I can think of is to stop the parallel build by checking helm status before running the helm upgrade, which is not idle.

Overall, this feature has had a lot of bugs in the past, and it's very possible that it doesn't work as it should again.

This error can also often be caused by duplicate env variable keys and the solution is described in this question and this github issue.

Look also at this topic about  parallel helm installs and use --concurrency=N flag.

When it comes to this:

I have a 70:30 success: fail ratio. This is weird and hard to understand.

Try checking your logs to see what may have gone wrong. Maybe you're running out of resources (for example, memory)? I tried to recreate this problem, but for me the solution was to remove duplicate kyes. You can also report a bug on github.


问:
Unsupported Resource ARN In Policy
I am trying to create an S3 bucket for my Next JS App to serve all images.

When going to the Object URL, I receive this error:

```<code><Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<RequestId>6SB4RB915NRGND12</RequestId>
<HostId>nPvYg2FlnBW9cmG+R4HmMI5K++WgIftGt/FO1WZ6IFZg2qwhAO+vbjC3AM698PP9+p8h5O1WlzU=</HostId>
</Error>
</code>```

I have therefore, attempted to create an Access Policy for the s3 bucket directory, but have an issue on the Resource line:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowPublicRead",
            "Principal": "*",
            "Effect": "Allow",
            "Action": ["s3:getObject"],
            "Resource": ["arn:aws:s3:::hiredinchina-images/*"]
        }
    ]
}
</code>```

The issue: "Unsuppored Resource ARN In Policy"

Bonus: If you could also help me just make these objects available for my website, that'd be even better. Any tips welcomed. This is my first attempt.

答:
I think you shoud remove the [] in resource line.

If you want to use S3 to host website, there are a lot of blogs for that. For NextJS with S3, you can read here: https://dev.to/parmentierchristophe/how-to-deploy-static-next-js-to-aws-s3-1d4f

Title: Unsupported Resource ARN In Policy

Body:
I am trying to create an S3 bucket for my Next JS App to serve all images.

When going to the Object URL, I receive this error:

<Error>
AccessDenied
<Message>Access Denied</Message>
<RequestId>6SB4RB915NRGND12</RequestId>
<HostId>nPvYg2FlnBW9cmG+R4HmMI5K++WgIftGt/FO1WZ6IFZg2qwhAO+vbjC3AM698PP9+p8h5O1WlzU=</HostId>
</Error>

I have therefore, attempted to create an Access Policy for the s3 bucket directory, but have an issue on the Resource line:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowPublicRead",
            "Principal": "*",
            "Effect": "Allow",
            "Action": ["s3:getObject"],
            "Resource": ["arn:aws:s3:::hiredinchina-images/*"]
        }
    ]
}

The issue: "Unsuppored Resource ARN In Policy"

Bonus: If you could also help me just make these objects available for my website, that'd be even better. Any tips welcomed. This is my first attempt.


问:
Horizontally align text from two different divs
I have the following structure of html code :

```<code><link rel="stylesheet" href="test.css" />

<div class="row">
  <div class="container">
    <p class="content">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
      veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
      commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
      velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
      cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
      est laborum.
    </p>
    <p class="align">Should be aligned</p>
  </div>

  <div class="container">
    <p class="content">Very short text</p>

    <p class="align">Should be aligned</p>
    <p>Some more text here</p>
  </div>
</div>
</code>```

Here is my css :

```<code>.container {
  display: flex;
  flex-direction: column;
  width: 40%;
  margin-right: 20px;
}

.row {
  display: flex;
  flex-direction: row;
}
</code>```

I am trying to find a way to horizontally align the two element with the align class but I can not figure it out. I have to precise that the content of the element with "content" class could be anything so I need a solution that works in every case.

(If you have a solution using some Js code it is ok)

Here is a Jsfiddle demo.

Actual result is this :

And this is what I want to achieve :

The text should go where the arrow point to be aligned with the left text, and the "Some more text" should be after the aligned text I hope it's clear now

Thank you very much for your time !

答:
It's looking great except that you need to remove the flex-direction for the .container div and add this instead

```<code>.row {
flex-flow: row nowrap;
}
</code>```

For the two children divs

```<code>.container{
display: flex;
flex-direction: column;
justify-content: center;
}
</code>```

Since Flexbox isn't supported by IE 10 and below, you should consider checking this demo

https://www.w3schools.com/howto/howto_css_two_columns.asp

Body:
I have the following structure of html code :

<link rel="stylesheet" href="test.css" />

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
      veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
      commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
      velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
      cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
      est laborum.

Should be aligned

Very short text

Should be aligned

Some more text here

Here is my css :

.container {
  display: flex;
  flex-direction: column;
  width: 40%;
  margin-right: 20px;
}

.row {
  display: flex;
  flex-direction: row;
}

I am trying to find a way to horizontally align the two element with the align class but I can not figure it out. I have to precise that the content of the element with "content" class could be anything so I need a solution that works in every case.

(If you have a solution using some Js code it is ok)

Here is a Jsfiddle demo.

Actual result is this :

And this is what I want to achieve :

The text should go where the arrow point to be aligned with the left text, and the "Some more text" should be after the aligned text I hope it's clear now

Thank you very much for your time !

Body:
It's looking great except that you need to remove the flex-direction for the .container div and add this instead

.row {
flex-flow: row nowrap;
}

For the two children divs

.container{
display: flex;
flex-direction: column;
justify-content: center;
}

Since Flexbox isn't supported by IE 10 and below, you should consider checking this demo

https://www.w3schools.com/howto/howto_css_two_columns.asp


问:
ASP .NET Core MVC Entity Framework - add data into many-to-many relationship
I would like to insert data into TripApplicationUser table - to save that for example that Jake has enrolled for a trip to London. The table is in my SQL Server in Visual Studio. It has 2 columns: TripId and ApplicationUserId. What should I do with my databaseContext object?</p>
```<code>public class ApplicationUser : IdentityUser
    {
        [PersonalData]
        [Column(TypeName = "nvarchar(MAX)")]
        public string FirstName { get; set; }
        [PersonalData]
        [Column(TypeName = "nvarchar(MAX)")]
        public string Surname { get; set; }
        [PersonalData]
        [Column(TypeName = "nvarchar(MAX)")]
        public string BirthDate { get; set; }

        public ICollection<TripApplicationUser> TripApplicationUsers { get; set; }
    }

public class Trip
    {
        public int TripId { get; set; }
        public string TripDate { get; set; }
        public int TripDuration { get; set; }
        public int TripLength { get; set; }
        public int TripSeats { get; set; }

        public int TrailId { get; set; }
        public Trail Trail { get; set; }

        public ICollection<TripApplicationUser> TripApplicationUsers { get; set; }
    }

public class TripApplicationUser
    {
        public int TripId { get; set; }
        public Trip Trip { get; set; }
        public string ApplicationUserId { get; set; }
        public ApplicationUser ApplicationUser { get; set; }
    }
</code>```

答:
1.First way:

Instantiate the relational table and configure the relationship between the other two tables in the relational table.

Demo1 as below:

Product.cs:

```<code>using System.Collections.Generic;

namespace MTM2.Models
{
    public partial class Product
    {
        public long ProductID { get; set; }
        public string ProductName { get; set; }

        //navigation property to Supplier
        public virtual ICollection<ProductSupplier> Supplier { get; set; }
    }
}
</code>```

Supplier.cs:

```<code>using System.Collections.Generic;

    namespace MTM2.Models
    {
        public partial class Supplier
        {

            public long SupplierID { get; set; }
            public string SupplierName { get; set; }

            // navigation property to Product
            public virtual ICollection<ProductSupplier> Product { get; set; }
        }
    }
</code>```

MTM2Context.cs:

```<code>using Microsoft.EntityFrameworkCore;
using MTM2.Models;

namespace MTM2.Data
{
    public class MTM2Context: DbContext

    {
        public MTM2Context(DbContextOptions<MTM2Context> options)
               : base(options)
        {
        }

        public DbSet<Product> Product { get; set; }
        public DbSet<Supplier> Supplier { get; set; }

        public DbSet<ProductSupplier> ProductSupplier { get; set; }
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            builder.Entity<ProductSupplier>().HasKey(i => new { i.ProductID, i.SupplierID });
        }
    }
}
</code>```

ProductSupplier.cs

```<code>using System.ComponentModel.DataAnnotations;

namespace MTM2.Models
{
    public class ProductSupplier
    {
        [Key]
        public long ProductID { get; set; }
        public Product Product { get; set; }
        [Key]
        public long SupplierID { get; set; }
        public Supplier Supplier { get; set; }
    }
}
</code>```

HomeController .cs:

```<code>public class HomeController : Controller
    {
        private readonly MTM2Context conn;

        public HomeController(MTM2Context context)
        {
            conn = context;
        }

        public IActionResult Index()
        {
            var A1Product = new Product() { ProductName = "A1" };
            var A2Product = new Product() { ProductName = "A2" };
            var supplier1 = new Supplier() { SupplierName = "B1" };
            var supplier2 = new Supplier() { SupplierName = "B2" };
            var pslist = new List<ProductSupplier>()
            {
                new ProductSupplier() { Product = A1Product, Supplier = supplier1 },
                new ProductSupplier() { Product = A1Product, Supplier = supplier2 },

                new ProductSupplier() { Product = A2Product, Supplier = supplier1 },
                new ProductSupplier() { Product = A2Product, Supplier = supplier2 },

            };
            conn.ProductSupplier.AddRange(pslist);

            conn.SaveChanges();
            return View();
        }
    }
</code>```

Result:

2.Second way:

when data do not exist in tables, add instances to context, add an instance to navigation property and call SaveChanges method from context. That is possible because Entity Framework, at the time of insert, puts primary key value (if Identity, AutoIncrement) in correspondent entity’s property inserted.

Demo 2 as below:

Product.cs:

```<code>using System.Collections.Generic;

namespace MtM.Models
{
    public partial class Product
    {
        public Product()
        {
            this.Supplier = new HashSet<Supplier>();
        }

        public long ProductID { get; set; }
        public string ProductName { get; set; }

        //navigation property to Supplier
        public virtual ICollection<Supplier> Supplier { get; set; }
    }
}
</code>```

Supplier.cs:

```<code>using System.Collections.Generic;

namespace MtM.Models
{

    public partial class Supplier
    {
        public Supplier()
        {
            this.Product = new HashSet<Product>();
        }

        public long SupplierID { get; set; }
        public string SupplierName { get; set; }

        // navigation property to Product
        public virtual ICollection<Product> Product { get; set; }
    }
}
</code>```

ProductSupplier.cs:

```<code>namespace MtM.Models
{
    public class ProductSupplier
    {

        public long ProductID { get; set; }
        public Product Product { get; set; }

        public long SupplierID { get; set; }
        public Supplier Supplier { get; set; }
    }
}
</code>```

MtMContext.cs:

```<code>using Microsoft.EntityFrameworkCore;
using MtM.Models;

namespace MtM.Data
{
    public class MtMContext : DbContext
    {
        public MtMContext(DbContextOptions<MtMContext> options)
            : base(options)
        {
        }

        public DbSet<Product> Product { get; set; }
        public DbSet<Supplier> Supplier { get; set; }

    }
}
</code>```

HomeController.cs:

```<code>namespace MtM.Controllers
{
    public class HomeController : Controller
    {
        private readonly MtMContext conn;

        public HomeController(MtMContext context)
        {
            conn = context;
        }
        public void Many()
        {
            var A1Product=new Product (){ ProductName="A1"};
            var A2Product = new Product() { ProductName = "A2" };
            var supplier1 = new Supplier() { SupplierName="B1"};
            var supplier2 = new Supplier() { SupplierName = "B2" };
            A1Product.Supplier.Add(supplier1);
            A1Product.Supplier.Add(supplier2);
            A2Product.Supplier.Add(supplier1);
            A2Product.Supplier.Add(supplier2);
            conn.Product.Add(A1Product);
            conn.Product.Add(A2Product);
            conn.SaveChanges();

        }
</code>```

Result:

Body:
I would like to insert data into TripApplicationUser table - to save that for example that Jake has enrolled for a trip to London. The table is in my SQL Server in Visual Studio. It has 2 columns: TripId and ApplicationUserId. What should I do with my databaseContext object?

public class ApplicationUser : IdentityUser
    {
        [PersonalData]
        [Column(TypeName = "nvarchar(MAX)")]
        public string FirstName { get; set; }
        [PersonalData]
        [Column(TypeName = "nvarchar(MAX)")]
        public string Surname { get; set; }
        [PersonalData]
        [Column(TypeName = "nvarchar(MAX)")]
        public string BirthDate { get; set; }

        public ICollection<TripApplicationUser> TripApplicationUsers { get; set; }
    }

public class Trip
    {
        public int TripId { get; set; }
        public string TripDate { get; set; }
        public int TripDuration { get; set; }
        public int TripLength { get; set; }
        public int TripSeats { get; set; }

        public int TrailId { get; set; }
        public Trail Trail { get; set; }

        public ICollection<TripApplicationUser> TripApplicationUsers { get; set; }
    }

public class TripApplicationUser
    {
        public int TripId { get; set; }
        public Trip Trip { get; set; }
        public string ApplicationUserId { get; set; }
        public ApplicationUser ApplicationUser { get; set; }
    }

Body:
1.First way:

Instantiate the relational table and configure the relationship between the other two tables in the relational table.

Demo1 as below:

Product.cs:

using System.Collections.Generic;

namespace MTM2.Models
{
    public partial class Product
    {
        public long ProductID { get; set; }
        public string ProductName { get; set; }

        //navigation property to Supplier
        public virtual ICollection<ProductSupplier> Supplier { get; set; }
    }
}

Supplier.cs:

using System.Collections.Generic;

    namespace MTM2.Models
    {
        public partial class Supplier
        {

            public long SupplierID { get; set; }
            public string SupplierName { get; set; }

            // navigation property to Product
            public virtual ICollection<ProductSupplier> Product { get; set; }
        }
    }

MTM2Context.cs:

using Microsoft.EntityFrameworkCore;
using MTM2.Models;

namespace MTM2.Data
{
    public class MTM2Context: DbContext

    {
        public MTM2Context(DbContextOptions<MTM2Context> options)
               : base(options)
        {
        }

        public DbSet<Product> Product { get; set; }
        public DbSet<Supplier> Supplier { get; set; }

        public DbSet<ProductSupplier> ProductSupplier { get; set; }
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            builder.Entity<ProductSupplier>().HasKey(i => new { i.ProductID, i.SupplierID });
        }
    }
}

ProductSupplier.cs

using System.ComponentModel.DataAnnotations;

namespace MTM2.Models
{
    public class ProductSupplier
    {
        [Key]
        public long ProductID { get; set; }
        public Product Product { get; set; }
        [Key]
        public long SupplierID { get; set; }
        public Supplier Supplier { get; set; }
    }
}

HomeController .cs:

public class HomeController : Controller
    {
        private readonly MTM2Context conn;

        public HomeController(MTM2Context context)
        {
            conn = context;
        }

        public IActionResult Index()
        {
            var A1Product = new Product() { ProductName = "A1" };
            var A2Product = new Product() { ProductName = "A2" };
            var supplier1 = new Supplier() { SupplierName = "B1" };
            var supplier2 = new Supplier() { SupplierName = "B2" };
            var pslist = new List<ProductSupplier>()
            {
                new ProductSupplier() { Product = A1Product, Supplier = supplier1 },
                new ProductSupplier() { Product = A1Product, Supplier = supplier2 },

                new ProductSupplier() { Product = A2Product, Supplier = supplier1 },
                new ProductSupplier() { Product = A2Product, Supplier = supplier2 },

            };
            conn.ProductSupplier.AddRange(pslist);

            conn.SaveChanges();
            return View();
        }
    }

Result:

2.Second way:

when data do not exist in tables, add instances to context, add an instance to navigation property and call SaveChanges method from context. That is possible because Entity Framework, at the time of insert, puts primary key value (if Identity, AutoIncrement) in correspondent entity’s property inserted.

Demo 2 as below:

Product.cs:

using System.Collections.Generic;

namespace MtM.Models
{
    public partial class Product
    {
        public Product()
        {
            this.Supplier = new HashSet<Supplier>();
        }

        public long ProductID { get; set; }
        public string ProductName { get; set; }

        //navigation property to Supplier
        public virtual ICollection<Supplier> Supplier { get; set; }
    }
}

Supplier.cs:

using System.Collections.Generic;

namespace MtM.Models
{

    public partial class Supplier
    {
        public Supplier()
        {
            this.Product = new HashSet<Product>();
        }

        public long SupplierID { get; set; }
        public string SupplierName { get; set; }

        // navigation property to Product
        public virtual ICollection<Product> Product { get; set; }
    }
}

ProductSupplier.cs:

namespace MtM.Models
{
    public class ProductSupplier
    {

        public long ProductID { get; set; }
        public Product Product { get; set; }

        public long SupplierID { get; set; }
        public Supplier Supplier { get; set; }
    }
}

MtMContext.cs:

using Microsoft.EntityFrameworkCore;
using MtM.Models;

namespace MtM.Data
{
    public class MtMContext : DbContext
    {
        public MtMContext(DbContextOptions<MtMContext> options)
            : base(options)
        {
        }

        public DbSet<Product> Product { get; set; }
        public DbSet<Supplier> Supplier { get; set; }

    }
}

HomeController.cs:

namespace MtM.Controllers
{
    public class HomeController : Controller
    {
        private readonly MtMContext conn;

        public HomeController(MtMContext context)
        {
            conn = context;
        }
        public void Many()
        {
            var A1Product=new Product (){ ProductName="A1"};
            var A2Product = new Product() { ProductName = "A2" };
            var supplier1 = new Supplier() { SupplierName="B1"};
            var supplier2 = new Supplier() { SupplierName = "B2" };
            A1Product.Supplier.Add(supplier1);
            A1Product.Supplier.Add(supplier2);
            A2Product.Supplier.Add(supplier1);
            A2Product.Supplier.Add(supplier2);
            conn.Product.Add(A1Product);
            conn.Product.Add(A2Product);
            conn.SaveChanges();

        }

Result:


问:
NGINX JSON log format
We have tried to get the error logs in JSON format as we can do for access logs. But we are getting error there.
Can we not format the error logs we are getting from NGINX server to JSON format as we can do for access logs?</p>

答: At the moment is not possible to format the error logs as JSON.</p>

Title: NGINX JSON log format


问:
Mapping through Data does not Return CSS Correctly
I'm mapping through some redux data and would anticipate given the css the following elements would stack ontop of each other, with each result having their own unique container.

However it appears they're lumping into one div.

Am I incorrectly mapping this data?

https://gyazo.com/31c7b43a00da89d84fa18bf144f3dd2e?token=cf8ebf5cdba4e9a125619d8b8707fbc7

```<code>  const searchResults = useSelector(state => state.jobsearch.roles.map(role => role.title))

    const SearchResultsText = () => {
      return (
          <JobContainer title={searchResults}>
                    <Typography>
                            {searchResults}
                    </Typography>
                </JobContainer>
      )
      ;
    };

</code>```

And the jsx itself:

```<code> {searchResults && searchResults.length < 3 && (
                    <SearchResultsText/>
                )}
</code>```

And also the css for the container is:

```<code>const JobContainer = styled.div`

    background-color: red;
`;
</code>```

As well at the parent container

```<code>const SearchContent = styled.div`
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    padding: 1em;
    overflow-y: auto;
    background-color:blue;
`;
</code>```

答:
You need to map the searchResults with a JSX element.

```<code><JobContainer>
  {searchResults && searchResults.length < 3 && searchResults.map((result) =>
    (<SearchResultsText text={result} />)
  )}
</JobContainer>
</code>```

Also, create a property in SearchResultsText so you can pass each value to the component.

```<code>const SearchResultsText = ({ text }) => {
  return (
    <Typography>
      {text}
    </Typography>
  );
};
</code>```

Body:
I'm mapping through some redux data and would anticipate given the css the following elements would stack ontop of each other, with each result having their own unique container.

However it appears they're lumping into one div.

Am I incorrectly mapping this data?

https://gyazo.com/31c7b43a00da89d84fa18bf144f3dd2e?token=cf8ebf5cdba4e9a125619d8b8707fbc7

  const searchResults = useSelector(state => state.jobsearch.roles.map(role => role.title))

    const SearchResultsText = () => {
      return (
          <JobContainer title={searchResults}>
                    <Typography>
                            {searchResults}
                    </Typography>
                </JobContainer>
      )
      ;
    };

And the jsx itself:

 {searchResults && searchResults.length < 3 && (
                    <SearchResultsText/>
                )}

And also the css for the container is:

const JobContainer = styled.div`

    background-color: red;
`;

As well at the parent container

const SearchContent = styled.div`
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    padding: 1em;
    overflow-y: auto;
    background-color:blue;
`;

Body:
You need to map the searchResults with a JSX element.

<JobContainer>
  {searchResults && searchResults.length < 3 && searchResults.map((result) =>
    (<SearchResultsText text={result} />)
  )}
</JobContainer>

Also, create a property in SearchResultsText so you can pass each value to the component.

const SearchResultsText = ({ text }) => {
  return (
    <Typography>
      {text}
    </Typography>
  );
};