问:
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><androidx.recyclerview.widget.RecyclerView
    android:id="@+id/my_recycler_view"
    android:scrollbars="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
</code>```

Instead of,

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

You are using androidx in MainActivity.

Hope this solves :)

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:
<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/my_recycler_view"
    android:scrollbars="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Instead of,

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

You are using androidx in MainActivity.

Hope this solves :)


来源: stackexchange

问:
Use Razor views as email templates inside a Web Forms app
I have an asp.net Web Forms application that needs to send emails.  I like the Razor syntax and as you can use Razor outside of MVC I thought I'd try and use that.  I've seen that you can programmatically pass a template string to razor but I'd like to keep my razor templates as separate .cshtml files.

Does anyone have any simple, idiot-proof advice as to how to do this?  I've tried to load them from file like this:

```<code>UserDetails userDetails = new UserDetails {Name = "Fred"};
string template = File.OpenText("Email/UserDetailsEmail.cshtml").ReadToEnd();
string messageText = Razor.Parse(template, userDetails);
</code>```

All to no avail.  There's an exception finding the file.  I'm using the razorengine dll.

I have everything else working, the smtp server etc, just not the views.

Any help appreciated.

答:
I would use the MVCMailer tool which you can setup with Nuget and has scaffolding for creating the views.

It is a very well written app and can be added to yours easily:

https://github.com/smsohan/MvcMailer

http://www.codeproject.com/KB/aspnet/MvcMailerNuGet.aspx

ContentLicense: CC BY-SA 3.0

Body:
I have an asp.net Web Forms application that needs to send emails.  I like the Razor syntax and as you can use Razor outside of MVC I thought I'd try and use that.  I've seen that you can programmatically pass a template string to razor but I'd like to keep my razor templates as separate .cshtml files.

Does anyone have any simple, idiot-proof advice as to how to do this?  I've tried to load them from file like this:

UserDetails userDetails = new UserDetails {Name = "Fred"};
string template = File.OpenText("Email/UserDetailsEmail.cshtml").ReadToEnd();
string messageText = Razor.Parse(template, userDetails);

All to no avail.  There's an exception finding the file.  I'm using the razorengine dll.

I have everything else working, the smtp server etc, just not the views.

Any help appreciated.


问:
How do you make a div shaped like an ellipse in CSS?
I am trying to make the following shapes with css. I don't know how I can do this, can you help?

答:
The steps are the following:

First we have an ordinary, rectangular DIV (let it be 32px in this example):

```<code>#example {
  width: 32px;
  height: 32px;
  background-color: red;
}
</code>```

With the border-radius property, we effectively convert it to a circle. The trick is that if we give it a 16px border-radius, we get a circle:

```<code>#example {
  width: 32px;
  height: 32px;
  background: red;
  border-radius: 16px;
}
</code>```

After that, with the transform: css-property we stretch it in a single direction. transform: scaleX(...) can stretch a div horizontally.

```<code>#example {
  width: 32px;
  height: 32px;
  background-color: red;
  border-radius: 16px;
  transform: scaleX(3.14);
}
</code>```

And done.

To get a rotated ellipse, you need 2 divs, or a matrix-based css-transform, to combine rotation and stretching.

ContentLicense: CC BY-SA 4.0

Body:
The steps are the following:

First we have an ordinary, rectangular DIV (let it be 32px in this example):

#example {
  width: 32px;
  height: 32px;
  background-color: red;
}

With the border-radius property, we effectively convert it to a circle. The trick is that if we give it a 16px border-radius, we get a circle:

#example {
  width: 32px;
  height: 32px;
  background: red;
  border-radius: 16px;
}

After that, with the transform: css-property we stretch it in a single direction. transform: scaleX(...) can stretch a div horizontally.

#example {
  width: 32px;
  height: 32px;
  background-color: red;
  border-radius: 16px;
  transform: scaleX(3.14);
}

And done.

To get a rotated ellipse, you need 2 divs, or a matrix-based css-transform, to combine rotation and stretching.


问:
Encode UTF8 text to Unicode C#
How to encode UTF8 text to Unicode?

```<code>string text_txt = "Ð¿ÑÐ¸Ð²ÐµÑ";
byte[] bytesUtf8 = Encoding.Default.GetBytes(text_txt);
text_txt = Encoding.UTF8.GetString(bytesUtf8);
</code>```

The problem is output: п�?иве�

I need output: привет

Using that site: https://www.branah.com/unicode-converter enter text in "UTF-8 text (Example: a ä¸ Ð¯)" to "Ð¿ÑÐ¸Ð²ÐµÑ" it will show you "привет" on Unicode text

Please give some advice thanks

答:
You need to be explicit about the type of encoding you're using to convert to bytes, (Syste.Text.Encoding.UTF8.GetBytes). eg:

```<code>using System;
using System.Text;

public class Program {
    public static void Main() {
        string text_txt = "Ð¿ÑÐ¸Ð²ÐµÑ";

        byte[] bytesUtf8 = Encoding.UTF8.GetBytes(text_txt);
        text_txt = Encoding.UTF8.GetString(bytesUtf8);

        Console.WriteLine(text_txt);
    }
}
</code>```

This way UTF8 is used to both encode and decode the string the same way, and when you ensure the same string comes back from the GetString method.

Title: Encode UTF8 text to Unicode C#

Body:
How to encode UTF8 text to Unicode?

string text_txt = "Ð¿ÑÐ¸Ð²ÐµÑ";
byte[] bytesUtf8 = Encoding.Default.GetBytes(text_txt);
text_txt = Encoding.UTF8.GetString(bytesUtf8);

The problem is output: п�?иве�

I need output: привет

Using that site: https://www.branah.com/unicode-converter enter text in "UTF-8 text (Example: a ä¸ Ð¯)" to "Ð¿ÑÐ¸Ð²ÐµÑ" it will show you "привет" on Unicode text

Please give some advice thanks

Body:
You need to be explicit about the type of encoding you're using to convert to bytes, (Syste.Text.Encoding.UTF8.GetBytes). eg:

using System;
using System.Text;

public class Program {
    public static void Main() {
        string text_txt = "Ð¿ÑÐ¸Ð²ÐµÑ";

        byte[] bytesUtf8 = Encoding.UTF8.GetBytes(text_txt);
        text_txt = Encoding.UTF8.GetString(bytesUtf8);

        Console.WriteLine(text_txt);
    }
}

This way UTF8 is used to both encode and decode the string the same way, and when you ensure the same string comes back from the GetString method.


问:
How to find an element which attribute has exact value and attribute name starts with given pattern with xpath
I would like to find an element which attribute has exact value and attribute name starts with given pattern.

HTML:

```<code><div class=col-xs-12>
    <select name=registrationProcedureCode tabIndex=-1 class="form-control selectized" id=registrationProcedureNew style="DISPLAY: none" data-bind="options: [''], value: registrationProcedureCode, optionsCaption: i2chCaption" jQuery1124022385363269720443="36" __ko__1582114720513="ko21">
        <option value="" selected></option>
    </select>
    <div class="selectize-control form-control single">
        <div class="selectize-input items not-full" jQuery1124022385363269720443="139">
            <input tabIndex=-32768 style="WIDTH: 337px" type=text autocomplete="off" placeholder="bla" jQuery1124022385363269720443="141">
        </div>
        <div class="selectize-dropdown single form-control" style="WIDTH: 627px; LEFT: 0px; DISPLAY: none; TOP: 34px" jQuery1124022385363269720443="136">
            <div class=selectize-dropdown-content></div>
        </div>
    </div>
</div>
</code>```

And there are some other div elements with jQueryblabla attributes.
So I need to find this div element with attribute value 139 and attribute name starting with jQuery.

I tried this line:

//div[@*[starts-with(name(), 'jQuery')]='139']

But it is wrong. Please let me know how to fix it.

答:
The correct way to write my xpath expression is

```<code>//div[@*[starts-with(name(), 'jquery')]='139']
</code>```

Cheers to @JackFleeting!

Body:
I would like to find an element which attribute has exact value and attribute name starts with given pattern.

HTML:

    <select name=registrationProcedureCode tabIndex=-1 class="form-control selectized" id=registrationProcedureNew style="DISPLAY: none" data-bind="options: [''], value: registrationProcedureCode, optionsCaption: i2chCaption" jQuery1124022385363269720443="36" __ko__1582114720513="ko21">
        <option value="" selected></option>
    </select>

            <input tabIndex=-32768 style="WIDTH: 337px" type=text autocomplete="off" placeholder="bla" jQuery1124022385363269720443="141">

And there are some other div elements with jQueryblabla attributes.
So I need to find this div element with attribute value 139 and attribute name starting with jQuery.

I tried this line:

//div[@*[starts-with(name(), 'jQuery')]='139']

But it is wrong. Please let me know how to fix it.

Body:
The correct way to write my xpath expression is

//div[@*[starts-with(name(), 'jquery')]='139']

Cheers to @JackFleeting!


问:
How to run Python and Jupyter with same virtual env, working with Visual Studio Code
For my current job it would be extremely helpful to be able to configure a virtualenv with the appropiate libraries versions, and be able to run either a python project, or cells in jupyter. This is because some people at my job work with jupyter, and some with Python, and sometimes both, and this way I would have a centralized program that could run both types, which I have not found outsaid of the paid version of PyCharm, which my company does not provide.

I just learned a few days ago about Windows Subsystem for Linux, WSL, and that it can be launched from withing Visual Studio Code, so I feel like this is my best bet to achieve that dual nature of programming from just ONE program, instead of running several like in the past.

As of right now, I have a repository cloned with WSL for a git project with different ".py" files, I open it with VSC, then open the terminal inside VSC, and I can both edit the Python code, and run it on the terminal, using bash commands as I would if I were in Ubuntu (I am doing all this from windows but can switch to Ubuntu if it would mean to be able to do this type of setup).

When I run with "Run Python file in terminal", it uses the virtualenv I have previously created.

The problem is, with Jupyter, it does not detect I have the libraries installed (like Pandas for example)

Description of my process with Jupyter so far: With the WSL console, I launch a jupyter notebook &. I then connect to that server, usin the VSC option for "Specify Local or Remote Jupyter server for connections", use the "Existing" option, copy the URL, then I go to the ".ipynb" file and start running code.

If, in a Jupyter cell, I do

```<code>import os
os.environ['VIRTUAL_ENV']
</code>```

I can see my virtual enviroment. If right after that, I run import pandas I get ModuleNotFoundError: No module named 'pandas'

If I do !pip freeze I can see all the libraries and right versions that I have installed in that enviroment.

I feel like I am almost there but something is missing. My guess is that import might be going to some default installed Python, and not the one from the enviroment, for some reason I am missing.

答:
Solved by doing what this answer suggests. The rest of answers may be of help, too:

https://stackoverflow.com/a/51036073/6028947

Body:
For my current job it would be extremely helpful to be able to configure a virtualenv with the appropiate libraries versions, and be able to run either a python project, or cells in jupyter. This is because some people at my job work with jupyter, and some with Python, and sometimes both, and this way I would have a centralized program that could run both types, which I have not found outsaid of the paid version of PyCharm, which my company does not provide.

I just learned a few days ago about Windows Subsystem for Linux, WSL, and that it can be launched from withing Visual Studio Code, so I feel like this is my best bet to achieve that dual nature of programming from just ONE program, instead of running several like in the past.

As of right now, I have a repository cloned with WSL for a git project with different ".py" files, I open it with VSC, then open the terminal inside VSC, and I can both edit the Python code, and run it on the terminal, using bash commands as I would if I were in Ubuntu (I am doing all this from windows but can switch to Ubuntu if it would mean to be able to do this type of setup).

When I run with "Run Python file in terminal", it uses the virtualenv I have previously created.

The problem is, with Jupyter, it does not detect I have the libraries installed (like Pandas for example)

Description of my process with Jupyter so far: With the WSL console, I launch a jupyter notebook &. I then connect to that server, usin the VSC option for "Specify Local or Remote Jupyter server for connections", use the "Existing" option, copy the URL, then I go to the ".ipynb" file and start running code.

If, in a Jupyter cell, I do

import os
os.environ['VIRTUAL_ENV']

I can see my virtual enviroment. If right after that, I run import pandas I get ModuleNotFoundError: No module named 'pandas'

If I do !pip freeze I can see all the libraries and right versions that I have installed in that enviroment.

I feel like I am almost there but something is missing. My guess is that import might be going to some default installed Python, and not the one from the enviroment, for some reason I am missing.


问:
Check mutiple values in Array and append third value in html
I want to check if mutiple vlaues exists in the array, and if they do, append the value of a third one- the script below obvously doesnt work, but might give a good idea on what I want to do. i only want to add this once, even if the array checks several times.

What's the best way to do this?

var names = {
  list: [{
      "model": "round",
      "type": "Special",
      "typedescription": "appendedvalue"
    }, {
      "model": "round",
      "type": "Special",
      "typedescription": "appendedvalue",
    }
    "model": "round",
    "type": "Special",
    "typedescription": "appendedvalue"
  },
  {
    "model": "square",
    "type": "Special",
    "typedescription": "appendedvalue"
  }]

};

if ($.inArray('model.round', 'type.special'
    names) !== -1) {
  $('.test').append('
' + typedescription.appendedvalue + '
');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="test"></div></code>```

答:
```<code>var names = {
  list: [
    {
      "model": "round",
      "type": "Special",
      "typeDescription": "appendedvalue"
    },
    {
      "model": "round",
      "type": "Special",
      "typeDescription": "appendedvalue",
    },
    {
      "model": "round",
      "type": "Special",
      "typeDescription": "appendedvalue"
    },
    {
      "model": "square",
      "type": "Special",
      "typeDescription": "appendedvalue"
    }
  ]
};

let name = names
  .list
  .find(n => n.model === "round" && n.type === "Special");

if(name) {
  $('.test').append(`<p>${name.typeDescription}</p>`);
}
</code>```


问:
Thread-safe uniform random number generator
I have some parallel Fortran90 code in which each thread needs to generate the same sequence of random numbers.

I have a random number generator that seems to be thread-unsafe, since, for a given seed, I'm completely unable to repeat the same results each time I run the program.

I surfed unsuccessfully (almost) the entire web looking for some code of a thread-safe RNG. Could anyone provide me with (the link to) the code of one?

Thanks in advance!

答: How about SPRNG?  I have not tried it myself though.</p>

OwnerDisplayName: Bellman

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eric P

OwnerDisplayName: Jakob Christensen


问:
How do I POST to a web page using Firebug?
How do I POST to a web page using Firebug?</p>

答:
I know this is an old question, but I recently stumbled upon the same problem and wanted to share the method I am using.

Assuming the web site you want to POST to has a form with method="POST" (a very likely scenario), you can use Firebug's JavaScript command line to programmatically submit a POST request. Just click the "Show Command Line" icon in Firebug and enter something like this in the narrow text box at the very bottom of the window:

```<code>    document.forms[0].submit()
</code>```

Maybe this helps someone.

Body:
I know this is an old question, but I recently stumbled upon the same problem and wanted to share the method I am using.

Assuming the web site you want to POST to has a form with method="POST" (a very likely scenario), you can use Firebug's JavaScript command line to programmatically submit a POST request. Just click the "Show Command Line" icon in Firebug and enter something like this in the narrow text box at the very bottom of the window:

    document.forms[0].submit()

Maybe this helps someone.


答:
border-radius: 50% and transform: rotate(-10deg) are what you're looking for.

div {
  height: 200px;
  width: 400px;
  border-radius: 50%;
  transform: rotate(-10deg);
  border: 1px solid;
  background: #e1ecf4;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

Title: How do you make a div shaped like an ellipse in CSS?

Body: I am trying to make the following shapes with css. I don't know how I can do this, can you help?

Body:
border-radius: 50% and transform: rotate(-10deg) are what you're looking for.

div {
  height: 200px;
  width: 400px;
  border-radius: 50%;
  transform: rotate(-10deg);
  border: 1px solid;
  background: #e1ecf4;
}

<div></div>


问:
Update table column based on condition of existing and another table
I have two huge tables with millions rec's, ORDER and ORDER_DETAILS

```<code>    ORDER
    id NUMBER;
    desc VARCHAR;
    code VARCHAR;
    total_amount NUMBER;

    ORDER_DETAILS
    id NUMBER;
    desc VARCHAR;
    code VARCHAR;
    amount NUMBER;

    ORDER table contains 'total amount' per id, desc
    ORDER
    ID DESC CODE, TOTAL_AMOUNT
    1  tl1  OTL1  20
    2  tl2  OTL8  50
</code>```

ORDER_DETAILS contains semi-total (amount) per order (id&desc)

```<code>ORDER_DETAILS
    ID DESC CODE, AMOUNT
    1  tl1  NULL  10
    1  tl1  NULL  10
    2  tl2  NULL  10
    2  tl2  NULL  10
    2  tl2  NULL  20
    2  tl2  NULL  10
</code>```

I need to update order_detail.code using the algorithm:

```<code> IF SUM(AMOUNT) = TOTAL_AMOUNT -per id & desc
 THEN UPDATE SET order_detail.code=ORDER.CODE
</code>```

So, the results should be:

```<code>ORDER_DETAILS
 ID DESC CODE, AMOUNT
 1  tl1  OTL1  10
 1  tl1  OTL1  10
 2  tl2  OTL8  10
 2  tl2  OTL8  10
 2  tl2  OTL8  20
 2  tl2  OTL8  10
</code>```

I tried the following, but it never ends:

```<code>    UPDATE ORDER_DETAIL A SET A.CODE = (SELECT TEMP1.CODE
                                         FROM
                                        ( SELECT
                                           ID,
                                           CODE,
                                           DESC,
                                           TOTAL_AMOUNT,
                                           SUM (AMOUNT) SUMAMNT
                                          FROM ORDER A, ORDER_DETAIL B
                                          WHERE A.ID  = B.ID
                                          AND   A.DESC  = B.DESC
                                          AND   B.AMOUNT<>0
                                          AND   B.CODE IS NULL
                                          GROUP BY AMOUNT ,ID, CODE, DESC, TOTAL_AMOUNT
                                          HAVING SUM (AMOUNT) = A.TOTAL_AMOUNT) TEMP1
                                          WHERE A.ID=TEMP1.ID
                                          AND   A.DESC=TEMP1.DESC
                                        );
</code>```

How can I achieve the desired result? If possible using a single sql statement?

Any help is appreciated and thanking you in advance

Hi Tejash,
Thank you for your answer
Please check below plan,, cost is huge,, it perform full scan on both tables –twice @ORDER_DETAILS

Plan

```<code>MERGE STATEMENT  CHOOSE
Cost: 2.894.308
    13 MERGE ORDER_DETAILS
        12 VIEW
            11 HASH JOIN  Cost: 2.894.308  Bytes: 246,708  Cardinality: 1,068
                8 VIEW  Cost: 2.375.331  Bytes: 115,344  Cardinality: 1,068
                    7 FILTER
                        6 SORT GROUP BY  Cost: 2.375.331  Bytes: 76,896  Cardinality: 1,068
                            5 HASH JOIN  Cost: 2.367.824  Bytes: 3.834.697.392  Cardinality: 53.259.686
                                2 PARTITION RANGE ALL  Cost: 517,16  Bytes: 1.757.569.638  Cardinality: 53.259.686
                                    1 TABLE ACCESS FULL TABLE ORDER_DETAILS Cost: 517,16  Bytes: 1.757.569.638  Cardinality: 53.259.686
                                4 PARTITION RANGE ALL  Cost: 1.512.742  Bytes: 3.576.967.836  Cardinality: 91.717.124
                                    3 TABLE ACCESS FULL TABLE ORDER Cost: 1.512.742  Bytes: 3.576.967.836  Cardinality: 91.717.124
                10 PARTITION RANGE ALL  Cost: 518,328  Bytes: 6.550.941.378  Cardinality: 53.259.686
                    9 TABLE ACCESS FULL TABLE ORDER_DETAILS Cost: 518,328  Bytes: 6.550.941.378  Cardinality: 53.259.686
</code>```

答:
Im only familiar with msSQL, but I think the following is standard SQL and apply to most DBs.</p>

```<code>Begin tran
 Update t
      Set t.code = t.hdr
  From(
     Select d.code, o.code as her
       From order_detail d
        Join order o on o.id = d.id) t
Commit tran
</code>```

Body:
I have two huge tables with millions rec's, ORDER and ORDER_DETAILS

    ORDER
    id NUMBER;
    desc VARCHAR;
    code VARCHAR;
    total_amount NUMBER;

    ORDER_DETAILS
    id NUMBER;
    desc VARCHAR;
    code VARCHAR;
    amount NUMBER;

    ORDER table contains 'total amount' per id, desc
    ORDER
    ID DESC CODE, TOTAL_AMOUNT
    1  tl1  OTL1  20
    2  tl2  OTL8  50

ORDER_DETAILS contains semi-total (amount) per order (id&desc)

ORDER_DETAILS
    ID DESC CODE, AMOUNT
    1  tl1  NULL  10
    1  tl1  NULL  10
    2  tl2  NULL  10
    2  tl2  NULL  10
    2  tl2  NULL  20
    2  tl2  NULL  10

I need to update order_detail.code using the algorithm:

 IF SUM(AMOUNT) = TOTAL_AMOUNT -per id & desc
 THEN UPDATE SET order_detail.code=ORDER.CODE

So, the results should be:

ORDER_DETAILS
 ID DESC CODE, AMOUNT
 1  tl1  OTL1  10
 1  tl1  OTL1  10
 2  tl2  OTL8  10
 2  tl2  OTL8  10
 2  tl2  OTL8  20
 2  tl2  OTL8  10

I tried the following, but it never ends:

    UPDATE ORDER_DETAIL A SET A.CODE = (SELECT TEMP1.CODE
                                         FROM
                                        ( SELECT
                                           ID,
                                           CODE,
                                           DESC,
                                           TOTAL_AMOUNT,
                                           SUM (AMOUNT) SUMAMNT
                                          FROM ORDER A, ORDER_DETAIL B
                                          WHERE A.ID  = B.ID
                                          AND   A.DESC  = B.DESC
                                          AND   B.AMOUNT<>0
                                          AND   B.CODE IS NULL
                                          GROUP BY AMOUNT ,ID, CODE, DESC, TOTAL_AMOUNT
                                          HAVING SUM (AMOUNT) = A.TOTAL_AMOUNT) TEMP1
                                          WHERE A.ID=TEMP1.ID
                                          AND   A.DESC=TEMP1.DESC
                                        );

How can I achieve the desired result? If possible using a single sql statement?

Any help is appreciated and thanking you in advance

Hi Tejash,
Thank you for your answer
Please check below plan,, cost is huge,, it perform full scan on both tables –twice @ORDER_DETAILS

Plan

MERGE STATEMENT  CHOOSE
Cost: 2.894.308
    13 MERGE ORDER_DETAILS
        12 VIEW
            11 HASH JOIN  Cost: 2.894.308  Bytes: 246,708  Cardinality: 1,068
                8 VIEW  Cost: 2.375.331  Bytes: 115,344  Cardinality: 1,068
                    7 FILTER
                        6 SORT GROUP BY  Cost: 2.375.331  Bytes: 76,896  Cardinality: 1,068
                            5 HASH JOIN  Cost: 2.367.824  Bytes: 3.834.697.392  Cardinality: 53.259.686
                                2 PARTITION RANGE ALL  Cost: 517,16  Bytes: 1.757.569.638  Cardinality: 53.259.686
                                    1 TABLE ACCESS FULL TABLE ORDER_DETAILS Cost: 517,16  Bytes: 1.757.569.638  Cardinality: 53.259.686
                                4 PARTITION RANGE ALL  Cost: 1.512.742  Bytes: 3.576.967.836  Cardinality: 91.717.124
                                    3 TABLE ACCESS FULL TABLE ORDER Cost: 1.512.742  Bytes: 3.576.967.836  Cardinality: 91.717.124
                10 PARTITION RANGE ALL  Cost: 518,328  Bytes: 6.550.941.378  Cardinality: 53.259.686
                    9 TABLE ACCESS FULL TABLE ORDER_DETAILS Cost: 518,328  Bytes: 6.550.941.378  Cardinality: 53.259.686

Body:
Im only familiar with msSQL, but I think the following is standard SQL and apply to most DBs.

Begin tran
 Update t
      Set t.code = t.hdr
  From(
     Select d.code, o.code as her
       From order_detail d
        Join order o on o.id = d.id) t
Commit tran


问:
NameError: name 'run_once' is not defined in python
Python: 3.8.1

I wanted to run a method only once in my class. I have learned the following ways of achieving things and worked well.

```<code>def run_once():
    # Code for something you only want to execute once
    print("test")
    run_once.__code__ = (lambda: None).__code__
    return "Success"

print(run_once())
print(run_once())
print(run_once())
</code>```

Output:- --> Expected and Actual

```<code>test
Success
None
None
</code>```

Apparently, getting an error while trying to achieving the same via static method in a class.

```<code>class testing():

    @staticmethod
    def run_once(data):
        # Code for something you only want to execute once
        print(data)
        run_once("").__code__ = (lambda: None).__code__
        return "Success"

print(testing.run_once("test"))
</code>```

Trackback:-

```<code>Traceback (most recent call last):
  File "foo/test.py", line 11, in <module>
    print(testing.run_once("test"))
  File "foo/test.py", line 7, in run_once
    run_once("").__code__ = (lambda: None).__code__
NameError: name 'run_once' is not defined
test
</code>```

Could someone highlight where changes required to be made?

答:
When you define run_once as a static method inside the testing class it must be referenced as testing.run_once, since run_once does not exists outside that class.

class testing():
    @staticmethod
    def run_once(data):
        # Code for something you only want to execute once
        print(data)
        testing.run_once.__code__ = (lambda x: None).__code__
        return "Success"
```

Body:
Python: 3.8.1

I wanted to run a method only once in my class. I have learned the following ways of achieving things and worked well.

def run_once():
    # Code for something you only want to execute once
    print("test")
    run_once.__code__ = (lambda: None).__code__
    return "Success"

print(run_once())
print(run_once())
print(run_once())

Output:- --> Expected and Actual

test
Success
None
None

Apparently, getting an error while trying to achieving the same via static method in a class.

class testing():

    @staticmethod
    def run_once(data):
        # Code for something you only want to execute once
        print(data)
        run_once("").__code__ = (lambda: None).__code__
        return "Success"

print(testing.run_once("test"))

Trackback:-

Traceback (most recent call last):
  File "foo/test.py", line 11, in <module>
    print(testing.run_once("test"))
  File "foo/test.py", line 7, in run_once
    run_once("").__code__ = (lambda: None).__code__
NameError: name 'run_once' is not defined
test

Could someone highlight where changes required to be made?


问:
Qt QWebEngine Remote Debugging: Chrome developer tools no longer work
Recently after some software updates (automated Windows 10 update, and possibly a Chrome auto-update) the developer tools for remote debugging from Qt's QWebEngine stopped working. The JavaScript console shows this:

```<code>Uncaught TypeError: document.registerElement is not a function
    at Object.UI.registerCustomElement (shell.js:formatted:18064)
    at shell.js:formatted:18178
    at shell.js:formatted:18266
devtools_app.js:formatted:2606 Uncaught ReferenceError: SDK is not defined
    at devtools_app.js:formatted:2606
</code>```

The code in question (from shell.js) is this:

```<code>UI.registerCustomElement = function(localName, typeExtension, prototype) {
    return document.registerElement(typeExtension, {
        prototype: Object.create(prototype),
        extends: localName
    });
}
</code>```

What is shell.js and where does it come from? What could be the cause of this problem?

The web page is actually being run in a Qt 5.12.3 web browser, but I'm using Chrome (remotely) for the Developer Tools.

I also upgraded Angular 7.x to Angular 8 at the same time, but no longer believe this is related.

My Chrome is currently version 80.0.3987.116 (Official Build) (64-bit).

UPDATE
I just tried downloading an older release of Chromium. (I tried Version 77.0.3823.0 since this dates back to mid-2019.) And debugging there WORKS.

答:
Google removed WebComponents V0 from Chrome, but GUI for remote debug uses them.
So when you try to launch remote debug on device with old Chrome on board -  debugger crashes with

```<code>Uncaught TypeError: document.registerElement is not a function
</code>```

I found two way to fight this

Downgrade Chrome and there is no easy way to do it (if you use mac here link for you https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html?prefix=Mac/668249/)

Upgrade chrome on target device and in most cases it is impossible (

Body:
Recently after some software updates (automated Windows 10 update, and possibly a Chrome auto-update) the developer tools for remote debugging from Qt's QWebEngine stopped working. The JavaScript console shows this:

Uncaught TypeError: document.registerElement is not a function
    at Object.UI.registerCustomElement (shell.js:formatted:18064)
    at shell.js:formatted:18178
    at shell.js:formatted:18266
devtools_app.js:formatted:2606 Uncaught ReferenceError: SDK is not defined
    at devtools_app.js:formatted:2606

The code in question (from shell.js) is this:

UI.registerCustomElement = function(localName, typeExtension, prototype) {
    return document.registerElement(typeExtension, {
        prototype: Object.create(prototype),
        extends: localName
    });
}

What is shell.js and where does it come from? What could be the cause of this problem?

The web page is actually being run in a Qt 5.12.3 web browser, but I'm using Chrome (remotely) for the Developer Tools.

I also upgraded Angular 7.x to Angular 8 at the same time, but no longer believe this is related.

My Chrome is currently version 80.0.3987.116 (Official Build) (64-bit).

UPDATE
I just tried downloading an older release of Chromium. (I tried Version 77.0.3823.0 since this dates back to mid-2019.) And debugging there WORKS.

Body:
Google removed WebComponents V0 from Chrome, but GUI for remote debug uses them.
So when you try to launch remote debug on device with old Chrome on board -  debugger crashes with

Uncaught TypeError: document.registerElement is not a function

I found two way to fight this

Downgrade Chrome and there is no easy way to do it (if you use mac here link for you https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html?prefix=Mac/668249/)

Upgrade chrome on target device and in most cases it is impossible (


问:
How do I compare a raw time in Java to now?

Possible Duplicate:

  How do I compare a raw time in Java?

For example suppose I have

```<code>String endTime = "16:30:45";
</code>```

How would I determine whether right now is before this time?  I have tried

```<code>SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss")
Date date = sdf.parse(endTime);
</code>```

However date has year 1970 and so the comparisons fail

答:
You can always do the inverse:</p>

```<code>"16:30:45".compareTo(new SimpleDateFormat("HH:mm:ss").format(new Date()))
</code>```

Body:
Possible Duplicate:

  How do I compare a raw time in Java?

For example suppose I have

String endTime = "16:30:45";

How would I determine whether right now is before this time?  I have tried

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss")
Date date = sdf.parse(endTime);

However date has year 1970 and so the comparisons fail

Body:
You can always do the inverse:

"16:30:45".compareTo(new SimpleDateFormat("HH:mm:ss").format(new Date()))


问:
MySql posts between specific date
I want to select statuses where their post date passed 6 hours but now 12 hours.
Exampe:

Now 20.02.2020 23:00:00

Post date 20.02.2020 16:00:00

(Now - Post date) > 6

(Now - Post date) < 12

Basically, what I want is:

6<(now-post_date)<12

I am trying this code below,

```<code>SELECT
    *
FROM
    offers INNER JOIN status ON offers.offer_id=status.offer_id
WHERE status.status_id IN(SELECT
                               MAX(status.status_id)
                          FROM status
                          GROUP BY status.offer_id)
    AND status.status_code IN(1, 2)
    AND 6*60*60 < (CURRENT_TIMESTAMP() - offers.offer_datePosted)
    AND 12*60*60 > (CURRENT_TIMESTAMP() - offers.offer_datePosted)
</code>```

What is my mistake here?
Thanks in advance!

答:
Use this to check the time.

```<code>AND NOW() - INTERVAL 6 HOUR < offers.offer_datePosted
AND NOW() + INTERVAL 12 HOUR > offers.offer_datePosted
</code>```

This will add the hours corretly

Title: MySql posts between specific date

Body:
I want to select statuses where their post date passed 6 hours but now 12 hours.
Exampe:

Now 20.02.2020 23:00:00

Post date 20.02.2020 16:00:00

(Now - Post date) > 6

(Now - Post date) < 12

Basically, what I want is:

6<(now-post_date)<12

I am trying this code below,

SELECT
    *
FROM
    offers INNER JOIN status ON offers.offer_id=status.offer_id
WHERE status.status_id IN(SELECT
                               MAX(status.status_id)
                          FROM status
                          GROUP BY status.offer_id)
    AND status.status_code IN(1, 2)
    AND 6*60*60 < (CURRENT_TIMESTAMP() - offers.offer_datePosted)
    AND 12*60*60 > (CURRENT_TIMESTAMP() - offers.offer_datePosted)

What is my mistake here?
Thanks in advance!

Body:
Use this to check the time.

AND NOW() - INTERVAL 6 HOUR < offers.offer_datePosted
AND NOW() + INTERVAL 12 HOUR > offers.offer_datePosted

This will add the hours corretly


问:
How to set a Hibernate interceptor for an EntityManagerFactory
I'm using JPA, but I need to unwrap my EntityManagerFactory, so I can add an interceptor to the Session. Afterward I want to wrap the Session back to a EntityManager.

"Why not just use Session instead of EntityManager?" We still want to reduce the impact of a possible technology migration

For what do I want to use Interceptor:

I can resume the problem in the following way: The project works running queries on a alarms database. Each place has one database with a Alarm Table, but the client wants to have a single database, where we will have to create multiple "Alarm Table", one for each place (ex: Table_Alarm-Place1, Table_Alarm-Place2). That means we would have multiple tables for the same entity, the interceptor has the goal of changing the Table name generate by hibernate in the final SQL

How I pretend to use the interceptor:

```<code>public class SqlInterceptor extends EmptyInterceptor {

    private String tableSufix;

    private static final Logger LOGGER = LoggerFactory.getLogger(SqlInterceptor.class);

    public SqlInterceptor(String tableSufix) {...}

    @Override
    public String onPrepareStatement(String sql) {
        String finalSql;

        //Manipulated SQL (parsed by Hibernate)

        return finalSql;
    }

}
</code>```

The project uses JPA 2.1 and Hibernate 4.3.11.Final

答:
A super easy way to override Hibernate's EmptyInterceptor is to just this in properties file

```<code>spring.jpa.properties.hibernate.session_factory.interceptor=<fully-qualified-interceptor-class-name>
</code>```

Cheers :)

Body:
I'm using JPA, but I need to unwrap my EntityManagerFactory, so I can add an interceptor to the Session. Afterward I want to wrap the Session back to a EntityManager.

"Why not just use Session instead of EntityManager?" We still want to reduce the impact of a possible technology migration

For what do I want to use Interceptor:

I can resume the problem in the following way: The project works running queries on a alarms database. Each place has one database with a Alarm Table, but the client wants to have a single database, where we will have to create multiple "Alarm Table", one for each place (ex: Table_Alarm-Place1, Table_Alarm-Place2). That means we would have multiple tables for the same entity, the interceptor has the goal of changing the Table name generate by hibernate in the final SQL

How I pretend to use the interceptor:

public class SqlInterceptor extends EmptyInterceptor {

    private String tableSufix;

    private static final Logger LOGGER = LoggerFactory.getLogger(SqlInterceptor.class);

    public SqlInterceptor(String tableSufix) {...}

    @Override
    public String onPrepareStatement(String sql) {
        String finalSql;

        //Manipulated SQL (parsed by Hibernate)

        return finalSql;
    }

}

The project uses JPA 2.1 and Hibernate 4.3.11.Final

Body:
A super easy way to override Hibernate's EmptyInterceptor is to just this in properties file

spring.jpa.properties.hibernate.session_factory.interceptor=<fully-qualified-interceptor-class-name>

Cheers :)


问:
Drag and drop list - not working with my data structure (stackblitz included)
I decided to make smaller implementation from my big project. At this moment i trying to rework list for drag&drop functionality. In my project i see names on list but can't drag and drop anything. In stackblitz i can't even show anything on my list. I using this to make drag&drop. There is my stackblitz with smaller implementation.

Edit 1

It will be nice when drag&drop will be combined with material list.

Edit 2

When i remove observable from file element, error disappears, but sadly still not working. Observable is required there.

答:
TS File

```<code>import { Component } from "@angular/core";
import { CdkDragDrop, moveItemInArray } from "@angular/cdk/drag-drop";
import { Observable } from "rxjs";
;
import { transferArrayItem} from '@angular/cdk/drag-drop';

import * as i0 from "@angular/core";
/**
 * @title Drag&Drop sorting
 */
@Component({
  selector: "cdk-drag-drop-sorting-example",
  templateUrl: "cdk-drag-drop-sorting-example.html",
  styleUrls: ["cdk-drag-drop-sorting-example.css"]
})
export class CdkDragDropSortingExample {
  todo = [
    {
      name: "Pictures",
      extension: ""
    },
    {
      name: "Movies",
      extension: ""
    }
  ];
  done = [
    {
      name: "Pictures2",
      extension: ""
    },
    {
      name: "Movies2",
      extension: ""
    }
  ];

  ngOnInit() {}
   drop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
      transferArrayItem(event.previousContainer.data,
                        event.container.data,
                        event.previousIndex,
                        event.currentIndex);
    }
  }
}
</code>```

HTML FILE

```<code><div class="example-container">
  <h2>To do</h2>

  <div
    cdkDropList
    #todoList="cdkDropList"
    [cdkDropListData]="todo"
    [cdkDropListConnectedTo]="[doneList]"
    class="example-list"
    (cdkDropListDropped)="drop($event)">
    <div class="example-box" *ngFor="let item of todo" cdkDrag>{{item.name}}</div>
  </div>
</div>

<div class="example-container">
  <h2>Done</h2>

  <div
    cdkDropList
    #doneList="cdkDropList"
    [cdkDropListData]="done"
    [cdkDropListConnectedTo]="[todoList]"
    class="example-list"
    (cdkDropListDropped)="drop($event)">
    <div class="example-box" *ngFor="let item of done" cdkDrag>{{item.name}}</div>
  </div>
</div>
</code>```

check Stackblizfor answer

Body:
TS File

import { Component } from "@angular/core";
import { CdkDragDrop, moveItemInArray } from "@angular/cdk/drag-drop";
import { Observable } from "rxjs";
;
import { transferArrayItem} from '@angular/cdk/drag-drop';

import * as i0 from "@angular/core";
/**
 * @title Drag&Drop sorting
 */
@Component({
  selector: "cdk-drag-drop-sorting-example",
  templateUrl: "cdk-drag-drop-sorting-example.html",
  styleUrls: ["cdk-drag-drop-sorting-example.css"]
})
export class CdkDragDropSortingExample {
  todo = [
    {
      name: "Pictures",
      extension: ""
    },
    {
      name: "Movies",
      extension: ""
    }
  ];
  done = [
    {
      name: "Pictures2",
      extension: ""
    },
    {
      name: "Movies2",
      extension: ""
    }
  ];

  ngOnInit() {}
   drop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
      transferArrayItem(event.previousContainer.data,
                        event.container.data,
                        event.previousIndex,
                        event.currentIndex);
    }
  }
}

HTML FILE

<div class="example-container">
  <h2>To do</h2>

  <div
    cdkDropList
    #todoList="cdkDropList"
    [cdkDropListData]="todo"
    [cdkDropListConnectedTo]="[doneList]"
    class="example-list"
    (cdkDropListDropped)="drop($event)">
    <div class="example-box" *ngFor="let item of todo" cdkDrag>{{item.name}}</div>
  </div>
</div>

<div class="example-container">
  <h2>Done</h2>

  <div
    cdkDropList
    #doneList="cdkDropList"
    [cdkDropListData]="done"
    [cdkDropListConnectedTo]="[todoList]"
    class="example-list"
    (cdkDropListDropped)="drop($event)">
    <div class="example-box" *ngFor="let item of done" cdkDrag>{{item.name}}</div>
  </div>
</div>

check Stackblizfor answer


问:
How do I refresh my code to make a new answer for the survey?
I've been working on this project where a site gives me 3 numbers portrayed with pictures.I quickly learned that the developers forgot to change the name of the PNG files in the HTML source so I learned to read those using code.

I have already setup a code with selenium and beatifulsoup to make a chrome page with that particular site.Give me time to login.Read the HTML Source in text code, find the numbers and instert them to the specified area and click the continue button.Then loop.

```<code>import time
import re
import numbers
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

driver = webdriver.Chrome(executable_path = "C:/Users/user/Desktop/Personal/PythonScripts/chromedriver.exe")
driver.get('URL I USED')

time.sleep(20)
driver.refresh()

soup = BeautifulSoup(driver.page_source ,"lxml")
all_items = soup.find_all('img')

for item in all_items:
    print('char:', item['src'][-5])

LIST = [item['src'][-5] for item in all_items]

new_list = []
for value in LIST:
    try:
        new_list.append(int(value))
    except ValueError:
        continue

for i in new_list:
    print(i, end="")

try :
 driver.find_element_by_tag_name('input').send_keys(new_list[0],new_list[1],new_list[2])
except :
    print('Fail')

html_source = driver.page_source
print(html_source)

button = driver.find_element_by_xpath('//*[@id="main"]/form/div[3]/input')
button.click()

time.sleep(5)
while True:
        for item in all_items:
            print('char:', item['src'][-5])

        LIST = [item['src'][-5] for item in all_items]

        new_list = []
        for value in LIST:
            try:
                new_list.append(int(value))
            except ValueError:
                continue

        for i in new_list:
           print(i, end="")

        try :
            driver.find_element_by_tag_name('input').send_keys(new_list[0],new_list[1],new_list[2])
        except :
            print('Fail')

        html_source = driver.page_source
        print(html_source)

        new_list.clear()
        button.click()
        time.sleep(10)
        driver.refresh()
</code>```

I am fairly new to python and coding in general so feel free to point out my mistakes even unrelated to the topic.
My issue is the page doesn't necessarily reload after pressing continue and I tried not reloading it but my code "reads" the first survey correctly but fails on the proceeding ones as it fills the blank with the previously used numbers.(only the first one).I added more than necessary amount of sleep time.Removed the driver.refresh() at the end of the loop.None of them worked.

Thanks in advance

答:
i would recommend to you changing the script to end the driver session after the survey is send.
Just start the while loop before starting the driver.

On the other hand, you are using BeutifulSoup only to get the images, you can change it to

```<code>driver.find_elements_by_tag_name ('img')
</code>```

to use selenium in all the script, the find_elements_by_tag_name will return a List of Elements

Body:
I've been working on this project where a site gives me 3 numbers portrayed with pictures.I quickly learned that the developers forgot to change the name of the PNG files in the HTML source so I learned to read those using code.

I have already setup a code with selenium and beatifulsoup to make a chrome page with that particular site.Give me time to login.Read the HTML Source in text code, find the numbers and instert them to the specified area and click the continue button.Then loop.

import time
import re
import numbers
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

driver = webdriver.Chrome(executable_path = "C:/Users/user/Desktop/Personal/PythonScripts/chromedriver.exe")
driver.get('URL I USED')

time.sleep(20)
driver.refresh()

soup = BeautifulSoup(driver.page_source ,"lxml")
all_items = soup.find_all('img')

for item in all_items:
    print('char:', item['src'][-5])

LIST = [item['src'][-5] for item in all_items]

new_list = []
for value in LIST:
    try:
        new_list.append(int(value))
    except ValueError:
        continue

for i in new_list:
    print(i, end="")

try :
 driver.find_element_by_tag_name('input').send_keys(new_list[0],new_list[1],new_list[2])
except :
    print('Fail')

html_source = driver.page_source
print(html_source)

button = driver.find_element_by_xpath('//*[@id="main"]/form/div[3]/input')
button.click()

time.sleep(5)
while True:
        for item in all_items:
            print('char:', item['src'][-5])

        LIST = [item['src'][-5] for item in all_items]

        new_list = []
        for value in LIST:
            try:
                new_list.append(int(value))
            except ValueError:
                continue

        for i in new_list:
           print(i, end="")

        try :
            driver.find_element_by_tag_name('input').send_keys(new_list[0],new_list[1],new_list[2])
        except :
            print('Fail')

        html_source = driver.page_source
        print(html_source)

        new_list.clear()
        button.click()
        time.sleep(10)
        driver.refresh()

I am fairly new to python and coding in general so feel free to point out my mistakes even unrelated to the topic.
My issue is the page doesn't necessarily reload after pressing continue and I tried not reloading it but my code "reads" the first survey correctly but fails on the proceeding ones as it fills the blank with the previously used numbers.(only the first one).I added more than necessary amount of sleep time.Removed the driver.refresh() at the end of the loop.None of them worked.

Thanks in advance

Body:
i would recommend to you changing the script to end the driver session after the survey is send.
Just start the while loop before starting the driver.

On the other hand, you are using BeutifulSoup only to get the images, you can change it to

driver.find_elements_by_tag_name ('img')

to use selenium in all the script, the find_elements_by_tag_name will return a List of Elements


问:
Solr term search not searching all values from multifields value
I have solr field

```<code><field name="AllTitles" type="text_general" indexed="true" stored="false" multiValued="true"/>

<fieldType name="text_general" class="solr.TextField" positionIncrementGap="100">
  <analyzer type="index">
    <charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" />
    <!-- in this example, we will only use synonyms at query time -->
    <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="false"/>
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
  <analyzer type="query">
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" />
    <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
</fieldType>
</code>```

Example of Value for AllTitles entered is

```<code>AllTitles: [ "Anything", "wuhan coronavirus", "anything" ]
AllTitles: [ "wuhan coronavirus", "anything", "anything" ]
</code>```

It searches from first index but if any matching term on index other than 1st then it's not searching

For example when I search

```<code>q="wuhan coronavirus"
</code>```

I get 2 results. When I search using field name "AllTitles"

```<code>q=AllTitles:"wuhan coronavirus"
</code>```

I get 7 results correctly.

Can anybody help me identifying the issue?

答:
First, in your SolrConfig.xml check what field has been defined in the "df". In the below example it is "text".

```<code><requestHandler name="/select" class="solr.SearchHandler">
   <lst name="defaults">
     <str name="echoParams">explicit</str>
     <int name="rows">10</int>
     <str name="df">text</str>
  </requestHandler>
</code>```

Second, in the schema.xml or managed-schema, whichever you are using, make sure you have copied "AllTitles" to "text". Like this,

```<code><copyField source="AllTitles" dest="text"/>
</code>```

You might as well test it by adding "AllTitles" to your "df" parameter when you query, before doing all these, like raghu777 has mentioned.

Body:
I have solr field

<field name="AllTitles" type="text_general" indexed="true" stored="false" multiValued="true"/>

<fieldType name="text_general" class="solr.TextField" positionIncrementGap="100">
  <analyzer type="index">
    <charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" />

    <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="false"/>
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
  <analyzer type="query">
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" />
    <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
</fieldType>

Example of Value for AllTitles entered is

AllTitles: [ "Anything", "wuhan coronavirus", "anything" ]
AllTitles: [ "wuhan coronavirus", "anything", "anything" ]

It searches from first index but if any matching term on index other than 1st then it's not searching

For example when I search

q="wuhan coronavirus"

I get 2 results. When I search using field name "AllTitles"

q=AllTitles:"wuhan coronavirus"

I get 7 results correctly.

Can anybody help me identifying the issue?

Body:
First, in your SolrConfig.xml check what field has been defined in the "df". In the below example it is "text".

<requestHandler name="/select" class="solr.SearchHandler">
   <lst name="defaults">
     <str name="echoParams">explicit</str>
     <int name="rows">10</int>
     <str name="df">text</str>
  </requestHandler>

Second, in the schema.xml or managed-schema, whichever you are using, make sure you have copied "AllTitles" to "text". Like this,

<copyField source="AllTitles" dest="text"/>

You might as well test it by adding "AllTitles" to your "df" parameter when you query, before doing all these, like raghu777 has mentioned.


问:
Why is it in SwiftUI, when presenting modal view with .sheet, init() is called twice
I am producing the situation on WatchOS with the following code

```<code>struct Modal : View {
    @Binding var showingModal : Bool

    init(showingModal : Binding<Bool>){
        self._showingModal = showingModal
        print("init modal")
    }

    var body: some View {
        Button(action: {
            self.showingModal.toggle()
        }, label: {
            Text("TTTT")
        })
    }
}

struct ContentView: View {
    @State var showingModal = false
    var body: some View {
        Button(action: {
            self.showingModal.toggle()
        }, label: {
            Text("AAAA")
        }).sheet(isPresented: $showingModal, content: {Modal(showingModal: self.$showingModal)})
    }
}
</code>```

Every time I press the button in the master view to summon the modal with .sheet, Two instances of the modal view are created.

Could someone explain this phenomenon?

答: Comment out/remove the init() method from Modal with everything else the same. You should be able to solve the issue of two instances of Modal being created, its because you are explicitly initializing the binding (showingModal) in the init() of Modal. Hope this makes sense.</p>

Body:
I am producing the situation on WatchOS with the following code

struct Modal : View {
    @Binding var showingModal : Bool

    init(showingModal : Binding<Bool>){
        self._showingModal = showingModal
        print("init modal")
    }

    var body: some View {
        Button(action: {
            self.showingModal.toggle()
        }, label: {
            Text("TTTT")
        })
    }
}

struct ContentView: View {
    @State var showingModal = false
    var body: some View {
        Button(action: {
            self.showingModal.toggle()
        }, label: {
            Text("AAAA")
        }).sheet(isPresented: $showingModal, content: {Modal(showingModal: self.$showingModal)})
    }
}

Every time I press the button in the master view to summon the modal with .sheet, Two instances of the modal view are created.

Could someone explain this phenomenon?


问:
Why is promise.finally in my Vue project not working in Edge?
I'm having tremendous trouble getting my polyfills to work in Edge. I've tried to follow the documentation with various attempts all not working. It seems to be promise.finally specifically that isn't working. This happens in a vuex module so I tried adding vuex to transpileDependencies in vue.config but with no luck.

My babel.config.js:

```<code>module.exports = {
  presets: [['@vue/cli-plugin-babel/preset', {
    useBuiltIns: 'entry',
  }]],
};
</code>```

In my main.js I have the following two imports in the very top:

```<code>import 'core-js/stable';
import 'regenerator-runtime/runtime';
</code>```

My vue.config.js

```<code>// eslint-disable-next-line import/no-extraneous-dependencies
const webpack = require('webpack');

const isProd = process.env.NODE_ENV === 'production';

module.exports = {
  configureWebpack: {
    // Set up all the aliases we use in our app.
    plugins: [
      new webpack.optimize.LimitChunkCountPlugin({
        maxChunks: 6,
      }),
    ],
  },
  css: {
    // Enable CSS source maps.
    sourceMap: !isProd,
  },
  transpileDependencies: ['vuex'],
};
</code>```

Note as mentioned above I have tried both with and without the transpileDepedencies. It says here vue/babel-preset-app that es7.promise.finally is included as a default polyfill

Versions:

Microsoft Edge: 44.18

Microsoft EdgeHTML 18.18362

@vue/cli-plugin-babel": "^4.1.2"

"core-js": "^3.6.4"

"regenerator-runtime": "^0.13.3"

Update 13/02

So I tried to type Promise.prototype on my site in edge and it does appear it is polyfilled:

So currently I'm investigating if some part of my chain (axios/vue axios) does not return a promise. Since it is working in chrome I'm suspecting that a part of the chain is not being polyfilled correctly?

This is my entire chain:

```<code>/* VUEX MODULE ACTION */
[a.ALL_CUSTOMERS](context) {
    context.commit(m.SET_CUSTOMER_LOADING, true);
    CustomerService.getAll()
      .then(({ data }) => {
        context.commit(m.SET_CUSTOMERS, data);
      })
      .finally(() => context.commit(m.SET_CUSTOMER_LOADING, false));
  },

/* CUSTOMER SERVICE */
import ApiService from '@/common/api.service';
const CustomerService = {
  getAll() {
    const resource = 'customers/';
    return ApiService.get(resource);
  },
...
}

/* API SERVICE */
import Vue from 'vue';
import axios from 'axios';
import VueAxios from 'vue-axios';

const ApiService = {
  init() {
    Vue.use(VueAxios, axios);
    let baseUrl = process.env.VUE_APP_APIURL;
    Vue.axios.defaults.baseURL = baseUrl;
  },

  setHeader() {
    Vue.axios.defaults.headers.common.Authorization = `Bearer ${getToken()}`;
  },

  get(resource) {
    this.setHeader();
    return Vue.axios.get(`${resource}`);
  },
  ...
}
</code>```

答:
Try adding a .browserslistrc file to your projects root with the following content:

```<code>> 1%
last 2 versions
</code>```

See https://github.com/browserslist/browserslist#best-practices information on last versions configuration.

If this does not resolve missing poly-fill, try disabling the plugin you are using that limits the number of chunks in order to ensure that this is not causing any poly-fills to be omitted.

```<code>plugins: [
  new webpack.optimize.LimitChunkCountPlugin({
    maxChunks: 6,
  }),
],
</code>```

Body:
I'm having tremendous trouble getting my polyfills to work in Edge. I've tried to follow the documentation with various attempts all not working. It seems to be promise.finally specifically that isn't working. This happens in a vuex module so I tried adding vuex to transpileDependencies in vue.config but with no luck.

My babel.config.js:

module.exports = {
  presets: [['@vue/cli-plugin-babel/preset', {
    useBuiltIns: 'entry',
  }]],
};

In my main.js I have the following two imports in the very top:

import 'core-js/stable';
import 'regenerator-runtime/runtime';

My vue.config.js

// eslint-disable-next-line import/no-extraneous-dependencies
const webpack = require('webpack');

const isProd = process.env.NODE_ENV === 'production';

module.exports = {
  configureWebpack: {
    // Set up all the aliases we use in our app.
    plugins: [
      new webpack.optimize.LimitChunkCountPlugin({
        maxChunks: 6,
      }),
    ],
  },
  css: {
    // Enable CSS source maps.
    sourceMap: !isProd,
  },
  transpileDependencies: ['vuex'],
};

Note as mentioned above I have tried both with and without the transpileDepedencies. It says here vue/babel-preset-app that es7.promise.finally is included as a default polyfill

Versions:

Microsoft Edge: 44.18

Microsoft EdgeHTML 18.18362

@vue/cli-plugin-babel": "^4.1.2"

"core-js": "^3.6.4"

"regenerator-runtime": "^0.13.3"

Update 13/02

So I tried to type Promise.prototype on my site in edge and it does appear it is polyfilled:

So currently I'm investigating if some part of my chain (axios/vue axios) does not return a promise. Since it is working in chrome I'm suspecting that a part of the chain is not being polyfilled correctly?

This is my entire chain:

/* VUEX MODULE ACTION */
[a.ALL_CUSTOMERS](context) {
    context.commit(m.SET_CUSTOMER_LOADING, true);
    CustomerService.getAll()
      .then(({ data }) => {
        context.commit(m.SET_CUSTOMERS, data);
      })
      .finally(() => context.commit(m.SET_CUSTOMER_LOADING, false));
  },

/* CUSTOMER SERVICE */
import ApiService from '@/common/api.service';
const CustomerService = {
  getAll() {
    const resource = 'customers/';
    return ApiService.get(resource);
  },
...
}

/* API SERVICE */
import Vue from 'vue';
import axios from 'axios';
import VueAxios from 'vue-axios';

const ApiService = {
  init() {
    Vue.use(VueAxios, axios);
    let baseUrl = process.env.VUE_APP_APIURL;
    Vue.axios.defaults.baseURL = baseUrl;
  },

  setHeader() {
    Vue.axios.defaults.headers.common.Authorization = `Bearer ${getToken()}`;
  },

  get(resource) {
    this.setHeader();
    return Vue.axios.get(`${resource}`);
  },
  ...
}

Body:
Try adding a .browserslistrc file to your projects root with the following content:

> 1%
last 2 versions

See https://github.com/browserslist/browserslist#best-practices information on last versions configuration.

If this does not resolve missing poly-fill, try disabling the plugin you are using that limits the number of chunks in order to ensure that this is not causing any poly-fills to be omitted.

plugins: [
  new webpack.optimize.LimitChunkCountPlugin({
    maxChunks: 6,
  }),
],


问:
Extra space on top and bottom of android Chip material component
I'm using Chip view in my layout

Since upgraded material design component from 1.0.0 to 1.1.0, there is an extra space at the top and bottom of view

I couldn't find any document about how to remove these spaces

In material 1.0.0

In material 1.1.0

```<code><com.google.android.material.chip.Chip
    style="@style/Widget.MaterialComponents.Chip.Action"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    android:text="Groceries"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
</code>```

答:
It is related to the chipMinTouchTargetSize attribute.

You can find in the Chip source code:

```<code>if (shouldEnsureMinTouchTargetSize()) {
  setMinHeight(minTouchTargetSize);
}
</code>```

You can change the chipMinTouchTargetSize in the layout or in the style:

```<code>    <com.google.android.material.chip.Chip
        app:chipMinTouchTargetSize="32dp"
        ../>
</code>```

or you can set app:ensureMinTouchTargetSize="false".

Pay attention to change this value since it changes the minimum touch target size.

Body:
I'm using Chip view in my layout

Since upgraded material design component from 1.0.0 to 1.1.0, there is an extra space at the top and bottom of view

I couldn't find any document about how to remove these spaces

In material 1.0.0

In material 1.1.0

<com.google.android.material.chip.Chip
    style="@style/Widget.MaterialComponents.Chip.Action"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    android:text="Groceries"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

Body:
It is related to the chipMinTouchTargetSize attribute.

You can find in the Chip source code:

if (shouldEnsureMinTouchTargetSize()) {
  setMinHeight(minTouchTargetSize);
}

You can change the chipMinTouchTargetSize in the layout or in the style:

    <com.google.android.material.chip.Chip
        app:chipMinTouchTargetSize="32dp"
        ../>

or you can set app:ensureMinTouchTargetSize="false".

Pay attention to change this value since it changes the minimum touch target size.


问:
Null Calculation With SQL Select Statement
I have Following Table

```<code>Input           Output
---------------------------------
12.22
                2.22
</code>```

If I pass Following Sql Statement:

Select Input,Output,Balance=sum(Input - Output) from Stock group by input,output

So The Output is:

```<code>Input            Output       Balance
--------------------------------------
12.22            NULL         NULL
NULL             2.22         NULL
</code>```

If I wants The Output Like Below:

```<code>Input            Output       Balance
--------------------------------------
12.22                         12.22
                 2.22         10.00
</code>```

Than What is SQL Transact Statement?

My Table Structure is as Below:

```<code>companyID   int
transID     int    -- Primary Key (Auto Increment)
Date        datetime
particulars varchar
input       decimal
output      decimal
</code>```

Note:- I have applied here Group By function on input and Output columns which doesn't make diference as there is transID columns which is autoincrement hence it should be display all the rows of the table.

答:
Using arcain sample table you can use following query that take advantage of window functioning to get the job done.

```<code>--arcain sample table

declare @stock table (
      transId int not null identity(1,1),
      [date] date not null, -- use datetime if not using SQL Server 2008
      input decimal(7,2) null,
      [output] decimal(7,2) null
    );

insert into @stock values
('1/23/2011', 12.22, null),
('1/23/2011', null, 2.22),
('1/24/2011', 16, null),
('1/24/2011', 3.76, null),
('1/24/2011', null, 5.50);
</code>```

Query

```<code>SELECT *,
        SUM( COALESCE(input,0) - COALESCE(output,0) )
            OVER (PARTITION BY date ORDER BY date,transId ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM @stock
</code>```

Body:
I have Following Table

Input           Output
---------------------------------
12.22
                2.22

If I pass Following Sql Statement:

Select Input,Output,Balance=sum(Input - Output) from Stock group by input,output

So The Output is:

Input            Output       Balance
--------------------------------------
12.22            NULL         NULL
NULL             2.22         NULL

If I wants The Output Like Below:

Input            Output       Balance
--------------------------------------
12.22                         12.22
                 2.22         10.00

Than What is SQL Transact Statement?

My Table Structure is as Below:

companyID   int
transID     int    -- Primary Key (Auto Increment)
Date        datetime
particulars varchar
input       decimal
output      decimal

Note:- I have applied here Group By function on input and Output columns which doesn't make diference as there is transID columns which is autoincrement hence it should be display all the rows of the table.

Body:
Using arcain sample table you can use following query that take advantage of window functioning to get the job done.

--arcain sample table

declare @stock table (
      transId int not null identity(1,1),
      [date] date not null, -- use datetime if not using SQL Server 2008
      input decimal(7,2) null,
      [output] decimal(7,2) null
    );

insert into @stock values
('1/23/2011', 12.22, null),
('1/23/2011', null, 2.22),
('1/24/2011', 16, null),
('1/24/2011', 3.76, null),
('1/24/2011', null, 5.50);

Query

SELECT *,
        SUM( COALESCE(input,0) - COALESCE(output,0) )
            OVER (PARTITION BY date ORDER BY date,transId ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM @stock