问:
Responsive padding flutter
Im trying to pass a percentage of screen size to padding widget but it says the value should be constant, also when you just type numbers it shows different UIs in different devices.
so what should we do for responsive padding.</p>

```<code>double h = MediaQuery.of(context).size.height;

Padding(padding: const EdgeInsets.fromLTRB(h*0.2, 5.0, 50.0, 0.0),
        child:...)
</code>```

答:
Remove the const keyword from your EdgeInsets. The const keyword means that Flutter knows the values that the specific widget will use beforehand. Obviously, if those values depend on the height of the device, Flutter is not able to know them until it executes your code.

Also, consider using LayoutBuilder instead of MediaQuery to get the available space constraints. In my experience, it is easier and more flexible to build the desired responsive layouts by obtaining a reference to the available screen space, instead of using the fixed device size.

Title: Responsive padding flutter

Body:
Im trying to pass a percentage of screen size to padding widget but it says the value should be constant, also when you just type numbers it shows different UIs in different devices.
so what should we do for responsive padding.

double h = MediaQuery.of(context).size.height;

Padding(padding: const EdgeInsets.fromLTRB(h*0.2, 5.0, 50.0, 0.0),
        child:...)


来源: stackexchange

问:
Custom Elements rendering multiple times
I am currently having an issue with custom elements, I am building some custom stuff to go on an ecommerce website and one of my custom elements is re-rendering itself multiple times.

```<code>window.initDealBadge = function(customer) {
class DealBadgeCustomElement extends HTMLElement {

    constructor(){
      super();
    }

    connectedCallback(){
      console.log("ELEMENT ADDED TO PAGE")
      const mountPoint = document.createElement('span');

      this.appendChild(mountPoint);

      const attrs = [].reduce.call(this.attributes, (memo, attr) => {
            memo[attr.name] = attr.value;
            return memo;
        }, {});
        const data = Object.assign({}, attrs);

      ReactDOM.render(<DealBadge customer={customer} id={data.id}/>, mountPoint);
    }
  }
customElements.define('deal-badge', DealBadgeCustomElement);
</code>```

}

This is my first time working with Custom elements, has anyone came across this issue before?

Thank you

答:
I managed to get it working, ConnectedCallback was being called multiple times. I added in a count to ensure it only runs once.</p>

```<code>window.initDealBadge = function(customer) {
class DealBadgeCustomElement extends HTMLElement {

    constructor(){
      super();
      this.count = 0
    }

    connectedCallback(){
      if(this.count === 0){
        this.count += 1
        console.log("ELEMENT ADDED TO PAGE")
        const mountPoint = document.createElement('span');

        this.appendChild(mountPoint);

        const attrs = [].reduce.call(this.attributes, (memo, attr) => {
              memo[attr.name] = attr.value;
              return memo;
          }, {});
          const data = Object.assign({}, attrs);

        ReactDOM.render(<DealBadge customer={customer} id={data.id}/>, mountPoint);
      }
    }
  }
customElements.define('deal-badge', DealBadgeCustomElement);};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am currently having an issue with custom elements, I am building some custom stuff to go on an ecommerce website and one of my custom elements is re-rendering itself multiple times.

window.initDealBadge = function(customer) {
class DealBadgeCustomElement extends HTMLElement {

    constructor(){
      super();
    }

    connectedCallback(){
      console.log("ELEMENT ADDED TO PAGE")
      const mountPoint = document.createElement('span');

      this.appendChild(mountPoint);

      const attrs = [].reduce.call(this.attributes, (memo, attr) => {
            memo[attr.name] = attr.value;
            return memo;
        }, {});
        const data = Object.assign({}, attrs);

      ReactDOM.render(<DealBadge customer={customer} id={data.id}/>, mountPoint);
    }
  }
customElements.define('deal-badge', DealBadgeCustomElement);

}

This is my first time working with Custom elements, has anyone came across this issue before?

Thank you

Body:
I managed to get it working, ConnectedCallback was being called multiple times. I added in a count to ensure it only runs once.

window.initDealBadge = function(customer) {
class DealBadgeCustomElement extends HTMLElement {

    constructor(){
      super();
      this.count = 0
    }

    connectedCallback(){
      if(this.count === 0){
        this.count += 1
        console.log("ELEMENT ADDED TO PAGE")
        const mountPoint = document.createElement('span');

        this.appendChild(mountPoint);

        const attrs = [].reduce.call(this.attributes, (memo, attr) => {
              memo[attr.name] = attr.value;
              return memo;
          }, {});
          const data = Object.assign({}, attrs);

        ReactDOM.render(<DealBadge customer={customer} id={data.id}/>, mountPoint);
      }
    }
  }
customElements.define('deal-badge', DealBadgeCustomElement);};


问:
How to set item position to bottomcenter launchbackground.xml
I tried to add to my app splash screen an image but I don't know how to set the gravity of it to bottom center. There is my code :

```<code><item
    android:width="265dp"
    android:height="160dp"
    android:drawable="@mipmap/bottomsplash"
    android:gravity="bottom" />
</code>```

The bottom gravity set it at the bottom left but I want it to bottom center.

答:
try this

android:gravity="bottom|center"

Body:
I tried to add to my app splash screen an image but I don't know how to set the gravity of it to bottom center. There is my code :

<item
    android:width="265dp"
    android:height="160dp"
    android:drawable="@mipmap/bottomsplash"
    android:gravity="bottom" />

The bottom gravity set it at the bottom left but I want it to bottom center.


问:
Autocall function when laravel index function of a controller is called
I have a controller class as follows:

```<code>class Controller extends BaseController{

protected function function1()
{
    //code
}

protected function function2()
{
     //code
}
}
</code>```

and every controller in the project extends this class such that i can write functions used in multiple controllers in this Controller class.

```<code>class RandomController extends Controller{

    public function aCertainFunction()
    {
        $this->function1();
        //code
    {
}
</code>```

I now have a function that should be called every time the index function of any controller is called.
One option is that i manually add this function at the start of every index function in the controllers i have and that i keep doing this for every new controller i create in the future but this doesn't seem efficient to me.

Is there a way to define this function in my Controller class such that every index function in all classes that inherit from this class will automatically call this function?

答:
You should definitely take a look at the Events Listening system embedded in the Laravel framework. Let's admit that you want to trigger aCertainFunction() every time function1 or function2 is executed.

You'll have to declare an Event class which will be stored into the namespace App\Events; (you don't need to extends Controller at all as it is dedicated to another purpose).

The public handle function of your Event class will be called to be executed when you trigger the event with the event() function. Therefore you will declare your aCertainFunction function directly inside your event class (and call it from the handle function). Please take a deep look at How Laravel is handling Events as it is really dedicated to delegate and call them on specific purposes (and that's why we call them "listeners").

Body:
I have a controller class as follows:

class Controller extends BaseController{

protected function function1()
{
    //code
}

protected function function2()
{
     //code
}
}

and every controller in the project extends this class such that i can write functions used in multiple controllers in this Controller class.

class RandomController extends Controller{

    public function aCertainFunction()
    {
        $this->function1();
        //code
    {
}

I now have a function that should be called every time the index function of any controller is called.
One option is that i manually add this function at the start of every index function in the controllers i have and that i keep doing this for every new controller i create in the future but this doesn't seem efficient to me.

Is there a way to define this function in my Controller class such that every index function in all classes that inherit from this class will automatically call this function?


问:
how is flatMap working with custom monads
I am new in scala and confused with Monads' implementation. In the below program when "a <- g(3)" is executed the value of 'a' is 23 and not Writer, why? what is happening behind the scene?</p>

```<code>case class Writer(value:Int, log:String) {
  def map(f:Int=>Int): Writer = {
    Writer(f(value), log)
  }
  def flatMap(f:Int=>Writer): Writer = {
    val temp = f(value)
    Writer(temp.value, log+"...."+temp.log)
  }
}

object Test extends App {

  def f(value: Int):Writer = {
    Writer(40+value, s"f has $value")
  }

  def g(value: Int):Writer = {
    Writer(20+value, s"g has $value")
  }

  val result1 = for {
    a <- g(3)
    b <- f(a)
  } yield b

  println(result1)

  val result2 = g(3) flatMap {
    a => f(a).map(b=>b)
  }

  println(result2)
}
</code>```

答:
From scala docs for comprehension: https://docs.scala-lang.org/tutorials/FAQ/yield.html https://docs.scala-lang.org/tour/for-comprehensions.html

it is nothing more than a syntactic sugar for composition of multiple monadic operations

Your call

```<code>for {
    a <- g(3)
    b <- f(a)
  } yield b
</code>```

gets de-sugared to:

```<code>g(3).flatMap { n =>
  f(n)
}
</code>```

The desugaring is applied on the evaluated result of g(3). You can look at this as:

```<code>writer: Writer = g(3) // evaluation of g(3)

writer.flatMap { n => // flatMap on Writer
  here n is your value which is Int
...
</code>```

So here n in the de-sugared is equivaluent to a in the syntax-sugar

Body:
I am new in scala and confused with Monads' implementation. In the below program when "a <- g(3)" is executed the value of 'a' is 23 and not Writer, why? what is happening behind the scene?

case class Writer(value:Int, log:String) {
  def map(f:Int=>Int): Writer = {
    Writer(f(value), log)
  }
  def flatMap(f:Int=>Writer): Writer = {
    val temp = f(value)
    Writer(temp.value, log+"...."+temp.log)
  }
}

object Test extends App {

  def f(value: Int):Writer = {
    Writer(40+value, s"f has $value")
  }

  def g(value: Int):Writer = {
    Writer(20+value, s"g has $value")
  }

  val result1 = for {
    a <- g(3)
    b <- f(a)
  } yield b

  println(result1)

  val result2 = g(3) flatMap {
    a => f(a).map(b=>b)
  }

  println(result2)
}

Body:
From scala docs for comprehension: https://docs.scala-lang.org/tutorials/FAQ/yield.html https://docs.scala-lang.org/tour/for-comprehensions.html

it is nothing more than a syntactic sugar for composition of multiple monadic operations

Your call

for {
    a <- g(3)
    b <- f(a)
  } yield b

gets de-sugared to:

g(3).flatMap { n =>
  f(n)
}

The desugaring is applied on the evaluated result of g(3). You can look at this as:

writer: Writer = g(3) // evaluation of g(3)

writer.flatMap { n => // flatMap on Writer
  here n is your value which is Int
...

So here n in the de-sugared is equivaluent to a in the syntax-sugar


问:
How do I get about NoResourceException
I'm trying to understand displaying a list of items in Android. From developers.android, they do explain it. However, My app crashes for some reason. I've tried putting my String array as a dummy with no fruition. This is despite the code having no errors. The stack trace says NoResourceException. The only resource is my activity file, which is in place. I'm starting to think that it may be a something beyond  the code. Maybe a dependency.

MainActivity.java

```<code>
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;
    private RecyclerView.LayoutManager layoutManager;
    String[] names;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        names = new String[] {"John","Peter","James","Andrew"};
        recyclerView = findViewById(R.id.my_recycler_view);

        recyclerView.setHasFixedSize(true);

        layoutManager= new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        adapter = new MyAdapter(names);
        recyclerView.setAdapter(adapter);
    }
}
</code>```

MyAdapter.java

```<code>
import android.view.LayoutInflater;

import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    public String[] mDataSet;

    public static class MyViewHolder extends RecyclerView.ViewHolder{

        public TextView textView;
        public MyViewHolder(TextView itemView) {
            super(itemView);
            textView =  itemView;
        }
    }

    public MyAdapter(String[] dataSet) {
        mDataSet = dataSet;

    }

    @Override
    public MyAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        TextView v = (TextView) LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_main, parent, false);
        MyViewHolder vh = new MyViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(@NonNull MyAdapter.MyViewHolder holder, int position) {
        holder.textView.setText(mDataSet[position]);
    }

    @Override
    public int getItemCount() {
        return mDataSet.length;
    }
}
</code>```

activity_main.xml

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

StackTrace

```<code>    android.content.res.Resources$NotFoundException: Resource ID #0x0
        at android.content.res.Resources.getValue(Resources.java:1552)
        at android.content.res.Resources.getDrawable(Resources.java:926)
        at android.graphics.drawable.Icon.loadDrawableInner(Icon.java:313)
        at android.graphics.drawable.Icon.loadDrawable(Icon.java:269)
        at android.widget.RemoteViews$TextViewDrawableAction.apply(RemoteViews.java:1502)
        at android.widget.RemoteViews.performApply(RemoteViews.java:2805)
        at android.widget.RemoteViews.apply(RemoteViews.java:2764)
        at android.widget.RemoteViews$ViewGroupAction.apply(RemoteViews.java:1373)
        at android.widget.RemoteViews.performApply(RemoteViews.java:2805)
        at android.widget.RemoteViews.reapply(RemoteViews.java:2795)
        at com.android.systemui.statusbar.BaseStatusBar.updateNotificationViews(BaseStatusBar.java:2162)
        at com.android.systemui.statusbar.BaseStatusBar.updateNotification(BaseStatusBar.java:2031)
        at com.android.systemui.statusbar.BaseStatusBar$6$2.run(BaseStatusBar.java:521)
        at android.os.Handler.handleCallback(Handler.java:815)
        at android.os.Handler.dispatchMessage(Handler.java:104)
        at android.os.Looper.loop(Looper.java:227)
        at android.app.ActivityThread.main(ActivityThread.java:6102)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:961)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:822)
</code>```

Updated Stacktrace

```<code>    java.lang.ClassCastException: androidx.constraintlayout.widget.ConstraintLayout cannot be cast to android.widget.TextView
        at com.projects.recyclerview.MyAdapter.onCreateViewHolder(MyAdapter.java:34)
        at com.projects.recyclerview.MyAdapter.onCreateViewHolder(MyAdapter.java:12)
        at androidx.recyclerview.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6794)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5975)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3924)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3641)
        at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4194)
        at android.view.View.layout(View.java:17051)
        at android.view.ViewGroup.layout(ViewGroup.java:5600)
        at androidx.constraintlayout.widget.ConstraintLayout.onLayout(ConstraintLayout.java:1915)
        at android.view.View.layout(View.java:17051)
        at android.view.ViewGroup.layout(ViewGroup.java:5600)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:396)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
        at android.view.View.layout(View.java:17051)
        at android.view.ViewGroup.layout(ViewGroup.java:5600)
        at androidx.appcompat.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:444)
        at android.view.View.layout(View.java:17051)
        at android.view.ViewGroup.layout(ViewGroup.java:5600)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:396)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
        at android.view.View.layout(View.java:17051)
        at android.view.ViewGroup.layout(ViewGroup.java:5600)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:2001)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1844)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1753)
        at android.view.View.layout(View.java:17051)
        at android.view.ViewGroup.layout(ViewGroup.java:5600)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:396)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
        at com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:2777)
        at android.view.View.layout(View.java:17051)
        at android.view.ViewGroup.layout(ViewGroup.java:5600)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2648)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2328)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1369)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6932)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:909)
        at android.view.Choreographer.doCallbacks(Choreographer.java:702)
        at android.view.Choreographer.doFrame(Choreographer.java:631)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:895)
        at android.os.Handler.handleCallback(Handler.java:815)
        at android.os.Handler.dispatchMessage(Handler.java:104)
        at android.os.Looper.loop(Looper.java:227)
        at android.app.ActivityThread.main(ActivityThread.java:6102)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:961)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:822)
</code>```

答:
```<code> TextView v = (TextView) LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_main, parent, false);
</code>```

The root view of activity_mail isn't a TextView, it's a ConstraintLayout.  You're inflating the wrong file most likely-  its a little odd for activity_main to be inflated inside a recyclerview

Title: How do I get about NoResourceException

Body:
I'm trying to understand displaying a list of items in Android. From developers.android, they do explain it. However, My app crashes for some reason. I've tried putting my String array as a dummy with no fruition. This is despite the code having no errors. The stack trace says NoResourceException. The only resource is my activity file, which is in place. I'm starting to think that it may be a something beyond  the code. Maybe a dependency.

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;
    private RecyclerView.LayoutManager layoutManager;
    String[] names;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        names = new String[] {"John","Peter","James","Andrew"};
        recyclerView = findViewById(R.id.my_recycler_view);

        recyclerView.setHasFixedSize(true);

        layoutManager= new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        adapter = new MyAdapter(names);
        recyclerView.setAdapter(adapter);
    }
}

MyAdapter.java

import android.view.LayoutInflater;

import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    public String[] mDataSet;

    public static class MyViewHolder extends RecyclerView.ViewHolder{

        public TextView textView;
        public MyViewHolder(TextView itemView) {
            super(itemView);
            textView =  itemView;
        }
    }

    public MyAdapter(String[] dataSet) {
        mDataSet = dataSet;

    }

    @Override
    public MyAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        TextView v = (TextView) LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_main, parent, false);
        MyViewHolder vh = new MyViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(@NonNull MyAdapter.MyViewHolder holder, int position) {
        holder.textView.setText(mDataSet[position]);
    }

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

activity_main.xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

StackTrace

    android.content.res.Resources$NotFoundException: Resource ID #0x0
        at android.content.res.Resources.getValue(Resources.java:1552)
        at android.content.res.Resources.getDrawable(Resources.java:926)
        at android.graphics.drawable.Icon.loadDrawableInner(Icon.java:313)
        at android.graphics.drawable.Icon.loadDrawable(Icon.java:269)
        at android.widget.RemoteViews$TextViewDrawableAction.apply(RemoteViews.java:1502)
        at android.widget.RemoteViews.performApply(RemoteViews.java:2805)
        at android.widget.RemoteViews.apply(RemoteViews.java:2764)
        at android.widget.RemoteViews$ViewGroupAction.apply(RemoteViews.java:1373)
        at android.widget.RemoteViews.performApply(RemoteViews.java:2805)
        at android.widget.RemoteViews.reapply(RemoteViews.java:2795)
        at com.android.systemui.statusbar.BaseStatusBar.updateNotificationViews(BaseStatusBar.java:2162)
        at com.android.systemui.statusbar.BaseStatusBar.updateNotification(BaseStatusBar.java:2031)
        at com.android.systemui.statusbar.BaseStatusBar$6$2.run(BaseStatusBar.java:521)
        at android.os.Handler.handleCallback(Handler.java:815)
        at android.os.Handler.dispatchMessage(Handler.java:104)
        at android.os.Looper.loop(Looper.java:227)
        at android.app.ActivityThread.main(ActivityThread.java:6102)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:961)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:822)

Updated Stacktrace

    java.lang.ClassCastException: androidx.constraintlayout.widget.ConstraintLayout cannot be cast to android.widget.TextView
        at com.projects.recyclerview.MyAdapter.onCreateViewHolder(MyAdapter.java:34)
        at com.projects.recyclerview.MyAdapter.onCreateViewHolder(MyAdapter.java:12)
        at androidx.recyclerview.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6794)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5975)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3924)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3641)
        at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4194)
        at android.view.View.layout(View.java:17051)
        at android.view.ViewGroup.layout(ViewGroup.java:5600)
        at androidx.constraintlayout.widget.ConstraintLayout.onLayout(ConstraintLayout.java:1915)
        at android.view.View.layout(View.java:17051)
        at android.view.ViewGroup.layout(ViewGroup.java:5600)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:396)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
        at android.view.View.layout(View.java:17051)
        at android.view.ViewGroup.layout(ViewGroup.java:5600)
        at androidx.appcompat.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:444)
        at android.view.View.layout(View.java:17051)
        at android.view.ViewGroup.layout(ViewGroup.java:5600)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:396)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
        at android.view.View.layout(View.java:17051)
        at android.view.ViewGroup.layout(ViewGroup.java:5600)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:2001)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1844)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1753)
        at android.view.View.layout(View.java:17051)
        at android.view.ViewGroup.layout(ViewGroup.java:5600)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:396)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
        at com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:2777)
        at android.view.View.layout(View.java:17051)
        at android.view.ViewGroup.layout(ViewGroup.java:5600)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2648)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2328)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1369)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6932)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:909)
        at android.view.Choreographer.doCallbacks(Choreographer.java:702)
        at android.view.Choreographer.doFrame(Choreographer.java:631)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:895)
        at android.os.Handler.handleCallback(Handler.java:815)
        at android.os.Handler.dispatchMessage(Handler.java:104)
        at android.os.Looper.loop(Looper.java:227)
        at android.app.ActivityThread.main(ActivityThread.java:6102)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:961)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:822)

Body:
 TextView v = (TextView) LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_main, parent, false);

The root view of activity_mail isn't a TextView, it's a ConstraintLayout.  You're inflating the wrong file most likely-  its a little odd for activity_main to be inflated inside a recyclerview


答:
You are probably using the wrong layout while trying to create the recycler view. activity_main is your general layout for the activity, however you're trying to use it in onCreateViewHolder as a list item.

You're probably looking for something called list_item.

LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);

Be careful on the R.layout.list_item. You currently have R.layout.activity_main there. Use your correct view to inflate the list item.

Title: How do I get about NoResourceException


问:
Query Subset of Columns with Gorm
Suppose I have the following Domain class:

```<code>class Book {
  String title
  String author
  byte[] largeCoverArtImage
}
</code>```

I have a list view where I do not need to display largeCoverArtImage, how can I perform the following SQL query using GORM Criteria?

```<code>select title, author from Book
</code>```

答:
In Grails (tested with 1.3.7 version) you can write:

```<code>def titlesAndAuthors = Book.withCriteria {
        projections {
            property 'title', 'title'
            property 'author', 'author'
        }
}
</code>```

And you'll get a list of Object[] like above example.

ContentLicense: CC BY-SA 2.5

Title: Query Subset of Columns with Gorm

Body:
Suppose I have the following Domain class:

class Book {
  String title
  String author
  byte[] largeCoverArtImage
}

I have a list view where I do not need to display largeCoverArtImage, how can I perform the following SQL query using GORM Criteria?

select title, author from Book

Body:
In Grails (tested with 1.3.7 version) you can write:

def titlesAndAuthors = Book.withCriteria {
        projections {
            property 'title', 'title'
            property 'author', 'author'
        }
}

And you'll get a list of Object[] like above example.

ContentLicense: CC BY-SA 3.0


问:
How to extract texts from text node isolating the
 tags within table?

I'm having an issue printing out in the same row, table data. Of course, I could just identify with css_selector("td"), but that prints out:
Name
Address
City/State
Phone in the same column
whereas I'm trying to create:
Name, Address, City/State, Phone to the same row

HTML: (see attached photo)

This seems like such a stupid problem to be hung up on... but I've been stuck for quite some time, and haven't been able to isolate
 tags.

Code:

```<code>for x in link:
driver.get(x)
try:
    i = 0
    while 0 < 20:
        name = driver.find_elements_by_xpath("/html/body/div[2]/div/div[1]/div/div/table/tbody/tr/td[1]/table/tbody/tr['"+str(i)+"']/td/strong")
        if name[i].is_displayed():
            print(name[i].text)

            i = i + 1
        else:
            i = i + 1
except(NoSuchElementException,JavascriptException, IndexError):
    continue
</code>```

I've identified it this way to try to simply return text of proceding siblings... again to no avail. driver.find_elements_by_css_selector("td")
Also returns the entire table data... but with it's breaks

答:
If you are able to identify the parent  element with css-selectors css_selector("td") to print Name, Address, City/State and Phone you can use the following Locator Strategies:

Name:

```<code>print(WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "td>strong"))).get_attribute("innerHTML"))
</code>```

Address:

```<code>print(driver.execute_script('return arguments[0].childNodes[3].textContent;', WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "td")))).strip())
</code>```

City/State:

```<code>print(driver.execute_script('return arguments[0].childNodes[5].textContent;', WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "td")))).strip())
</code>```

Phone:

```<code>print(driver.execute_script('return arguments[0].lastChild.textContent;', WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "td")))).strip())
</code>```

Title: How to extract texts from text node isolating the <br> tags within table?

Body:
I'm having an issue printing out in the same row, table data. Of course, I could just identify with css_selector("td"), but that prints out:
Name
Address
City/State
Phone in the same column
whereas I'm trying to create:
Name, Address, City/State, Phone to the same row

HTML: (see attached photo)

This seems like such a stupid problem to be hung up on... but I've been stuck for quite some time, and haven't been able to isolate
 tags.

Code:

for x in link:
driver.get(x)
try:
    i = 0
    while 0 < 20:
        name = driver.find_elements_by_xpath("/html/body/div[2]/div/div[1]/div/div/table/tbody/tr/td[1]/table/tbody/tr['"+str(i)+"']/td/strong")
        if name[i].is_displayed():
            print(name[i].text)

            i = i + 1
        else:
            i = i + 1
except(NoSuchElementException,JavascriptException, IndexError):
    continue

I've identified it this way to try to simply return text of proceding siblings... again to no avail. driver.find_elements_by_css_selector("td")
Also returns the entire table data... but with it's breaks

Body:
If you are able to identify the parent <td> element with css-selectors css_selector("td") to print Name, Address, City/State and Phone you can use the following Locator Strategies:

Name:

print(WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "td>strong"))).get_attribute("innerHTML"))

Address:

print(driver.execute_script('return arguments[0].childNodes[3].textContent;', WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "td")))).strip())

City/State:

print(driver.execute_script('return arguments[0].childNodes[5].textContent;', WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "td")))).strip())

Phone:

print(driver.execute_script('return arguments[0].lastChild.textContent;', WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "td")))).strip())


问:
HTTP 500 error launcing ASP.NET 3.0 application
I have just upgraded our ASP.NET Core 2.2 web application to 3.0. It builds and deploys fine. The problem is when I go to run it from our IIS server. This was running perfectly fine as a Core 2.2 web app, but now fails since upgrading to Core 3.0.

When I launch the web app from the commandline there are no reported errors.

When I launch the application from the browser the Windows logs indicate that the app started correctly.

The app then fails with an HTTP 500 error. Here are the IIS log entries.

We're using Windows Server 2012 R2 with IIS 8.5.9600.16384

The app appears to start correctly but then fails with an HTTP 500 error. Has anyone else seen this or something similar? Any ideas how to diagnose / fix the problem?

UPDATE

I've attached the VS 2019 debugger to the deployed app via the w3wp.exe process and it's not even hitting any of the middleware (I have a breakpoint at Startup() in Startup.cs).

I've tried changing the application pool settings e.g. identity, .NET version but to no avail.

When I launch the site from the web server I get the following error message which doesn't really tell me anything.

I can't see what's causing the problem.

答:
After investigation and comparison of the build artifacts that the build produces vs the deployed app, I discovered that the appsettings.json was not being deployed. No idea how or when this started failing, but it caused the app to generate an HTTP 500 error message. Our app's Azure ADB2C settings are contained in this file so it was crashing trying to authenticate but couldn't find the authentication settings.

There was no obvious error being generated and everything seemed to be loading fine. It was at the point at which the app was trying to authenticate that it was failing. All working now.


问:
GetProcAddress function in C++
Hello guys: I've loaded my DLL in my project but whenever I use the GetProcAddress function. it returns NULL! what should I do?
I use this function ( double GetNumber(double x) ) in "MYDLL.dll"

Here is a code which I used:

```<code>typedef double (*LPGETNUMBER)(double Nbr);
HINSTANCE hDLL = NULL;
LPGETNUMBER lpGetNumber;
hDLL = LoadLibrary(L"MYDLL.DLL");
lpGetNumber = (LPGETNUMBER)GetProcAddress((HMODULE)hDLL, "GetNumber");
</code>```

答:
Checking return codes and calling GetLastError() will set you free.  You should be checking return codes twice here.  You are actually checking return codes zero times.

```<code>hDLL = LoadLibrary(L"MYDLL.DLL");
</code>```

Check hDLL.  Is it NULL?  If so, call GetLastError() to find out why.  It may be as simple as "File Not Found".

```<code>lpGetNumber = (LPGETNUMBER)GetProcAddress((HMODULE)hDLL, "GetNumber");
</code>```

If lpGetNumber is NULL, call GetLastError().  It will tell you why the proc address could not be found.  There are a few likely scenarios:

There is no exported function named GetNumber

There is an exported function named GetNumber, but it is not marked extern "c", resulting in name mangling.

hDLL isn't a valid library handle.

If it turns out to be #1 above, you need to export the functions by decorating the declaration with __declspec(dllexport) like this:

MyFile.h

```<code>__declspec(dllexport) int GetNumber();
</code>```

If it turns out to be #2 above, you need to do this:

```<code>extern "C"
{
  __declspec(dllexport) int GetNumber();
};
</code>```

Title: GetProcAddress function in C++

Body:
Hello guys: I've loaded my DLL in my project but whenever I use the GetProcAddress function. it returns NULL! what should I do?
I use this function ( double GetNumber(double x) ) in "MYDLL.dll"

Here is a code which I used:

typedef double (*LPGETNUMBER)(double Nbr);
HINSTANCE hDLL = NULL;
LPGETNUMBER lpGetNumber;
hDLL = LoadLibrary(L"MYDLL.DLL");
lpGetNumber = (LPGETNUMBER)GetProcAddress((HMODULE)hDLL, "GetNumber");

Body:
Checking return codes and calling GetLastError() will set you free.  You should be checking return codes twice here.  You are actually checking return codes zero times.

hDLL = LoadLibrary(L"MYDLL.DLL");

Check hDLL.  Is it NULL?  If so, call GetLastError() to find out why.  It may be as simple as "File Not Found".

lpGetNumber = (LPGETNUMBER)GetProcAddress((HMODULE)hDLL, "GetNumber");

If lpGetNumber is NULL, call GetLastError().  It will tell you why the proc address could not be found.  There are a few likely scenarios:

There is no exported function named GetNumber

There is an exported function named GetNumber, but it is not marked extern "c", resulting in name mangling.

hDLL isn't a valid library handle.

If it turns out to be #1 above, you need to export the functions by decorating the declaration with __declspec(dllexport) like this:

MyFile.h

__declspec(dllexport) int GetNumber();

If it turns out to be #2 above, you need to do this:

extern "C"
{
  __declspec(dllexport) int GetNumber();
};


问:
How to write python code for salary rule in odoo
I am trying to write the python code in the Computation part of the salary rules in the payroll module.

result = payslip.salaryrule()

In the payslip module, I'm creating the salaryrule function like this -

```<code>class CustomPayslip(models.Model):
    @api.multi
    def salaryrule(self):
        hourly_rate = self.emp_amount
        return round(self.billable_hours * hourly_rate, 2)
</code>```

But when I create a employee payslip and click on Compute Sheet button, I get this error from flectra - Wrong python code defined for salary rule.

答:
try to add the code directly into the rule

```<code>hourly_rate = self.emp_amount
result = round(self.billable_hours * hourly_rate, 2)
</code>```

and try payslip instead of self

Body:
I am trying to write the python code in the Computation part of the salary rules in the payroll module.

result = payslip.salaryrule()

In the payslip module, I'm creating the salaryrule function like this -

class CustomPayslip(models.Model):
    @api.multi
    def salaryrule(self):
        hourly_rate = self.emp_amount
        return round(self.billable_hours * hourly_rate, 2)

But when I create a employee payslip and click on Compute Sheet button, I get this error from flectra - Wrong python code defined for salary rule.

Body:
try to add the code directly into the rule

hourly_rate = self.emp_amount
result = round(self.billable_hours * hourly_rate, 2)

and try payslip instead of self


问:
Why I can sometimes use functions from nested modules without importing the whole path?
I was wondering what's the difference between these two cases? Is the inner structure of the modules somehow different?

So why this one works:

```<code>>>> import numpy
>>> numpy.random.RandomState
<class 'numpy.random.mtrand.RandomState'>
</code>```

But this one doesn't work until I import the nested module also:

```<code>>>> import tkinter
>>> tkinter.ttk.Spinbox
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'tkinter' has no attribute 'ttk'
>>> import tkinter.ttk
>>> tkinter.ttk.Spinbox
<class 'tkinter.ttk.Spinbox'>
</code>```

I think that this must be something to do with the __init__.py files in each module, but a concrete example of an implementation would be helpful.

答:
This kind of import behavior can be achieved by importing the deep class in the respective __init__.py files. Here's a quick demonstration of a project structure that works pretty much exactly like the real numpy and tkinter packages did:

```<code>.
├── main.py
├── numpy
│   ├── __init__.py
│   └── random
│       ├── __init__.py
│       └── mtrand.py
└── tkinter
    ├── __init__.py
    └── ttk.py
</code>```

numpy/__init__.py:

```<code>from .random import RandomState
</code>```

numpy/random/__init__.py:

```<code>from .mtrand import RandomState
</code>```

numpy/random/mtrand.py:

```<code>class RandomState:
    pass
</code>```

tkinter/__init__.py:

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

tkinter/ttk.py:

```<code>class Spinbox:
    pass
</code>```

main.py:

```<code>import numpy
import tkinter

print(numpy.random.RandomState)

try:
    print(tkinter.ttk.Spinbox)
except AttributeError as e:
    print("Error:", e)
    import tkinter.ttk
    print(tkinter.ttk.Spinbox)
</code>```

Output:

<class 'numpy.random.mtrand.RandomState'>
Error: module 'tkinter' has no attribute 'ttk'
<class 'tkinter.ttk.Spinbox'>
```

Body:
I was wondering what's the difference between these two cases? Is the inner structure of the modules somehow different?

So why this one works:

>>> import numpy
>>> numpy.random.RandomState
<class 'numpy.random.mtrand.RandomState'>

But this one doesn't work until I import the nested module also:

>>> import tkinter
>>> tkinter.ttk.Spinbox
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'tkinter' has no attribute 'ttk'
>>> import tkinter.ttk
>>> tkinter.ttk.Spinbox
<class 'tkinter.ttk.Spinbox'>

I think that this must be something to do with the __init__.py files in each module, but a concrete example of an implementation would be helpful.

Body:
This kind of import behavior can be achieved by importing the deep class in the respective __init__.py files. Here's a quick demonstration of a project structure that works pretty much exactly like the real numpy and tkinter packages did:

.
├── main.py
├── numpy
│   ├── __init__.py
│   └── random
│       ├── __init__.py
│       └── mtrand.py
└── tkinter
    ├── __init__.py
    └── ttk.py

numpy/__init__.py:

from .random import RandomState

numpy/random/__init__.py:

from .mtrand import RandomState

numpy/random/mtrand.py:

class RandomState:
    pass

tkinter/__init__.py:

tkinter/ttk.py:

class Spinbox:
    pass

main.py:

import numpy
import tkinter

print(numpy.random.RandomState)

try:
    print(tkinter.ttk.Spinbox)
except AttributeError as e:
    print("Error:", e)
    import tkinter.ttk
    print(tkinter.ttk.Spinbox)

Output:

<class 'numpy.random.mtrand.RandomState'>
Error: module 'tkinter' has no attribute 'ttk'
<class 'tkinter.ttk.Spinbox'>


问:
How to cache Pytorch models for use when not connected to the internet?
I'm using vgg19 in a classification problem. I have access to the campus research computer to train on, but the nodes where the computation is done don't have access to the internet. So running a line of code like self.net = models.vgg19(pretrained=True) fails with the error urllib.error.URLError: <urlopen error [Errno 101] Network is unreachable>

Is there a way I could cache the model on the head node (where I have internet access), and load the model from the cache instead of the internet on the compute node?

答:
If you just save the weights of pretrained networks somewhere, you can load them just like you can load any other network weights.

Saving:

import torchvision

#  I am assuming we have internet access here
model = torchvision.models.vgg16(pretrained=True)
torch.save(model.state_dict(), "Somewhere")
```

<p>Loading:</p>

<pre class="lang-py prettyprint-override"><code>import torchvision

def create_vgg16(dict_path=None):
    model = torchvision.models.vgg16(pretrained=False)
    if (dict_path != None):
        model.load_state_dict(torch.load(dict_path))
    return model

model = create_vgg16("Somewhere")
</code>```

Body:
If you just save the weights of pretrained networks somewhere, you can load them just like you can load any other network weights.

Saving:

import torchvision

#  I am assuming we have internet access here
model = torchvision.models.vgg16(pretrained=True)
torch.save(model.state_dict(), "Somewhere")

Loading:

import torchvision

def create_vgg16(dict_path=None):
    model = torchvision.models.vgg16(pretrained=False)
    if (dict_path != None):
        model.load_state_dict(torch.load(dict_path))
    return model

model = create_vgg16("Somewhere")


问:
Overlapping of dynamic and static routes in next JS
I created a nextJS application and using its routing system there. Now I have created a dynamic route to catch a URL like {base_url}/{username}/{post-slug}. But it is also capturing {base_url}/post/create which I want to be rendered on different page.
So is there anything available in nextJS route to match a URL absolutely? Like, exact in react router? Or do I have to redirect user from getInitialProps function in nextJS?

答:
I created sample codesandbox for this question.

It works without Regular Expression. Always the specific route (post/create) has the priority.

I hope this helps you.


问:
Javascript Drag and Drop: removing dragged element following successful drop
I'm using the native drag and drop API in javascript.  How can I remove a dragged element from the DOM following a successful drop?

I've tried listening to the drop event, but this only gets fired on the element which is dropped onto and has no reference to the element being dragged.

I've tried listening to the dragend element, but this doesn't let me know whether a drop was successful or not.

I'm trying to avoid storing the element being dragged in a global variable as this will cause problems if a drag occurs between different tabs or browsers.

Here's an example: http://jsfiddle.net/KNG6n/3/

A list of letters which can be dragged into the box.  When a letter's node is dropped on the box, I'd like it to be removed from the list (without effecting any other list items containing the same letter)

答:
You get the drop position of element in the dragend event. You can find if an droppable element is present at that position.

You can use document.elementFromPoint(x, y);


问:
How to sort a Vector of Vectors?
In Java I am wondering how to sort vectors of vectors on a particular column where one vector is used as a row and one vector is used to hold all the row vectors e.g.

```<code> Vector row = new Vector();
    Vector main = new Vector();

    row.add("Column1");
    row.add("Column2");
    row.add("Column3");

    main.add(row);
</code>```

Then sort the variables in one of the columns e.g. Column2.

Thank you

答:
(why do people still use Vector and avoid generics? I should ask that question on SO... ;) )

Let me suggest a modern refactoring first:

```<code>List<List<String>> main = new ArrayList<List<String>>();
List<String> row = new ArrayList<String>();
row.add("Column1");
row.add("Column2");
row.add("Column3");
main.add(row);
</code>```

Now we can look at Collections.sort(Comparator<T> comp) which will do the sorting of main. We just have to implement a Comparator class that is able to compare two rows according to our parameter - which is a certain column, in our case:

```<code>public class MyComparator implements Comparator<List<String>> {
  private int columnIndex = 0;
  public MyComparator(int columnIndex) {this.columnIndex = columnIndex;}

  @Override
  public int compare(List<String> thisRow, List<String> otherRow) {
    return thisRow.get(columnIndex).compareTo(otherRow.get(columnIndex));
  }
}
</code>```

Use the comparator like this:

```<code>Collections.sort(main, new MyComparator(1));  // will sort according to "column2"
</code>```

Note - this is an incomplete implementation, I don't check if the index values are valid and if all rows have the same size .. should be done in production code.

Title: How to sort a Vector of Vectors?

Body:
In Java I am wondering how to sort vectors of vectors on a particular column where one vector is used as a row and one vector is used to hold all the row vectors e.g.

 Vector row = new Vector();
    Vector main = new Vector();

    row.add("Column1");
    row.add("Column2");
    row.add("Column3");

    main.add(row);

Then sort the variables in one of the columns e.g. Column2.

Thank you

Body:
(why do people still use Vector and avoid generics? I should ask that question on SO... ;) )

Let me suggest a modern refactoring first:

List<List<String>> main = new ArrayList<List<String>>();
List<String> row = new ArrayList<String>();
row.add("Column1");
row.add("Column2");
row.add("Column3");
main.add(row);

Now we can look at Collections.sort(Comparator<T> comp) which will do the sorting of main. We just have to implement a Comparator class that is able to compare two rows according to our parameter - which is a certain column, in our case:

public class MyComparator implements Comparator<List<String>> {
  private int columnIndex = 0;
  public MyComparator(int columnIndex) {this.columnIndex = columnIndex;}

  @Override
  public int compare(List<String> thisRow, List<String> otherRow) {
    return thisRow.get(columnIndex).compareTo(otherRow.get(columnIndex));
  }
}

Use the comparator like this:

Collections.sort(main, new MyComparator(1));  // will sort according to "column2"

Note - this is an incomplete implementation, I don't check if the index values are valid and if all rows have the same size .. should be done in production code.


问:
Filter generic list from partial object in typescript
How can I filter my generic list based on a partial object received?

Here is what I have so far:

```<code>export class GenericRestApiMock<T> {

    protected store: T[];

    public getByFilter(fitler?: { [P in keyof T]?: T[P] } & { pageNumber?: 1; limit?: 10 }): Observable<T[]> {

        // filter store object

        return of<T[]>(...);
   }

}
</code>```

答:
Assuming you want the objects to match all values in the filter, the solution could be easy enough. You can use Object.keys to get the keys of the filter (although, you will have to type assert the result of this is Array<keyof T>, see why here ). You can then use filter to go over all items in the array, and find the ones where all the keys match:

```<code>export class GenericRestApiMock<T> {

    protected store: T[];

    public getByFilter(fitler?: { [P in keyof T]?: T[P] } &  { pageNumber?: 1; limit?: 10 }): Observable<T[]> {
        if (!fitler) return of(this.store);

        // filter store object
        let filterKeys = Object.keys(fitler)
            .filter(k => k !== 'pageNumber' && k !== 'limit') as Array<keyof T>
        let filterValues = this.store.filter(o => filterKeys.every(k => fitler[k] === o[k]))
        let { pageNumber = 0, limit = 10 } = fitler;
        return of<T[]>(filterValues.slice(pageNumber * limit,pageNumber * limit+ limit ));
   }

}
</code>```

Playground Link

Body:
How can I filter my generic list based on a partial object received?

Here is what I have so far:

export class GenericRestApiMock<T> {

    protected store: T[];

    public getByFilter(fitler?: { [P in keyof T]?: T[P] } & { pageNumber?: 1; limit?: 10 }): Observable<T[]> {

        // filter store object

        return of<T[]>(...);
   }

}

Body:
Assuming you want the objects to match all values in the filter, the solution could be easy enough. You can use Object.keys to get the keys of the filter (although, you will have to type assert the result of this is Array<keyof T>, see why here ). You can then use filter to go over all items in the array, and find the ones where all the keys match:

export class GenericRestApiMock<T> {

    protected store: T[];

    public getByFilter(fitler?: { [P in keyof T]?: T[P] } &  { pageNumber?: 1; limit?: 10 }): Observable<T[]> {
        if (!fitler) return of(this.store);

        // filter store object
        let filterKeys = Object.keys(fitler)
            .filter(k => k !== 'pageNumber' && k !== 'limit') as Array<keyof T>
        let filterValues = this.store.filter(o => filterKeys.every(k => fitler[k] === o[k]))
        let { pageNumber = 0, limit = 10 } = fitler;
        return of<T[]>(filterValues.slice(pageNumber * limit,pageNumber * limit+ limit ));
   }

}

<a href="https://www.typescriptlang.org/play/?ssl=18&ssc=2&pln=3&pc=1#code/JYWwDg9gTgLgBAbzgeQEYGcCmUBuBDVAG0wBo4IAzOAXzgqghDgHIoAPAK3WYFgAofpjaRYcAMaE86dHADimAHbZgYgEqZ0MAIJhgAWQhiA1gB4AKgD5E-fnDtwwDGJjHOAJnE3RMALjhmAbQBdAG4bPnsHAFciFTgAc0wYACEATwAxYEJnKAAKCmAYYigAfj8kAIAFOGAFOCNMVMp-ILL-KqCaOAAyOyQwPESAOSiQVGw2gEYQuEJQQqmABhoASj80LFwCYnNgqwRbSPtgKlyAQgKi7BW4KCSoqDrKXJgAC2B0ADovO5WwgQiRzsAHpgXQsjlPDBvORUBwXDBDkDiPACtlsABpRoyAC8KDhCM+DVS6HyhWKKyRQPsnzROVyRjgOKsjLOOLxzAGw1G4ygzB6vVZ7JYcxAhWYNykcC0UCgeFSJmJzUsVMiKPB6KgADU8IQohomXA3h9vtC7rSIdhchAmVY6ZjsZ9MDhsKkGbbwVcoAEjJ12XiID6gitKYDkUlEA5BpgRmNsIbFmRRYVDZNlrQ8Zdiv9qbd7o9yBRdkELGTNTq9RpvnMxJhclyYzz4wAqWbzGAkBux3lwVvJmAAajbYvgIZzdmo4WoQA" rel="nofollow noreferrer">Playground Link


问:
Applying same styles to parent and nested children
I have following css rule

```<code>* {
    box-sizing: border-box;
    -webkit-tap-highlight-color: transparent;
    -webkit-touch-callout: none;
}
</code>```

I also want to apply same style rules to *::after and *::before, and I can do so via *, *::after, *::before {}. However I want to keep it consistent with other scss I have that is nested, hence I'm trying to figure out how to nest these pseudo elements, yet apply same style to all 3 of these selectors.

答:
You can use the parent selector this way:

```<code>* {
  &, &::after, &::before {
    box-sizing: border-box;
    -webkit-tap-highlight-color: transparent;
    -webkit-touch-callout: none;
  }
}
</code>```

It will compile as:

```<code>*, *::after, *::before {
  box-sizing: border-box;
  -webkit-tap-highlight-color: transparent;
  -webkit-touch-callout: none;
}
</code>```

Body:
I have following css rule

* {
    box-sizing: border-box;
    -webkit-tap-highlight-color: transparent;
    -webkit-touch-callout: none;
}

I also want to apply same style rules to *::after and *::before, and I can do so via *, *::after, *::before {}. However I want to keep it consistent with other scss I have that is nested, hence I'm trying to figure out how to nest these pseudo elements, yet apply same style to all 3 of these selectors.

Body:
You can use the parent selector this way:

* {
  &, &::after, &::before {
    box-sizing: border-box;
    -webkit-tap-highlight-color: transparent;
    -webkit-touch-callout: none;
  }
}

It will compile as:

*, *::after, *::before {
  box-sizing: border-box;
  -webkit-tap-highlight-color: transparent;
  -webkit-touch-callout: none;
}


问:
Python beeceptor webhooks
I am trying to get my head around web hooks. I receive a web hook from Shopify. I use  https://beeceptor.com/ to receive the web hook which looks like the screenshot attached. It is a JSON. I want to use python to process the received POST and take some action. Can I know how I can retrieve this using python? Do I need to use the Flask framework or can I do with request? Here are details from Shopify https://shopify.dev/tutorials/manage-webhooks#verify-webhook
which I am unsure of.   </p>

答: You need to create a web app that can accept incoming HTTP traffic from Shopify - you can do this in Flask/Python or really any other web technology stack. Services like AWS Lambda can also work to receive the webhook and do some processing.</p>

Title: Python beeceptor webhooks


问:
I am using flutter bottomNavigatonBar widget, Is there anything which it can be raised?
This is what I want !

```<code>        floatingActionButton: FloatingActionButton(
          onPressed: () {},
          child: Icon(Icons.add),
        ),
        bottomNavigationBar: BottomAppBar(
          shape: CircularNotchedRectangle(),
          notchMargin: 4.0,
          child: Row(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              IconButton(
                icon: Icon(Icons.home),
                onPressed: () {},
              ),
              IconButton(
                icon: Icon(Icons.search),
                onPressed: () {},
              ),
              IconButton(
                icon: Icon(Icons.notifications),
                onPressed: () {},
              ),
              IconButton(
                icon: Icon(Icons.perm_identity),
                onPressed: () {},
              ),
            ],
          ),
        ),
</code>```

I want the Nav bar to be slightly raised from the bottom and have rounded border. Currently it's sitting in the bottom of the screen.

答: you can use Fancy Navigation bar if you want that output you can just remove the text by putting an empty text to its title.</p>

Body:
This is what I want !

        floatingActionButton: FloatingActionButton(
          onPressed: () {},
          child: Icon(Icons.add),
        ),
        bottomNavigationBar: BottomAppBar(
          shape: CircularNotchedRectangle(),
          notchMargin: 4.0,
          child: Row(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              IconButton(
                icon: Icon(Icons.home),
                onPressed: () {},
              ),
              IconButton(
                icon: Icon(Icons.search),
                onPressed: () {},
              ),
              IconButton(
                icon: Icon(Icons.notifications),
                onPressed: () {},
              ),
              IconButton(
                icon: Icon(Icons.perm_identity),
                onPressed: () {},
              ),
            ],
          ),
        ),

I want the Nav bar to be slightly raised from the bottom and have rounded border. Currently it's sitting in the bottom of the screen.


问:
Reading selected files using starting name of file in Python
I have more than 1000 files in the same folder. I want to read selected files from it.

Here randon_text is different in each file.
I have successfully fetched all file names in one list name file_name_list.

I want something like below

file_name == part_0000 then Work1

file_name != _confirm or _start then work2

I have done some part of the required work using the below code.
for i in file_name_list:
if i.name == "part_0000"

Here I don't know how to read file with matching text or the same format in python.
I need something the same as like function in SQL so I can read files with initial text only.

答:
```<code>for i in file_name_list:
    if "part_0000" in i.name:
           if "part_00001" in i.name or "part_00002" in i.name:
               continue
           #enter your condition here....
</code>```


问:
perl decode string in cyrillic
I've got a problem with the following string:

```<code>$str="this is \321\213\321\213\321\213\321\213\321\213 \321\201\320\277\320\260\321\200\321\202\320\260\321\200";
</code>```

This string is located in an ascii text file and I want to store in a Mysql db (utf8). \321\231 ... are cyrillic symbols.

What can I do to make \321\213 look like cyrillic characters in Mysql db

This should be described in RFC2047, end look like it was utf7 to utf8 conversion.. dont know excatly.
its "unicode escape"

working variant:

```<code>use Encode::Escape;
$var1='\321\213';
         print decode 'unicode-escape', $var1;
#correct mysql view in phpmyadmin
$dbh = DBI->connect('DBI:mysql:database=test', 'testuser', 'testpass', { mysql_enable_utf8 => 1});
</code>```

答:
You need to convert explicitly the codes to characters. For that you need to know what's the input encoding. I suppose it's iso-8859-5, but it could be windows-1252 or something else.

```<code>use Encode qw( decode );

my $str="this is \321\213\321\213\321\213\321\213\321 \321\201\320\277\320\260\321\200\321\202\320\260\321";
my $out .= from_to( "iso-8859-5","utf-8", $str );
</code>```

I've just seen that your source string is indeed QP, so you need to convert from QP to bytes; that's easy, simply use MIME::QuotedPrint:

```<code>use MIME::QuotedPrint ();

my $out = MIME::QuotedPrint::decode($str);
</code>```

Title: perl decode string in cyrillic

Body:
I've got a problem with the following string:

$str="this is \321\213\321\213\321\213\321\213\321\213 \321\201\320\277\320\260\321\200\321\202\320\260\321\200";

This string is located in an ascii text file and I want to store in a Mysql db (utf8). \321\231 ... are cyrillic symbols.

What can I do to make \321\213 look like cyrillic characters in Mysql db

This should be described in RFC2047, end look like it was utf7 to utf8 conversion.. dont know excatly.
its "unicode escape"

working variant:

use Encode::Escape;
$var1='\321\213';
         print decode 'unicode-escape', $var1;
#correct mysql view in phpmyadmin
$dbh = DBI->connect('DBI:mysql:database=test', 'testuser', 'testpass', { mysql_enable_utf8 => 1});

Body:
You need to convert explicitly the codes to characters. For that you need to know what's the input encoding. I suppose it's iso-8859-5, but it could be windows-1252 or something else.

use Encode qw( decode );

my $str="this is \321\213\321\213\321\213\321\213\321 \321\201\320\277\320\260\321\200\321\202\320\260\321";
my $out .= from_to( "iso-8859-5","utf-8", $str );

I've just seen that your source string is indeed QP, so you need to convert from QP to bytes; that's easy, simply use MIME::QuotedPrint:

use MIME::QuotedPrint ();

my $out = MIME::QuotedPrint::decode($str);


问:
Finding p% of smallest tensor values - TensorFlow 2.0
I am using Python 3.7 and TensorFlow 2.0 and I have the following problem. Within a given tensor of any dimension, if I want to find p% of the smallest weights (where, p can be a user input), how do I do so?

Example:

```<code>x = tf.random.normal(shape=(3, 2, 2))

x.numpy()
Out[8]:
array([[[-0.30938825,  0.40093166],
        [ 1.5417175 , -0.9551434 ]],

       [[-0.7977963 , -2.0784302 ],
        [-1.5039488 , -0.75159657]],

       [[ 1.7954558 ,  0.19909047],
        [-0.2359499 , -2.4791834 ]]], dtype=float32)
</code>```

Within the tensor 'x' (of shape: (3, 2, 2)), how can I find say p = 30% of smallest weights? I then plan on removing the p% of smallest weights by setting them to zero.

Thanks!

Body:
I am using Python 3.7 and TensorFlow 2.0 and I have the following problem. Within a given tensor of any dimension, if I want to find p% of the smallest weights (where, p can be a user input), how do I do so?

Example:

x = tf.random.normal(shape=(3, 2, 2))

x.numpy()
Out[8]:
array([[[-0.30938825,  0.40093166],
        [ 1.5417175 , -0.9551434 ]],

       [[-0.7977963 , -2.0784302 ],
        [-1.5039488 , -0.75159657]],

       [[ 1.7954558 ,  0.19909047],
        [-0.2359499 , -2.4791834 ]]], dtype=float32)

Within the tensor 'x' (of shape: (3, 2, 2)), how can I find say p = 30% of smallest weights? I then plan on removing the p% of smallest weights by setting them to zero.

Thanks!

Body:
Using TensorFlow Probability's stats.percentile:

In [5]: import tensorflow_probability as tfp

In [6]: p30 = tfp.stats.percentile(x, q=30.)

In [7]: p30
Out[7]: <tf.Tensor: id=1159, shape=(), dtype=float32, numpy=-0.9551434>

In [8]: tf.where(x <= p30, 0, x)
Out[8]:
<tf.Tensor: id=1108, shape=(3, 2, 2), dtype=float32, numpy=
array([[[-0.30938825,  0.40093166],
        [ 1.5417175 ,  0.        ]],

       [[-0.7977963 ,  0.        ],
        [ 0.        , -0.75159657]],

       [[ 1.7954558 ,  0.19909047],
        [-0.2359499 ,  0.        ]]], dtype=float32)>

Minimal requirements:

tensorflow==2.0
tensorflow-probability==0.7


问:
i have 3 text boxes for Day , Month and Year .From this need to calculate a date
I have 3 textboxes for Day, Month and Year. From this need to calculate a date. And need subtraction functionality also ( Calculation on Current date)

Eg: Current date = 20-02-2020 , Day -1 and Month - 1 and Year = 1 then the result = 21-03-2021

答:
Thank you all for your time ..
I have solved my question and sharing for your reference</p>

```<code>        int value_days = 0;
        int.TryParse(txtRecommendationfor_OPReview_Days.Text, out value_days);
        int value_months = 0;
        int.TryParse(txtRecommendationfor_OPReview_Months.Text, out value_months);
        int value_years = 0;
        int.TryParse(txtRecommendationfor_OPReview_Years.Text, out value_years);
        if ((value_days <= 0 || Convert.ToString(value_days) == "") && (value_months <= 0 || Convert.ToString(value_months) == "") && (value_years <= 0 || Convert.ToString(value_years) == ""))
        {
            dtpRecommendationfor_OP.Value = DateTime.Now;
            return;
        }
        else
        {
            int OPReview_Days = Convert.ToInt32(txtRecommendationfor_OPReview_Days.Text.Trim() == "" ? 0.ToString() : txtRecommendationfor_OPReview_Days.Text.Trim());
            int OPReview_Months = Convert.ToInt32(txtRecommendationfor_OPReview_Months.Text.Trim() == "" ? 0.ToString() : txtRecommendationfor_OPReview_Months.Text.Trim());
            int OPReview_years = Convert.ToInt32(txtRecommendationfor_OPReview_Years.Text.Trim() == "" ? 0.ToString() : txtRecommendationfor_OPReview_Years.Text.Trim());

            var _date = DateTime.Now.AddDays(OPReview_Days).AddMonths(OPReview_Months).AddYears(OPReview_years);
            dtpRecommendationfor_OP.Value = _date;
        }
</code>```

Body:
Thank you all for your time ..
I have solved my question and sharing for your reference

        int value_days = 0;
        int.TryParse(txtRecommendationfor_OPReview_Days.Text, out value_days);
        int value_months = 0;
        int.TryParse(txtRecommendationfor_OPReview_Months.Text, out value_months);
        int value_years = 0;
        int.TryParse(txtRecommendationfor_OPReview_Years.Text, out value_years);
        if ((value_days <= 0 || Convert.ToString(value_days) == "") && (value_months <= 0 || Convert.ToString(value_months) == "") && (value_years <= 0 || Convert.ToString(value_years) == ""))
        {
            dtpRecommendationfor_OP.Value = DateTime.Now;
            return;
        }
        else
        {
            int OPReview_Days = Convert.ToInt32(txtRecommendationfor_OPReview_Days.Text.Trim() == "" ? 0.ToString() : txtRecommendationfor_OPReview_Days.Text.Trim());
            int OPReview_Months = Convert.ToInt32(txtRecommendationfor_OPReview_Months.Text.Trim() == "" ? 0.ToString() : txtRecommendationfor_OPReview_Months.Text.Trim());
            int OPReview_years = Convert.ToInt32(txtRecommendationfor_OPReview_Years.Text.Trim() == "" ? 0.ToString() : txtRecommendationfor_OPReview_Years.Text.Trim());

            var _date = DateTime.Now.AddDays(OPReview_Days).AddMonths(OPReview_Months).AddYears(OPReview_years);
            dtpRecommendationfor_OP.Value = _date;
        }


问:
WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'
Suddenly when Syncing Gradle, I get this error:

WARNING: API 'variant.getJavaCompile()' is obsolete and has been
  replaced with 'variant.getJavaCompileProvider()'.
      It will be removed at the end of 2019.
      For more information, see https://d.android.com/r/tools/task-configuration-avoidance
      Affected Modules: app

I've got this build.gradle for the app module:

```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'
apply plugin: 'com.google.gms.google-services'

apply plugin: 'io.fabric'

android {
    compileSdkVersion 28
    buildToolsVersion "28.0.2"
    defaultConfig {
        applicationId "..."
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "..."
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        versionNameSuffix = version_suffix

        [...]
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'

            [...]
        }
        debug {
            [...]
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.2.61"
    implementation 'androidx.appcompat:appcompat:1.0.0-rc02'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation "com.android.support:preference-v7:28.0.0"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
    implementation 'com.google.android.material:material:1.0.0-rc02'

    [...]
}
</code>```

I can compile the app correctly, but it's a bit bothering, and as I see it, something will stop working at the end of 2019. Any ideas of what is it and how to solve it?

答:
I had same problem and it solved by defining kotlin gradle plugin version in build.gradle file.

change this

```<code> classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
</code>```

to

```<code> classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50{or latest version}"
</code>```

Body:
Suddenly when Syncing Gradle, I get this error:

WARNING: API 'variant.getJavaCompile()' is obsolete and has been
  replaced with 'variant.getJavaCompileProvider()'.
      It will be removed at the end of 2019.
      For more information, see https://d.android.com/r/tools/task-configuration-avoidance
      Affected Modules: app

I've got this build.gradle for the app module:

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'
apply plugin: 'com.google.gms.google-services'

apply plugin: 'io.fabric'

android {
    compileSdkVersion 28
    buildToolsVersion "28.0.2"
    defaultConfig {
        applicationId "..."
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "..."
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        versionNameSuffix = version_suffix

        [...]
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'

            [...]
        }
        debug {
            [...]
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.2.61"
    implementation 'androidx.appcompat:appcompat:1.0.0-rc02'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation "com.android.support:preference-v7:28.0.0"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
    implementation 'com.google.android.material:material:1.0.0-rc02'

    [...]
}

I can compile the app correctly, but it's a bit bothering, and as I see it, something will stop working at the end of 2019. Any ideas of what is it and how to solve it?

Body:
I had same problem and it solved by defining kotlin gradle plugin version in build.gradle file.

change this

 classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

to

 classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50{or latest version}"


问:
How to replace NAs with values from another column in data.table (Example given)?
DT is data.table and I want to replace NAs with values from visits column and Expected_DT is desired DT.

```<code>DT<-data.table(name=c("x","x","x","x"),hour=1:4,count=c(NA,45,56,78),visits=c(14,45,56,78))

name hour count visits
1:    x    1    NA     14
2:    x    2    45     45
3:    x    3    56     56
4:    x    4    78     78
</code>```

This is what I want

```<code>Expected_DT<-data.table(name=c("x","x","x","x"),hour=1:4,count=c(14,45,56,78),visits=c(14,45,56,78))

   name hour count visits
1:    x    1    14     14
2:    x    2    45     45
3:    x    3    56     56
4:    x    4    78     78
</code>```

答:
And here is a dplyr version to be complete for other users:</p>

```<code>library(dplyr)

DT %>%
    mutate(count = if_else(is.na(count), visits, count))

  name hour count visits
1    x    1    14     14
2    x    2    45     45
3    x    3    56     56
4    x    4    78     78
</code>```

Body:
DT is data.table and I want to replace NAs with values from visits column and Expected_DT is desired DT.

DT<-data.table(name=c("x","x","x","x"),hour=1:4,count=c(NA,45,56,78),visits=c(14,45,56,78))

name hour count visits
1:    x    1    NA     14
2:    x    2    45     45
3:    x    3    56     56
4:    x    4    78     78

This is what I want

Expected_DT<-data.table(name=c("x","x","x","x"),hour=1:4,count=c(14,45,56,78),visits=c(14,45,56,78))

   name hour count visits
1:    x    1    14     14
2:    x    2    45     45
3:    x    3    56     56
4:    x    4    78     78

Body:
And here is a dplyr version to be complete for other users:

library(dplyr)

DT %>%
    mutate(count = if_else(is.na(count), visits, count))

  name hour count visits
1    x    1    14     14
2    x    2    45     45
3    x    3    56     56
4    x    4    78     78


问:
How to check if an array contains any undefined value in javascript
I want to know whether my array contains any undefined value. My array is like this,

How to find it?
I tried this method but it doesn't read 'undefined'

```<code> let newValues = []
 if(values.length === selectedCertifiedList.length){
   values && values.filter(v => v === (undefined ||  0 || null)).map(val => {
        newValues.push(val);
   })
 }
</code>```

答:
arr.some(item => item === undefined)

returns true if any item in the array is undefined

Body:
I want to know whether my array contains any undefined value. My array is like this,

How to find it?
I tried this method but it doesn't read 'undefined'

 let newValues = []
 if(values.length === selectedCertifiedList.length){
   values && values.filter(v => v === (undefined ||  0 || null)).map(val => {
        newValues.push(val);
   })
 }


问:
the MySQL service on local computer started and then stopped
the MySQL service on local computer started and then stopped. Some services stop automatically if they are not in use by other services or programs.

Can anyone resolve this issue? Thanks.

答:
Delete or rename the 2 following files from "C:\ProgramData\MySQL\MySQL Server 5.7\Data":
ib_logfile0
ib_logfile1</p>


问:
SwiftUI Path as contentShape, doesn't line up with Image
TL;DR: I'm using a Path to specify the hit area for an Image. But I don't know how to adjust the Path coordinates to match the layout that SwiftUI decides on... or if I even need to do so.

Runtime

My (test) app looks like this, Image borders (not frames) colored for clarity:

What I want is for taps in the opaque orange to be handled by that Image. Taps outside the opaque orange — even if within the bounds of the orange image — should "fall through" either to the green image or the gray background. But no. (The purple outline shows where the path is, according to itself; see code below).

Details

Here's the intrinsic (in pixels) layout of the images:

The path around the opaque part is trivially seen to be

```<code>[(200, 200), (600, 200), (600, 600), (200, 600)]
</code>```

How do these coordinates and the Image coordinates relate?

Code

```<code>extension CGPoint {
    typealias Tuple = (x:CGFloat, y:CGFloat)
    init(tuple t: Tuple) {
        self.init(x: t.x, y: t.y)
    }
}

struct ContentView: View {

    var points = [(200, 200), (600, 200), (600, 600), (200, 600)]
        .map(CGPoint.init(tuple:))
        // .map { p in p.shifted(dx:-64, dy:-10)}  // Didn't seem to help.

    var path : Path {
        var result = Path()
        result.move(to: points.first!)
        result.addLines(points)
        result.closeSubpath()
        return result
    }

    var body: some View {
        ZStack{
            Image("gray")       // Just so we record all touches.
            .resizable()
            .frame(maxWidth : .infinity,maxHeight: .infinity)
            .onTapGesture {
                print("background")
            }

            Image("square_green")
            .resizable()
            .scaledToFit()
            .border(Color.green, width: 4)
            .offset(x: 64, y:10)    // So the two Images don't overlap completely.
            .onTapGesture {
                print("green")
            }

            Image("square_orange")
            .resizable()
            .scaledToFit()
            .contentShape(path)        // Magic should happen here.
            .border(Color.orange, width: 4)
            .offset(x: -64, y:-10)
            // .contentShape(path)     // Didn't work here either.
            .onTapGesture {
                 print("orange")
            }

            path.stroke(Color.purple)  // Origin at absolute (200,200) as expected.

        }
    }
}
</code>```

答:
1) .offset only shifts content, but position of view in view hierarchy layout is not changed, so use instead .position;

2) shape for contentShape should be constructed in view coordinate space

Body:
TL;DR: I'm using a Path to specify the hit area for an Image. But I don't know how to adjust the Path coordinates to match the layout that SwiftUI decides on... or if I even need to do so.

Runtime

My (test) app looks like this, Image borders (not frames) colored for clarity:

What I want is for taps in the opaque orange to be handled by that Image. Taps outside the opaque orange — even if within the bounds of the orange image — should "fall through" either to the green image or the gray background. But no. (The purple outline shows where the path is, according to itself; see code below).

Details

Here's the intrinsic (in pixels) layout of the images:

The path around the opaque part is trivially seen to be

[(200, 200), (600, 200), (600, 600), (200, 600)]

How do these coordinates and the Image coordinates relate?

Code

extension CGPoint {
    typealias Tuple = (x:CGFloat, y:CGFloat)
    init(tuple t: Tuple) {
        self.init(x: t.x, y: t.y)
    }
}

struct ContentView: View {

    var points = [(200, 200), (600, 200), (600, 600), (200, 600)]
        .map(CGPoint.init(tuple:))
        // .map { p in p.shifted(dx:-64, dy:-10)}  // Didn't seem to help.

    var path : Path {
        var result = Path()
        result.move(to: points.first!)
        result.addLines(points)
        result.closeSubpath()
        return result
    }

    var body: some View {
        ZStack{
            Image("gray")       // Just so we record all touches.
            .resizable()
            .frame(maxWidth : .infinity,maxHeight: .infinity)
            .onTapGesture {
                print("background")
            }

            Image("square_green")
            .resizable()
            .scaledToFit()
            .border(Color.green, width: 4)
            .offset(x: 64, y:10)    // So the two Images don't overlap completely.
            .onTapGesture {
                print("green")
            }

            Image("square_orange")
            .resizable()
            .scaledToFit()
            .contentShape(path)        // Magic should happen here.
            .border(Color.orange, width: 4)
            .offset(x: -64, y:-10)
            // .contentShape(path)     // Didn't work here either.
            .onTapGesture {
                 print("orange")
            }

            path.stroke(Color.purple)  // Origin at absolute (200,200) as expected.

        }
    }
}


问:
Passing previously assigned variable in `{% for` block in Shopify
In blog-templte.liquid

```<code>{% assign articleSortOrder = '' %}
 ....

{% for article in blog.articles {{articleSortOrder}} %}
</code>```

got an error : Liquid syntax error: Unexpected character { in "article in blog.articles {{articleSortOrder}}"

The intention is to pass the variable to sort the articles depending on some condition.

Q: is how to make it work?

答:
This is not a valid liquid code:

{% for article in blog.articles {{articleSortOrder}} %}

You can't pass a liquid inside a liquid, a.k.a {% {{ }} %}

In addition for loops accept only a few parameters:

reversed - which will reverse the loop

limit - which will limit the iterations

offset - which will make the loop skip a specific set number of items

Sort is not one of them.

You can read more about the for loop here: https://shopify.dev/docs/liquid/reference/tags/iteration-tags

In order to sort the blog in a specific way you must code it like so:

```<code>{% assign articleSortOrder = '' %}
{% assign blog_articles_sort = blog.articles | sort: articleSortOrder %}
{% for article in blog_articles_sort %}

{% endfor %}
</code>```

Where you assign the articles in a specific variable and sort them.

Please have in mind that this will sort ONLY 50 articles.

If you like to sort more than 50 you will need to overwrite the paginate object {% paginate blog.articles by 9999 %}

Then your code will look like this:

```<code>{% paginate blog.articles by 9999 %}
  {% assign articleSortOrder = '' %}
  {% assign blog_articles_sort = blog.articles | sort: articleSortOrder %}
  {% for article in blog_articles_sort %}

  {% endfor %}
{% endpaginate %}
</code>```

More about paginate can be seen here: https://shopify.dev/docs/liquid/reference/tags/theme-tags/#paginate

Please have in mind that the sort function in Shopify is limited. You may need to sort them with javascript or another approach depending one what you are looking for.

Body:
In blog-templte.liquid

{% assign articleSortOrder = '' %}
 ....

{% for article in blog.articles {{articleSortOrder}} %}

got an error : Liquid syntax error: Unexpected character { in "article in blog.articles {{articleSortOrder}}"

The intention is to pass the variable to sort the articles depending on some condition.

Q: is how to make it work?

Body:
This is not a valid liquid code:

{% for article in blog.articles {{articleSortOrder}} %}

You can't pass a liquid inside a liquid, a.k.a {% {{ }} %}

In addition for loops accept only a few parameters:

reversed - which will reverse the loop

limit - which will limit the iterations

offset - which will make the loop skip a specific set number of items

Sort is not one of them.

You can read more about the for loop here: https://shopify.dev/docs/liquid/reference/tags/iteration-tags

In order to sort the blog in a specific way you must code it like so:

{% assign articleSortOrder = '' %}
{% assign blog_articles_sort = blog.articles | sort: articleSortOrder %}
{% for article in blog_articles_sort %}

{% endfor %}

Where you assign the articles in a specific variable and sort them.

Please have in mind that this will sort ONLY 50 articles.

If you like to sort more than 50 you will need to overwrite the paginate object {% paginate blog.articles by 9999 %}

Then your code will look like this:

{% paginate blog.articles by 9999 %}
  {% assign articleSortOrder = '' %}
  {% assign blog_articles_sort = blog.articles | sort: articleSortOrder %}
  {% for article in blog_articles_sort %}

  {% endfor %}
{% endpaginate %}

More about paginate can be seen here: https://shopify.dev/docs/liquid/reference/tags/theme-tags/#paginate

Please have in mind that the sort function in Shopify is limited. You may need to sort them with javascript or another approach depending one what you are looking for.


问:
Transformers summarization with Python Pytorch - how to get longer output?
I use Ai-powered summarization from https://github.com/huggingface/transformers/tree/master/examples/summarization - state of the art results.

Should i train it myself to get summary output longer than used in original huggingface github training script?
:

```<code>python run_summarization.py \
    --documents_dir $DATA_PATH \
    --summaries_output_dir $SUMMARIES_PATH \ # optional
    --no_cuda false \
    --batch_size 4 \
    --min_length 50 \
    --max_length 200 \
    --beam_size 5 \
    --alpha 0.95 \
    --block_trigram true \
    --compute_rouge true
</code>```

When i do inference with

```<code>--min_length 500 \
--max_length 600 \
</code>```

I got a good output for 200 tokens, but the rest of the text is

```<code>. . . [unused7] [unused7] [unused7] [unused8] [unused4] [unused7] [unused7]  [unused4] [unused7] [unused8]. [unused4] [unused7] . [unused4] [unused8] [unused4] [unused8].  [unused4]  [unused4] [unused8]  [unused4] . .  [unused4] [unused6] [unused4] [unused7] [unused6] [unused4] [unused8] [unused5] [unused4] [unused7] [unused4] [unused4] [unused7]. [unused4] [unused6]. [unused4] [unused4] [unused4] [unused8]  [unused4] [unused7]  [unused4] [unused8] [unused6] [unused4]   [unused4] [unused4]. [unused4].  [unused5] [unused4] [unused8] [unused7] [unused4] [unused7] [unused9] [unused4] [unused7]  [unused4] [unused7] [unused5] [unused4]  [unused5] [unused4] [unused6]  [unused4]. .  . [unused5]. [unused4]  [unused4]   [unused4] [unused6] [unused5] [unused4] [unused4]  [unused6] [unused4] [unused6]  [unused4] [unused4] [unused5] [unused4]. [unused5]  [unused4] . [unused4]  [unused4] [unused8] [unused8] [unused4]  [unused7] [unused4] [unused8]  [unused4] [unused7]  [unused4] [unused8]  [unused4]  [unused8] [unused4] [unused6]
</code>```

答:
The short answer is: Yes, probably.

To explain this in a bit more detail, we have to look at the paper behind the implementation: In Table 1, you can clearly see that most of their generated headlines are much shorter than what you are trying to initialize. While that alone might not be an indicator that you couldn't generate anything longer, we can go even deeper and look at the meaning of the [unusedX] tokens, as described by BERT dev Jacob Devlin:

Since [the [unusedX] tokens] were not used they are effectively randomly initialized.

Further, the summariazation paper describes

Position embeddings in the original BERT model have a maximum length
  of 512; we over-come this limitation by adding more position
  em-beddings  that  are  initialized randomly and fine-tuned with other
  parameters in the encoder.

This is a strong indicator that past a certain length, they are likely falling back to the default initialization, which is unfortunately random. The question is whether you can still salvage the previous pre-training, and simply fine-tune to your objective, or whether it is better to just start from scratch.

Body:
I use Ai-powered summarization from https://github.com/huggingface/transformers/tree/master/examples/summarization - state of the art results.

Should i train it myself to get summary output longer than used in original huggingface github training script?
:

python run_summarization.py \
    --documents_dir $DATA_PATH \
    --summaries_output_dir $SUMMARIES_PATH \ # optional
    --no_cuda false \
    --batch_size 4 \
    --min_length 50 \
    --max_length 200 \
    --beam_size 5 \
    --alpha 0.95 \
    --block_trigram true \
    --compute_rouge true

When i do inference with

--min_length 500 \
--max_length 600 \

I got a good output for 200 tokens, but the rest of the text is

. . . [unused7] [unused7] [unused7] [unused8] [unused4] [unused7] [unused7]  [unused4] [unused7] [unused8]. [unused4] [unused7] . [unused4] [unused8] [unused4] [unused8].  [unused4]  [unused4] [unused8]  [unused4] . .  [unused4] [unused6] [unused4] [unused7] [unused6] [unused4] [unused8] [unused5] [unused4] [unused7] [unused4] [unused4] [unused7]. [unused4] [unused6]. [unused4] [unused4] [unused4] [unused8]  [unused4] [unused7]  [unused4] [unused8] [unused6] [unused4]   [unused4] [unused4]. [unused4].  [unused5] [unused4] [unused8] [unused7] [unused4] [unused7] [unused9] [unused4] [unused7]  [unused4] [unused7] [unused5] [unused4]  [unused5] [unused4] [unused6]  [unused4]. .  . [unused5]. [unused4]  [unused4]   [unused4] [unused6] [unused5] [unused4] [unused4]  [unused6] [unused4] [unused6]  [unused4] [unused4] [unused5] [unused4]. [unused5]  [unused4] . [unused4]  [unused4] [unused8] [unused8] [unused4]  [unused7] [unused4] [unused8]  [unused4] [unused7]  [unused4] [unused8]  [unused4]  [unused8] [unused4] [unused6]


问:
How to Serialize xml and get just deepest nodes
I have the following xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<root>
    <file_1>
        <file_name Value="" />
        <date Value="" />
        <information>
            <page1>
                <percentage Value="90%" />
                <profit Value="50%" />
                <total Value="$1500" />
            </page1>
        </information>
    </file_1>
</root>
</code>```

and I want to serialize that xml but I want that all subnodes in page1 node could be handle like properties, for example:

```<code>var xmlInfo = new List<xmlClass>();
var FieldName = xmlInfo[0].FieldName; // the value of FieldName should be percentage
var data = xmlInfo[0].Value; // the value of data should be 90%
</code>```

In other words, I'm only interested in the deepest nodes to serialize them into an object.

I have a serialization method, but I don't know how to build the class.

```<code>public static T Deserialize<T>(XDocument doc)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

            using (var reader = doc.Root.CreateReader())
            {
                return (T)xmlSerializer.Deserialize(reader);
            }
        }
</code>```

答: The XPath expression //*[not(child::node())] returns all elements without child nodes (either child elements or child text nodes), if that matches your definition of "deepest".

Body:
I have the following xml file

<?xml version="1.0" encoding="utf-8"?>
<root>
    <file_1>
        <file_name Value="" />
        <date Value="" />
        <information>
            <page1>
                <percentage Value="90%" />
                <profit Value="50%" />
                <total Value="$1500" />
            </page1>
        </information>
    </file_1>
</root>

and I want to serialize that xml but I want that all subnodes in page1 node could be handle like properties, for example:

var xmlInfo = new List<xmlClass>();
var FieldName = xmlInfo[0].FieldName; // the value of FieldName should be percentage
var data = xmlInfo[0].Value; // the value of data should be 90%

In other words, I'm only interested in the deepest nodes to serialize them into an object.

I have a serialization method, but I don't know how to build the class.

public static T Deserialize<T>(XDocument doc)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

            using (var reader = doc.Root.CreateReader())
            {
                return (T)xmlSerializer.Deserialize(reader);
            }
        }


问:
Native UITextField Secure Text Entry forces English (US) keyboard
I have a very simple login page (login + password).

My users are french, so their keyboard are French (azerty).

Since iOS 12, when they click on the password textfield, which is secured, the keyboard switches to English (qwerty), even if they do not have this keyboard installed on their devices. Moreover, if they do not have this keyboard installed, they can't switch back to their keyboard.

I found out that if I deactivate Secure Text Entry, the problem does not show up.

I also tried to set isSecureTextEntry programmatically, and the bug shows up.

I am adding two screenshots, one for each text field.

Thank you a lot for your time & help.

答:
Just in case, I corrected this by simply adding this to my main viewController :

```<code>func passwordSignUpViewController(forAuthUI authUI: FUIAuth, email: String, requireDisplayName: Bool) -> FUIPasswordSignUpViewController {
    return CustomPasswordSignUpViewController(authUI: authUI, email: email, requireDisplayName: true)
}
</code>```

And I created the subclass of FUIPasswordSignUpViewController

```<code>import Foundation
import FirebaseUI

class CustomPasswordSignUpViewController : FUIPasswordSignUpViewController, UITextFieldDelegate {

 override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?, authUI: FUIAuth, email: String?, requireDisplayName: Bool) {
    super.init(nibName: "FUIPasswordSignUpViewController", bundle: nibBundleOrNil, authUI: authUI, email: email, requireDisplayName: requireDisplayName)
 }

 required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
 }

 override func viewDidLoad() {
    super.viewDidLoad()
 }

 func textFieldDidBeginEditing(_ textField: UITextField) {
    if #available(iOS 12.0, *) {
        textField.textContentType = .oneTimeCode
    }
 }
}
</code>```

Body:
Just in case, I corrected this by simply adding this to my main viewController :

func passwordSignUpViewController(forAuthUI authUI: FUIAuth, email: String, requireDisplayName: Bool) -> FUIPasswordSignUpViewController {
    return CustomPasswordSignUpViewController(authUI: authUI, email: email, requireDisplayName: true)
}

And I created the subclass of FUIPasswordSignUpViewController

import Foundation
import FirebaseUI

class CustomPasswordSignUpViewController : FUIPasswordSignUpViewController, UITextFieldDelegate {

 override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?, authUI: FUIAuth, email: String?, requireDisplayName: Bool) {
    super.init(nibName: "FUIPasswordSignUpViewController", bundle: nibBundleOrNil, authUI: authUI, email: email, requireDisplayName: requireDisplayName)
 }

 required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
 }

 override func viewDidLoad() {
    super.viewDidLoad()
 }

 func textFieldDidBeginEditing(_ textField: UITextField) {
    if #available(iOS 12.0, *) {
        textField.textContentType = .oneTimeCode
    }
 }
}