问:
Shared element back transition not working with recyclerview and cardviews in fragments
I'm trying to create a transition between a recycler view with cardviews fragment to a fragment that only contains 1 card. The problem is that the back transition is not working, while the enter transition is. If I remove setReorderingAllowed(true); then the back transition is working, but the enter transition stops working.
This is what I have.

Fragment with recyclerview with cardviews

```<code>public class OrdersFragment extends Fragment implements OrderAdapter.OnOrderListener {

    private OrderAdapter mAdapter;

    private TextView bonnenTextView;

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

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_bonnen, container, false);
        bonnenTextView = view.findViewById(R.id.bonnen_text_view);
        RecyclerView orderRecyclerView = view.findViewById(R.id.order_recycler_view);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        orderRecyclerView.setLayoutManager(layoutManager);
        if (mAdapter == null) {
            mAdapter = new OrderAdapter(this);
            fetchOrders();
        }
        orderRecyclerView.setAdapter(mAdapter);
        return view;
    }

    private void fetchOrders() {
        new OrderFetcher().fetch(new Callback() {
            @Override
            public void onComplete(Result result) {
                if (result instanceof Result.Success) {
                    mAdapter.setOrders((Order[]) ((Result.Success<?>)result).data);
                    mAdapter.notifyDataSetChanged();
                } else {
                    Toast.makeText(getContext(), "Could not load orders", Toast.LENGTH_SHORT).show();
                }
                startPostponedEnterTransition();
            }
        });
    }

    @Override
    public void onOrderClick(int position, View view, Order order) {
        Log.i("OrderClick", "Transition name " + view.getTransitionName());

        View carrierTextView = view.findViewById(R.id.carrier_text_view);
        View numberTextView = view.findViewById(R.id.id_text_view);
        View pickerTextView = view.findViewById(R.id.picker_text_view);
        View locationTextView = view.findViewById(R.id.location_text_view);

        FragmentTransaction transaction = getParentFragmentManager().beginTransaction();
        transaction.addSharedElement(view, view.getTransitionName());
        transaction.addSharedElement(carrierTextView, carrierTextView.getTransitionName());
        transaction.addSharedElement(numberTextView, numberTextView.getTransitionName());
        transaction.addSharedElement(pickerTextView, pickerTextView.getTransitionName());
        transaction.addSharedElement(locationTextView, locationTextView.getTransitionName());
        transaction.addSharedElement(bonnenTextView, bonnenTextView.getTransitionName());
        transaction.replace(R.id.nav_host_fragment, BonFragment.newInstance(view.getTransitionName(), order));
        transaction.addToBackStack(null);
        transaction.setReorderingAllowed(true);
        transaction.commit();
    }
}
</code>```

xml that goes with fragment above

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

    <TextView
        android:id="@+id/bonnen_text_view"
        android:transitionName="bonnen_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:text="@string/orders"
        android:textColor="@color/secondary"
        android:textSize="40sp"
        android:textStyle="bold"
        android:typeface="normal" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/order_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="20dp"/>
</LinearLayout>
</code>```

Fragment with single cardview

```<code>public static BonFragment newInstance(String cardTransitionName, Order order) {
        BonFragment bonFragment = new BonFragment();

        Bundle args = new Bundle();
        args.putParcelable("orderParcel", order);
        args.putString("cardTransitionName", cardTransitionName);
        bonFragment.setArguments(args);

        return bonFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View root = inflater.inflate(R.layout.fragment_bon, container, false);

        CardView orderCard = root.findViewById(R.id.order_card);
        TextView carrierTextView = root.findViewById(R.id.carrier_text_view);
        TextView numberTextView = root.findViewById(R.id.id_text_view);
        TextView pickerTextView = root.findViewById(R.id.picker_text_view);
        TextView locationTextView = root.findViewById(R.id.location_text_view);

        if (getArguments() != null && getArguments().getParcelable("orderParcel") != null) {
            Order order = getArguments().getParcelable("orderParcel");
            orderCard.setTransitionName(getArguments().getString("cardTransitionName"));
            if (order != null) {
                carrierTextView.setTransitionName("carrier" + order.getIndex());
                carrierTextView.setText(order.getCarrier());
                numberTextView.setTransitionName("number" + order.getIndex());
                numberTextView.setText(String.valueOf(order.getNumber()));
                pickerTextView.setTransitionName("picker" + order.getIndex());
                pickerTextView.setText(order.getPicker());
                locationTextView.setTransitionName("location" + order.getIndex());
                locationTextView.setText(order.getPosition());

                carrierTextView.setText("Lorem Ipsum");
                numberTextView.setText("Dolor sit amet");
                pickerTextView.setText("consectetur adipiscing elit");
                locationTextView.setText("Mauris semper");

            }
        }

        orderCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getParentFragmentManager().popBackStack();
            }
        });

        Transition transition = TransitionInflater.from(getContext()).inflateTransition(R.transition.card_transition);
        setSharedElementEnterTransition(transition);
        setSharedElementReturnTransition(transition);
        return root;
    }
</code>```

xml that goes with fragment above

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

    <TextView
        android:transitionName="bonnen_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:text="@string/orders"
        android:textColor="@color/secondary"
        android:textSize="40sp"
        android:textStyle="bold"
        android:typeface="normal" />

    <androidx.cardview.widget.CardView
        android:id="@+id/order_card"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:cardBackgroundColor="@color/primaryLight"
        android:foreground="?android:attr/selectableItemBackground"
        android:clickable="true"
        android:layout_margin="25dp">

        <LinearLayout
            android:transitionName="order_card_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_margin="10dp">
            <TextView
                android:id="@+id/carrier_text_view"
                android:transitionName="carrier_text_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="@color/secondary"
                android:textSize="20sp"
                android:textStyle="bold"/>
            <TextView
                android:id="@+id/id_text_view"
                android:transitionName="id_text_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="@color/secondary" />
            <TextView
                android:id="@+id/picker_text_view"
                android:transitionName="picker_text_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="@color/secondary" />
            <TextView
                android:id="@+id/location_text_view"
                android:transitionName="location_text_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="@color/secondary" />
        </LinearLayout>
    </androidx.cardview.widget.CardView>
</LinearLayout>
</code>```

This is what it looks like with setReorderingAllowed(true);

This is what it looks like without setReorderingAllowed(true);

EDIT
After applying the answer given by ianhanniballake I got it working.
Here is what I did for future reference.
The only changes I made is in the OrdersFragment class.
I removed the override of the onCreate() method.
I removed the startPostponedEnterTransition(); from my fetchOrders() method and I added

```<code>@Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        postponeEnterTransition();
        final ViewGroup parentView = (ViewGroup) view.getParent();
        parentView.getViewTreeObserver()
                .addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                    @Override
                    public boolean onPreDraw() {
                        parentView.getViewTreeObserver().removeOnPreDrawListener(this);
                        startPostponedEnterTransition();
                        return true;
                    }
                });
        super.onViewCreated(view, savedInstanceState);
    }
</code>```

That's it

答:
In Kotlin you need to start the transition in doOnPreDraw callback of the recyclerView like below:

```<code>recyclerView.doOnPreDraw {
    startPostponedEnterTransition()
}
</code>```

Body:
I'm trying to create a transition between a recycler view with cardviews fragment to a fragment that only contains 1 card. The problem is that the back transition is not working, while the enter transition is. If I remove setReorderingAllowed(true); then the back transition is working, but the enter transition stops working.
This is what I have.

Fragment with recyclerview with cardviews

public class OrdersFragment extends Fragment implements OrderAdapter.OnOrderListener {

    private OrderAdapter mAdapter;

    private TextView bonnenTextView;

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

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_bonnen, container, false);
        bonnenTextView = view.findViewById(R.id.bonnen_text_view);
        RecyclerView orderRecyclerView = view.findViewById(R.id.order_recycler_view);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        orderRecyclerView.setLayoutManager(layoutManager);
        if (mAdapter == null) {
            mAdapter = new OrderAdapter(this);
            fetchOrders();
        }
        orderRecyclerView.setAdapter(mAdapter);
        return view;
    }

    private void fetchOrders() {
        new OrderFetcher().fetch(new Callback() {
            @Override
            public void onComplete(Result result) {
                if (result instanceof Result.Success) {
                    mAdapter.setOrders((Order[]) ((Result.Success<?>)result).data);
                    mAdapter.notifyDataSetChanged();
                } else {
                    Toast.makeText(getContext(), "Could not load orders", Toast.LENGTH_SHORT).show();
                }
                startPostponedEnterTransition();
            }
        });
    }

    @Override
    public void onOrderClick(int position, View view, Order order) {
        Log.i("OrderClick", "Transition name " + view.getTransitionName());

        View carrierTextView = view.findViewById(R.id.carrier_text_view);
        View numberTextView = view.findViewById(R.id.id_text_view);
        View pickerTextView = view.findViewById(R.id.picker_text_view);
        View locationTextView = view.findViewById(R.id.location_text_view);

        FragmentTransaction transaction = getParentFragmentManager().beginTransaction();
        transaction.addSharedElement(view, view.getTransitionName());
        transaction.addSharedElement(carrierTextView, carrierTextView.getTransitionName());
        transaction.addSharedElement(numberTextView, numberTextView.getTransitionName());
        transaction.addSharedElement(pickerTextView, pickerTextView.getTransitionName());
        transaction.addSharedElement(locationTextView, locationTextView.getTransitionName());
        transaction.addSharedElement(bonnenTextView, bonnenTextView.getTransitionName());
        transaction.replace(R.id.nav_host_fragment, BonFragment.newInstance(view.getTransitionName(), order));
        transaction.addToBackStack(null);
        transaction.setReorderingAllowed(true);
        transaction.commit();
    }
}

xml that goes with fragment above

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

    <TextView
        android:id="@+id/bonnen_text_view"
        android:transitionName="bonnen_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:text="@string/orders"
        android:textColor="@color/secondary"
        android:textSize="40sp"
        android:textStyle="bold"
        android:typeface="normal" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/order_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="20dp"/>
</LinearLayout>

Fragment with single cardview

public static BonFragment newInstance(String cardTransitionName, Order order) {
        BonFragment bonFragment = new BonFragment();

        Bundle args = new Bundle();
        args.putParcelable("orderParcel", order);
        args.putString("cardTransitionName", cardTransitionName);
        bonFragment.setArguments(args);

        return bonFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View root = inflater.inflate(R.layout.fragment_bon, container, false);

        CardView orderCard = root.findViewById(R.id.order_card);
        TextView carrierTextView = root.findViewById(R.id.carrier_text_view);
        TextView numberTextView = root.findViewById(R.id.id_text_view);
        TextView pickerTextView = root.findViewById(R.id.picker_text_view);
        TextView locationTextView = root.findViewById(R.id.location_text_view);

        if (getArguments() != null && getArguments().getParcelable("orderParcel") != null) {
            Order order = getArguments().getParcelable("orderParcel");
            orderCard.setTransitionName(getArguments().getString("cardTransitionName"));
            if (order != null) {
                carrierTextView.setTransitionName("carrier" + order.getIndex());
                carrierTextView.setText(order.getCarrier());
                numberTextView.setTransitionName("number" + order.getIndex());
                numberTextView.setText(String.valueOf(order.getNumber()));
                pickerTextView.setTransitionName("picker" + order.getIndex());
                pickerTextView.setText(order.getPicker());
                locationTextView.setTransitionName("location" + order.getIndex());
                locationTextView.setText(order.getPosition());

                carrierTextView.setText("Lorem Ipsum");
                numberTextView.setText("Dolor sit amet");
                pickerTextView.setText("consectetur adipiscing elit");
                locationTextView.setText("Mauris semper");

            }
        }

        orderCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getParentFragmentManager().popBackStack();
            }
        });

        Transition transition = TransitionInflater.from(getContext()).inflateTransition(R.transition.card_transition);
        setSharedElementEnterTransition(transition);
        setSharedElementReturnTransition(transition);
        return root;
    }

xml that goes with fragment above

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

    <TextView
        android:transitionName="bonnen_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:text="@string/orders"
        android:textColor="@color/secondary"
        android:textSize="40sp"
        android:textStyle="bold"
        android:typeface="normal" />

    <androidx.cardview.widget.CardView
        android:id="@+id/order_card"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:cardBackgroundColor="@color/primaryLight"
        android:foreground="?android:attr/selectableItemBackground"
        android:clickable="true"
        android:layout_margin="25dp">

        <LinearLayout
            android:transitionName="order_card_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_margin="10dp">
            <TextView
                android:id="@+id/carrier_text_view"
                android:transitionName="carrier_text_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="@color/secondary"
                android:textSize="20sp"
                android:textStyle="bold"/>
            <TextView
                android:id="@+id/id_text_view"
                android:transitionName="id_text_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="@color/secondary" />
            <TextView
                android:id="@+id/picker_text_view"
                android:transitionName="picker_text_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="@color/secondary" />
            <TextView
                android:id="@+id/location_text_view"
                android:transitionName="location_text_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="@color/secondary" />
        </LinearLayout>
    </androidx.cardview.widget.CardView>
</LinearLayout>

This is what it looks like with setReorderingAllowed(true);

This is what it looks like without setReorderingAllowed(true);

EDIT
After applying the answer given by ianhanniballake I got it working.
Here is what I did for future reference.
The only changes I made is in the OrdersFragment class.
I removed the override of the onCreate() method.
I removed the startPostponedEnterTransition(); from my fetchOrders() method and I added

@Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        postponeEnterTransition();
        final ViewGroup parentView = (ViewGroup) view.getParent();
        parentView.getViewTreeObserver()
                .addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                    @Override
                    public boolean onPreDraw() {
                        parentView.getViewTreeObserver().removeOnPreDrawListener(this);
                        startPostponedEnterTransition();
                        return true;
                    }
                });
        super.onViewCreated(view, savedInstanceState);
    }

That's it

Body:
In Kotlin you need to start the transition in doOnPreDraw callback of the recyclerView like below:

recyclerView.doOnPreDraw {
    startPostponedEnterTransition()
}


来源: stackexchange

问:
Algorithm to generate bit mask
I was facing this unique problem of generating a bit-mask based on the input parameter. For example,

if param = 2, then the mask will be 0x3  (11b)
if param = 5, then the mask will be 0x1F (1 1111b)

This I implemented using a for-loop in C, something like

```<code>int nMask = 0;
for (int i = 0; i < param; i ++) {

    nMask |= (1 << i);
}
</code>```

I would like to know if there is a better algorithm ~~~

答:
For a 32-bit mask you can use this (use uint64_t for a 64-bit mask):

```<code>#include <assert.h>
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int
main()
{
    size_t n = 8;
    assert(n <= 32);
    uint32_t mask = ~(uint32_t)0 >> (32 - n);

    printf("mask = %08" PRIX32 "\n", mask);
}
</code>```

I know it's an answer to a very old post. But in case some human being actually reads this: I would welcome any feedback.

ContentLicense: CC BY-SA 2.5

Title: Algorithm to generate bit mask

Body:
I was facing this unique problem of generating a bit-mask based on the input parameter. For example,

if param = 2, then the mask will be 0x3  (11b)
if param = 5, then the mask will be 0x1F (1 1111b)

This I implemented using a for-loop in C, something like

int nMask = 0;
for (int i = 0; i < param; i ++) {

    nMask |= (1 << i);
}

I would like to know if there is a better algorithm ~~~

Body:
For a 32-bit mask you can use this (use uint64_t for a 64-bit mask):

#include <assert.h>
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int
main()
{
    size_t n = 8;
    assert(n <= 32);
    uint32_t mask = ~(uint32_t)0 >> (32 - n);

    printf("mask = %08" PRIX32 "\n", mask);
}

I know it's an answer to a very old post. But in case some human being actually reads this: I would welcome any feedback.

ContentLicense: CC BY-SA 4.0


问:
moodle external login
I have writing some changes at index.php and index_form.php to login in my mambo server. I recive from mambo the username and md5 password, etc.., then I test if this user is in moodle database, if not create, then login, else login.

The question is that I can't login a user created from this script in moodle, I also tried to log it mannualy in the default login screen, but the password is always wrong.

The insertion script is inserting the password this way: hash_internal_user_password($_SESSION['PHP_AUTH_PW'])

Then I'm trying to login it this way:
location="https://server/moodle/login/index.php?username='. $_SESSION['PHP_AUTH_USER'] .'&password='. $_SESSION['PHP_AUTH_PW']

What I'm doing wrong?

答:
it's pretty simple

create your login page something like this

```<code>in your "config.php"
</code>```

$CFG->alternateloginurl = ' your url ';

ContentLicense: CC BY-SA 3.0

Title: moodle external login

Body:
it's pretty simple

create your login page something like this

in your "config.php"

$CFG->alternateloginurl = ' your url ';


问:
PHP Getting one or two values from serialised array?
How do I get the groupname value from this array and assign it to a variable??</p>
```<code>a:4:{s:9:"groupname";s:4:"wewe";s:9:"idCompany";N;s:4:"desc";N;s:6:"active";s:1:"Y";}
</code>```

答: @m.eriksson - You solved it for me thank you ... WP had unserialised the array already ! so just using $sname = $formdata["groupname"]; did the trick! Thank you</p>

Body:
How do I get the groupname value from this array and assign it to a variable??

a:4:{s:9:"groupname";s:4:"wewe";s:9:"idCompany";N;s:4:"desc";N;s:6:"active";s:1:"Y";}


问:
Dart: NoSuchMethodError - method not found "h" on null
I am using Flutter Web and when accessing a FutureBuilder I get the NoSuchMethodError - method not found "h" on null
When inspecting the page, i see the following error:

```<code>core_patch.dart:195 Uncaught TypeError: Cannot read properties of undefined (reading 'h')
    at Object.bax (VM5 main.dart.js:25360:16)
    at VM5 main.dart.js:45250:25
    at aWT.a (VM5 main.dart.js:3607:62)
    at aWT.$2 (VM5 main.dart.js:39703:14)
    at aVB.$1 (VM5 main.dart.js:39697:21)
    at a8Y.nJ (VM5 main.dart.js:40765:32)
    at aN8.$0 (VM5 main.dart.js:40122:11)
    at Object.Ds (VM5 main.dart.js:3740:40)
    at ax.tk (VM5 main.dart.js:40054:3)
    at a3F.dm (VM5 main.dart.js:39692:8)
</code>```

It looks like an error from Dart js.
I have update my flutter version to 2.10, but previously I had the same error, except that instead of "h" I got "i" (NoSuchMethodError - method not found "i")

P.S. I get this error ONLY in production(release) build, using debug build everything works just fine.

Code Snipped

```<code>FutureBuilder(
 future: AlgoliaService().getEmployees(searchQuery),
 builder: (BuildContext context,
    AsyncSnapshot<AlgoliaQuerySnapshot> snapshot) {
        if (snapshot.hasError) {
             return Text("Error:  ${snapshot.error}"); // Error happens here
           }

        if (snapshot.connectionState == ConnectionState.waiting) {
            return Center(child: CircularProgressIndicator(),);}
</code>```

答:
You have to add checks like snapshot.hasData, snapshot.hasError in the builder method of FutureBuilder. Because at first the snapshot will always be null on a FutureBuilder and after the future is executed it will return value in snapshot.
Check this page there is a runnable example in here of FutureBuilder</p>

Body:
I am using Flutter Web and when accessing a FutureBuilder I get the NoSuchMethodError - method not found "h" on null
When inspecting the page, i see the following error:

core_patch.dart:195 Uncaught TypeError: Cannot read properties of undefined (reading 'h')
    at Object.bax (VM5 main.dart.js:25360:16)
    at VM5 main.dart.js:45250:25
    at aWT.a (VM5 main.dart.js:3607:62)
    at aWT.$2 (VM5 main.dart.js:39703:14)
    at aVB.$1 (VM5 main.dart.js:39697:21)
    at a8Y.nJ (VM5 main.dart.js:40765:32)
    at aN8.$0 (VM5 main.dart.js:40122:11)
    at Object.Ds (VM5 main.dart.js:3740:40)
    at ax.tk (VM5 main.dart.js:40054:3)
    at a3F.dm (VM5 main.dart.js:39692:8)

It looks like an error from Dart js.
I have update my flutter version to 2.10, but previously I had the same error, except that instead of "h" I got "i" (NoSuchMethodError - method not found "i")

P.S. I get this error ONLY in production(release) build, using debug build everything works just fine.

Code Snipped

FutureBuilder(
 future: AlgoliaService().getEmployees(searchQuery),
 builder: (BuildContext context,
    AsyncSnapshot<AlgoliaQuerySnapshot> snapshot) {
        if (snapshot.hasError) {
             return Text("Error:  ${snapshot.error}"); // Error happens here
           }

        if (snapshot.connectionState == ConnectionState.waiting) {
            return Center(child: CircularProgressIndicator(),);}


问:
How to move volume histogram from bottom to top?
How to move the volume histogram on TradingView from the bottom of the main chart to the top?</p>

答: You cannot do that. You can move it to a new pane above the main chart.


问:
Why its typical to extend functions when behavior could be implemented in the only function
Typical implementation from openzappelin

```<code>    function _setOwner(address newOwner) private {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }

    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _setOwner(newOwner);
    }
</code>```

Why not to implement the same behavior with the only function (including functionality of both)?

```<code>    function _setOwner(address newOwner) private {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
</code>```

答:
The _setOwner(address) private function is also invoked from renounceOwnership(), passing it the zero address value.

So it's a matter of creating reusable private functions, rather than assigning into a set of properties (even though this snippet assigns to just one property) from different places.

Body:
Typical implementation from openzappelin

    function _setOwner(address newOwner) private {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }

    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _setOwner(newOwner);
    }

Why not to implement the same behavior with the only function (including functionality of both)?

    function _setOwner(address newOwner) private {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }


问:
Conditional Running Total with DAX
I have a table with 2 columns: ID and Numbers; and I want to create a new column Result with the running total of the Numbers column but every time the running total surpass 20, the running total should be restarted. Also, if the running total is lower than 20, the result should not be displayed. This have to be done using DAX only.

Thanks in advice.

Note: the Conditional Running Total column exist just to show how the running total works.

ID
Numbers
ConditionalRunningTotal
Result

1
9
9

2
7
16

3
9
25
25

4
8
8

5
9
17

6
9
26
26

7
1
1

8
0
1

9
0
1

10
9
10

11
9
19

12
2
21
21

13
1
1

Eddit: I added couple more rows to test the solution.

答:
I test this only on your sample data, there may be some errors in logic. I split this to several column, for better understanding of what i doing.

```<code>Running = var _curID = 'Table'[ID]
var _run = CALCULATE( sum('Table'[Numbers]), FILTER(all('Table'),  'Table'[ID] <= _curID))
return

ceiling(floor(ceiling(_run , 5) -
ceiling(MOD(_run, 5), 20), 15)
, 20) /20

Rung = var _curID = 'Table'[ID]
var  _previousDate = CALCULATE( max('Table'[Running]), FILTER('Table', 'Table'[ID] < EARLIER('Table'[ID])))
return
_previousDate+0

Final = var _id = [ID]
var _Rung = [Rung]
var _ret =
CALCULATE( sum('Table'[Numbers]), filter(ALL('Table'), [ID] <= _id && _Rung = [Rung]))
return
if (_ret > 20, _ret, 0)
</code>```

Final output:

Title: Conditional Running Total with DAX

Body:
I test this only on your sample data, there may be some errors in logic. I split this to several column, for better understanding of what i doing.

Running = var _curID = 'Table'[ID]
var _run = CALCULATE( sum('Table'[Numbers]), FILTER(all('Table'),  'Table'[ID] <= _curID))
return

ceiling(floor(ceiling(_run , 5) -
ceiling(MOD(_run, 5), 20), 15)
, 20) /20

Rung = var _curID = 'Table'[ID]
var  _previousDate = CALCULATE( max('Table'[Running]), FILTER('Table', 'Table'[ID] < EARLIER('Table'[ID])))
return
_previousDate+0

Final = var _id = [ID]
var _Rung = [Rung]
var _ret =
CALCULATE( sum('Table'[Numbers]), filter(ALL('Table'), [ID] <= _id && _Rung = [Rung]))
return
if (_ret > 20, _ret, 0)

Final output:


问:
How does pixels relate to screen size in CSS
If set the width of a div to 450px. What will happen to the div on a smaller screen say a phone or tablet??</p>

答:
A pixel is 1/96 of a inch. However, a inch in this context does not necessarily correspond to a physical inch.

According to the CSS spec, on a physical media like a printed paper, measures have to be anchored to a physical measure such as an inch or a centimeter, and all other measures would be relative to that.

However on a screen, the measures may be anchored to a pixel, and then the actual size of a pixel should take in account the average distance users are holding the screen from their eyes. A pixel size should match a 1/96 physical inch for a device used to be held on arm-length distance. But it would be smaller for mobile screen which is held close, and bigger for a TV screen which is used on distance.

In these cases, the CSS measures of inch, cm etc. would be relative too, keeping the proportion of 1px = 1/96 inch.


问:
GraphQL Tag dynamic table name in query (apollo)
In my app every customer has a own table for its data. Depending on which customer was selected I want to dynamically build the tablename for the Graphql query.

For example:

```<code>// Query for customer 1
gql`
  query overviewQuery {
    customer_1 {
      aggregate {
        count
      }
  }
}
`
</code>```
```<code>// Query for customer 2
gql`
  query overviewQuery {
    customer_2 {
      aggregate {
        count
      }
  }
}
`
</code>```

I have the customer id in my vuex store and want to insert a variable into the query like in the following pseudocode which is not working.

```<code>const tblUserAggregateName = `customer_${this.$store.state.customer.customerId`

gql`
  query overviewQuery {
    ${this.tblUserAggregateName} {
      aggregate {
        count
      }
  }
`
</code>```

Is there an option how to do this or how can this problem be solved?

It is not an option to hardcode all different customer queries and selected them on runtime.

Thanks!

答:
In the answers it was mentioned, that it is against best practice to dynamically change the table name of GraphQL queries.

As changing the complete database structure for all clients (they each have a separate Database with a own PostgreSQL schema name) is not an option, I found a solution the looks a little bit hacky and definitely not best practice but I thought I might be interesting to share for others with the same problem.

The approach is pretty easy: I write the query as a simple string where I could use variables and convert them later to the gql AST Object with graphql-tag

const query = () => {
  const queryString = `
    {
      ${customerId}_table_name {
        aggregate {
           count
        }
      }
  }`

  return gql`${queryString}`
}

```

Works, but I you have a better solution, I am happy to learn!

Body:
In my app every customer has a own table for its data. Depending on which customer was selected I want to dynamically build the tablename for the Graphql query.

For example:

// Query for customer 1
gql`
  query overviewQuery {
    customer_1 {
      aggregate {
        count
      }
  }
}
`

// Query for customer 2
gql`
  query overviewQuery {
    customer_2 {
      aggregate {
        count
      }
  }
}
`

I have the customer id in my vuex store and want to insert a variable into the query like in the following pseudocode which is not working.

const tblUserAggregateName = `customer_${this.$store.state.customer.customerId`

gql`
  query overviewQuery {
    ${this.tblUserAggregateName} {
      aggregate {
        count
      }
  }
`

Is there an option how to do this or how can this problem be solved?

It is not an option to hardcode all different customer queries and selected them on runtime.

Thanks!

Body:
In the answers it was mentioned, that it is against best practice to dynamically change the table name of GraphQL queries.

As changing the complete database structure for all clients (they each have a separate Database with a own PostgreSQL schema name) is not an option, I found a solution the looks a little bit hacky and definitely not best practice but I thought I might be interesting to share for others with the same problem.

The approach is pretty easy: I write the query as a simple string where I could use variables and convert them later to the gql AST Object with graphql-tag

const query = () => {
  const queryString = `
    {
      ${customerId}_table_name {
        aggregate {
           count
        }
      }
  }`

  return gql`${queryString}`
}

Works, but I you have a better solution, I am happy to learn!


问:
Why does this OpenGL + WIN32 code produce Vertical lines?
To be clear, I've extensively tested this code and found the issue is somewhere with the code written prior to the WGL code. It's precisely in the WIN32 code. Now I think it could partially be caused by calling gluOrth2D but even then, that shouldn't be the primary cause as far I as I understand. I may figure this out myself just by messing with stuff but considering this issue (that occured in a much larger project) has taken up a lot of my time I thought it was worth posting this encase anyone else runs into the same problem. I'm hoping for an explanation as well as fix/correction.</p>
```<code>#include <GL/glew.h>
#include <glfw3.h>
#define GLFW_EXPOSE_NATIVE_WGL
#define GLFW_EXPOSE_NATIVE_WIN32
#include <glfw3native.h>

constexpr int width = 1000, height = 1000;

bool running = true;

LRESULT CALLBACK WIN32_processMessage(HWND hwnd, UINT msg,
    WPARAM wparam, LPARAM lparam)
{
    return DefWindowProcA(hwnd, msg, wparam, lparam);
}

int main()
{
    HINSTANCE hinst = GetModuleHandleA(NULL);

    HICON icon = LoadIcon(hinst, IDI_APPLICATION);

    WNDCLASSA* wc = (WNDCLASSA*)memset(malloc(sizeof(WNDCLASSA)), 0, sizeof(WNDCLASSA));
    if (wc == NULL)
    {
        return -1;
    }

    wc->style = CS_DBLCLKS;
    wc->lpfnWndProc = WIN32_processMessage;
    wc->cbClsExtra = 0;
    wc->cbWndExtra = 0;
    wc->hInstance = hinst;
    wc->hIcon = icon;
    wc->hCursor = LoadCursor(NULL, IDC_ARROW);
    wc->hbrBackground = NULL;
    wc->lpszClassName = "toast_window_class";

    if (!RegisterClassA(wc))
    {
        return 1;
    }

    UINT32 windowX = 100;
    UINT32 windowY = 100;
    UINT32 windowWidth = width;
    UINT32 windowHeight = height;

    UINT32 windowStyle = WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION;
    UINT32 windowExStyle = WS_EX_APPWINDOW;

    windowStyle |= WS_MAXIMIZEBOX;
    windowStyle |= WS_MINIMIZEBOX;
    windowStyle |= WS_THICKFRAME;

    RECT borderRect = { 0,0,0,0 };
    AdjustWindowRectEx(&borderRect, windowStyle, 0, windowExStyle);

    windowX += borderRect.left;
    windowY += borderRect.top;

    windowWidth += borderRect.right - borderRect.left;
    windowWidth += borderRect.bottom - borderRect.top;

    HWND window = CreateWindowExA(windowExStyle, "toast_window_class", (LPCSTR)"test",
        windowStyle, windowX, windowY, windowWidth, windowHeight, 0, 0, hinst, 0);

    if (window == 0)
    {
        return 2;
    }

    bool shouldActivate = true;
    const int showWindowCommandFlags = shouldActivate ? SW_SHOW : SW_SHOWNOACTIVATE;

    ShowWindow(window, showWindowCommandFlags);

    // WGL -----------------------------------------------------------
    HDC device = GetDC(window);

    PIXELFORMATDESCRIPTOR pfd;
    pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 32;
    pfd.cAlphaBits = 0;
    pfd.cAccumBits = 0;
    pfd.cDepthBits = 0;
    pfd.cStencilBits = 0;
    pfd.cAuxBuffers = 0;
    pfd.iLayerType = PFD_MAIN_PLANE;

    SetPixelFormat(device, ChoosePixelFormat(device, &pfd), &pfd);

    HGLRC render = wglCreateContext(device);

    wglMakeCurrent(device, render);

    // GLEW ---------------------------------------------------------

    const GLint res = glewInit();

    if (GLEW_OK != res)
    {
        return 1;
    }

    // setup OpenGL --------------------------------------------------
    gluOrtho2D(0, width, 0, height);

    // main loop -----------------------------------------------------
    while (running)
    {
        glClear(GL_COLOR_BUFFER_BIT);

        // rendering
        glBegin(GL_POINTS);
        for (int x = 10; x < width - 10; ++x)
        {
            for (int y = 10; y < height - 10; ++y)
            {
                glVertex2f(x, y);
            }
        }
        glEnd();

        SwapBuffers(device);
    }

    return 0;
}
</code>```

答:
So I managed to fix it. They key was in lines 49 and 54. I've commented out the parts that were causing the problem in this sample:

```<code>UINT32 windowStyle = WS_OVERLAPPED | WS_SYSMENU; //| WS_CAPTION;
UINT32 windowExStyle = WS_EX_APPWINDOW;

windowStyle |= WS_MAXIMIZEBOX;
windowStyle |= WS_MINIMIZEBOX;
//windowStyle |= WS_THICKFRAME;
</code>```

I'm not super familiar with WIN32 windowing code. This was really my first attempt at it. So I'd welcome any comments if anyone can add some.

Body:
To be clear, I've extensively tested this code and found the issue is somewhere with the code written prior to the WGL code. It's precisely in the WIN32 code. Now I think it could partially be caused by calling gluOrth2D but even then, that shouldn't be the primary cause as far I as I understand. I may figure this out myself just by messing with stuff but considering this issue (that occured in a much larger project) has taken up a lot of my time I thought it was worth posting this encase anyone else runs into the same problem. I'm hoping for an explanation as well as fix/correction.

#include <GL/glew.h>
#include <glfw3.h>
#define GLFW_EXPOSE_NATIVE_WGL
#define GLFW_EXPOSE_NATIVE_WIN32
#include <glfw3native.h>

constexpr int width = 1000, height = 1000;

bool running = true;

LRESULT CALLBACK WIN32_processMessage(HWND hwnd, UINT msg,
    WPARAM wparam, LPARAM lparam)
{
    return DefWindowProcA(hwnd, msg, wparam, lparam);
}

int main()
{
    HINSTANCE hinst = GetModuleHandleA(NULL);

    HICON icon = LoadIcon(hinst, IDI_APPLICATION);

    WNDCLASSA* wc = (WNDCLASSA*)memset(malloc(sizeof(WNDCLASSA)), 0, sizeof(WNDCLASSA));
    if (wc == NULL)
    {
        return -1;
    }

    wc->style = CS_DBLCLKS;
    wc->lpfnWndProc = WIN32_processMessage;
    wc->cbClsExtra = 0;
    wc->cbWndExtra = 0;
    wc->hInstance = hinst;
    wc->hIcon = icon;
    wc->hCursor = LoadCursor(NULL, IDC_ARROW);
    wc->hbrBackground = NULL;
    wc->lpszClassName = "toast_window_class";

    if (!RegisterClassA(wc))
    {
        return 1;
    }

    UINT32 windowX = 100;
    UINT32 windowY = 100;
    UINT32 windowWidth = width;
    UINT32 windowHeight = height;

    UINT32 windowStyle = WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION;
    UINT32 windowExStyle = WS_EX_APPWINDOW;

    windowStyle |= WS_MAXIMIZEBOX;
    windowStyle |= WS_MINIMIZEBOX;
    windowStyle |= WS_THICKFRAME;

    RECT borderRect = { 0,0,0,0 };
    AdjustWindowRectEx(&borderRect, windowStyle, 0, windowExStyle);

    windowX += borderRect.left;
    windowY += borderRect.top;

    windowWidth += borderRect.right - borderRect.left;
    windowWidth += borderRect.bottom - borderRect.top;

    HWND window = CreateWindowExA(windowExStyle, "toast_window_class", (LPCSTR)"test",
        windowStyle, windowX, windowY, windowWidth, windowHeight, 0, 0, hinst, 0);

    if (window == 0)
    {
        return 2;
    }

    bool shouldActivate = true;
    const int showWindowCommandFlags = shouldActivate ? SW_SHOW : SW_SHOWNOACTIVATE;

    ShowWindow(window, showWindowCommandFlags);

    // WGL -----------------------------------------------------------
    HDC device = GetDC(window);

    PIXELFORMATDESCRIPTOR pfd;
    pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 32;
    pfd.cAlphaBits = 0;
    pfd.cAccumBits = 0;
    pfd.cDepthBits = 0;
    pfd.cStencilBits = 0;
    pfd.cAuxBuffers = 0;
    pfd.iLayerType = PFD_MAIN_PLANE;

    SetPixelFormat(device, ChoosePixelFormat(device, &pfd), &pfd);

    HGLRC render = wglCreateContext(device);

    wglMakeCurrent(device, render);

    // GLEW ---------------------------------------------------------

    const GLint res = glewInit();

    if (GLEW_OK != res)
    {
        return 1;
    }

    // setup OpenGL --------------------------------------------------
    gluOrtho2D(0, width, 0, height);

    // main loop -----------------------------------------------------
    while (running)
    {
        glClear(GL_COLOR_BUFFER_BIT);

        // rendering
        glBegin(GL_POINTS);
        for (int x = 10; x < width - 10; ++x)
        {
            for (int y = 10; y < height - 10; ++y)
            {
                glVertex2f(x, y);
            }
        }
        glEnd();

        SwapBuffers(device);
    }

    return 0;
}

Body:
So I managed to fix it. They key was in lines 49 and 54. I've commented out the parts that were causing the problem in this sample:

UINT32 windowStyle = WS_OVERLAPPED | WS_SYSMENU; //| WS_CAPTION;
UINT32 windowExStyle = WS_EX_APPWINDOW;

windowStyle |= WS_MAXIMIZEBOX;
windowStyle |= WS_MINIMIZEBOX;
//windowStyle |= WS_THICKFRAME;

I'm not super familiar with WIN32 windowing code. This was really my first attempt at it. So I'd welcome any comments if anyone can add some.


问:
How to merge a function into another
Sorry for asking a basic thing. new to Python and Django ,
I want to resend email if the OTP from PUT request is incorrect.
I have a function which send email with otp automatically on Register.
But if user PUT incorrect OTP I want to resend that email with new otp, So I want to merge sent_email_otp into verifyEmail function.
So how could I achieve that?

```<code>@receiver(post_save, sender=CustomUser)
def send_email_otp(sender, instance, created, **kwargs):
    if created:
        try:
            subject = "Your email needs to be verified to use site"
            message = f'Hi, Dear {instance.name} use this following OTP to Get verified your email : OTP({instance.otpForEmail})'

            email_from = settings.EMAIL_HOST_USER
            recipient_list = [instance.email]
            send_mail(subject, message, email_from, recipient_list)
            print(f"Email Sent to {instance.email}")
        except Exception as e:
            print(e)
            print("Something Wrong at send_email_otp")

@api_view(['PUT'])
@permission_classes([IsAuthenticated])
def verifyEmail(request, pk):

    user = CustomUser.objects.get(id=pk)

    data = request.data
    otp_to_verify = data['otpForEmail']

    if otp_to_verify == user.otpForEmail:
        user.isEmailVerified = True

        user.save()
        message = {'detail': 'Your email is now verified'}
        return Response(message, status=status.HTTP_400_BAD_REQUEST)
    else:

        message = {
            'detail': 'OTP is not valid and expired, Use New OTP which we have sent you on the email'}
        return Response(message, status=status.HTTP_400_BAD_REQUEST)
</code>```

Edit:
If I simply call the send_email_otp() inside else statement of verifyEmail then this error comes :

```<code>TypeError: send_email_otp() missing 3 required positional arguments: 'sender', 'instance', and 'created'
</code>```

答:
You cant call the signal directly unless you provide it the expected input.

You will need to create another function for sending the otp. and call it in the post_save signal and in the view

def send_otp(name, email, otpForEmail):
    subject = "Your email needs to be verified to use site"
    message = f'Hi, Dear {name} use this following OTP to Get verified your email : OTP({otpForEmail})'

    email_from = settings.EMAIL_HOST_USER
    recipient_list = [email]
    send_mail(subject, message, email_from, recipient_list)
    print(f"Email Sent to {email}")

@receiver(post_save, sender=CustomUser)
def send_email_otp_on_post_save(sender, instance, created, **kwargs):
    if created:
        try:
            send_otp(instance.name, instance.email, instance.otpForMail)
        except Exception as e:
            print(e)
            print("Something Wrong at send_email_otp")

@api_view(['PUT'])
@permission_classes([IsAuthenticated])
def verifyEmail(request, pk):

    user = CustomUser.objects.get(id=pk)

    data = request.data
    otp_to_verify = data['otpForEmail']

    if otp_to_verify == user.otpForEmail:
        user.isEmailVerified = True

        user.save()
        message = {'detail': 'Your email is now verified'}
        return Response(message, status=status.HTTP_400_BAD_REQUEST)
    else:

        message = {
            'detail': 'OTP is not valid and expired, Use New OTP which we have sent you on the email'}
        send_otp(user.name, user.email, user.otpForEmail)
        return Response(message, status=status.HTTP_400_BAD_REQUEST)

```

Title: How to merge a function into another

Body:
Sorry for asking a basic thing. new to Python and Django ,
I want to resend email if the OTP from PUT request is incorrect.
I have a function which send email with otp automatically on Register.
But if user PUT incorrect OTP I want to resend that email with new otp, So I want to merge sent_email_otp into verifyEmail function.
So how could I achieve that?

@receiver(post_save, sender=CustomUser)
def send_email_otp(sender, instance, created, **kwargs):
    if created:
        try:
            subject = "Your email needs to be verified to use site"
            message = f'Hi, Dear {instance.name} use this following OTP to Get verified your email : OTP({instance.otpForEmail})'

            email_from = settings.EMAIL_HOST_USER
            recipient_list = [instance.email]
            send_mail(subject, message, email_from, recipient_list)
            print(f"Email Sent to {instance.email}")
        except Exception as e:
            print(e)
            print("Something Wrong at send_email_otp")

@api_view(['PUT'])
@permission_classes([IsAuthenticated])
def verifyEmail(request, pk):

    user = CustomUser.objects.get(id=pk)

    data = request.data
    otp_to_verify = data['otpForEmail']

    if otp_to_verify == user.otpForEmail:
        user.isEmailVerified = True

        user.save()
        message = {'detail': 'Your email is now verified'}
        return Response(message, status=status.HTTP_400_BAD_REQUEST)
    else:

        message = {
            'detail': 'OTP is not valid and expired, Use New OTP which we have sent you on the email'}
        return Response(message, status=status.HTTP_400_BAD_REQUEST)

Edit:
If I simply call the send_email_otp() inside else statement of verifyEmail then this error comes :

TypeError: send_email_otp() missing 3 required positional arguments: 'sender', 'instance', and 'created'


问:
barplot labels to show full numbers instead of scientific formula
I'm using this kaggle dataset to perform my data analysis.
I converted 'course_students_enrolled' column values to integers.
When I plot courses with highest numbers of students, I get a figure where bar labels that represent values above 1M appear written in formula like 1.3e+06 instead of showing the full number. Same goes with the number above the chart.
This is my code of the plot:

popularity_filt = (main_df['course_students_enrolled'].sort_values(ascending=False))
most_pop_courses = main_df.iloc[popularity_filt.index][:10]
course_titles = most_pop_courses['title'].to_list()
data = most_pop_courses[['title','course_students_enrolled']]
sns.set_context(font_scale=3, rc={'font.size':12, 'axes.labelsize':20})
sns.set_style('darkgrid')
palette = sns.color_palette(palette="Greens_d", n_colors=len(data))
plt.figure(figsize=(12,6))
ax = sns.barplot(x='title', y='course_students_enrolled', data=data, palette=np.array(palette[::-1]));
ax.set_xticklabels(course_titles, rotation=40, ha='right')
ax.bar_label(ax.containers[0]);

plt.show()
```

Is there a way to show full numbers instead?

答:
You can convert it into the appropriate string using f-string:</p>
```<code>ax.bar_label(ax.containers[0], labels=[f'{x.get_height():.0f}' for x in ax.containers[0]])
</code>```

Body:
I'm using this kaggle dataset to perform my data analysis.
I converted 'course_students_enrolled' column values to integers.
When I plot courses with highest numbers of students, I get a figure where bar labels that represent values above 1M appear written in formula like 1.3e+06 instead of showing the full number. Same goes with the number above the chart.
This is my code of the plot:

popularity_filt = (main_df['course_students_enrolled'].sort_values(ascending=False))
most_pop_courses = main_df.iloc[popularity_filt.index][:10]
course_titles = most_pop_courses['title'].to_list()
data = most_pop_courses[['title','course_students_enrolled']]
sns.set_context(font_scale=3, rc={'font.size':12, 'axes.labelsize':20})
sns.set_style('darkgrid')
palette = sns.color_palette(palette="Greens_d", n_colors=len(data))
plt.figure(figsize=(12,6))
ax = sns.barplot(x='title', y='course_students_enrolled', data=data, palette=np.array(palette[::-1]));
ax.set_xticklabels(course_titles, rotation=40, ha='right')
ax.bar_label(ax.containers[0]);

plt.show()

Is there a way to show full numbers instead?

Body:
You can convert it into the appropriate string using f-string:

ax.bar_label(ax.containers[0], labels=[f'{x.get_height():.0f}' for x in ax.containers[0]])


问:
Is it possible to change the variance of a base class/trait in Scala?
I would like to derive from Scala's immutable Map. It is defined as such:

```<code>trait Map[A, +B]
</code>```

Unfortunately, my implementation needs to be invariant in B. I tried the following, but without success:

```<code>def +(kv : (A, B)) : MyMap[A, B] = { ... }

override def +[B1 >: B](kv : (A, B1)) : MyMap[A, B1] =
    throw new IllegalArgumentException()
</code>```

Maybe there is a trick with @uncheckedVariance?

答:
The trouble is that if you derive an invariant version from an immutable map, you'll break type safety. For example:

```<code>val dm = DiotMap(1 -> "abc")
val m: Map[Int, Any] = dm
</code>```

This declaration is valid, because Map is covariant. If your collection cannot handle covariance, what will happen when I use m?

Body:
I would like to derive from Scala's immutable Map. It is defined as such:

trait Map[A, +B]

Unfortunately, my implementation needs to be invariant in B. I tried the following, but without success:

def +(kv : (A, B)) : MyMap[A, B] = { ... }

override def +[B1 >: B](kv : (A, B1)) : MyMap[A, B1] =
    throw new IllegalArgumentException()

Maybe there is a trick with @uncheckedVariance?

Body:
The trouble is that if you derive an invariant version from an immutable map, you'll break type safety. For example:

val dm = DiotMap(1 -> "abc")
val m: Map[Int, Any] = dm

This declaration is valid, because Map is covariant. If your collection cannot handle covariance, what will happen when I use m?


问:
Setting QScrollArea background to transparent makes contents disappear and changes scroll bar looks
So a simple scroll area with many buttons would look like this:

with the following code:

```<code>from PyQt5.QtWidgets import QWidget, QApplication, QScrollArea, QVBoxLayout, QPushButton

class TestWindow(QWidget):
    def __init__(self):
        super().__init__()
        scroll = QScrollArea()
        # scroll.setStyleSheet('background: transparent')
        widget = QWidget(self)
        widget.setLayout(QVBoxLayout())
        for i in range(10):
            widget.layout().addWidget(QPushButton())
        scroll.setWidget(widget)

        self.setLayout(QVBoxLayout())
        self.layout().addWidget(scroll)

        self.show()

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    w = TestWindow()
    w.show()
    sys.exit(app.exec_())
</code>```

but if I use scroll.setStyleSheet('background: transparent') to set the background of the scroll area to transparent, it makes the buttons disappear and changes how the scroll bar looks:

Apparently I am doing something wrong. Can you please help me spot my mistake?

答: Turns out that I just have to change the background of the scroll area specifically using scroll.setStyleSheet('QScrollArea {background: transparent;}')

Body:
So a simple scroll area with many buttons would look like this:

with the following code:

from PyQt5.QtWidgets import QWidget, QApplication, QScrollArea, QVBoxLayout, QPushButton

class TestWindow(QWidget):
    def __init__(self):
        super().__init__()
        scroll = QScrollArea()
        # scroll.setStyleSheet('background: transparent')
        widget = QWidget(self)
        widget.setLayout(QVBoxLayout())
        for i in range(10):
            widget.layout().addWidget(QPushButton())
        scroll.setWidget(widget)

        self.setLayout(QVBoxLayout())
        self.layout().addWidget(scroll)

        self.show()

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    w = TestWindow()
    w.show()
    sys.exit(app.exec_())

but if I use scroll.setStyleSheet('background: transparent') to set the background of the scroll area to transparent, it makes the buttons disappear and changes how the scroll bar looks:

Apparently I am doing something wrong. Can you please help me spot my mistake?


问:
Hashtable, two test does not work with Junit
I have written a code where I implement a hashtable of a set interface. All of my tests I going through except these two below in the test class. I have included how I have written them. For the first test I get:

```<code>java.lang.AssertionError:
Expected: <-1>
     but: was <0>
Expected :<-1>
Actual   :<0>
</code>```

and then the second test I get:

```<code>java.lang.AssertionError:
Expected: <0>
     but: was <10>
Expected :<0>
Actual   :<10>
</code>```

I don't know what I am supposed to write/ change in the tests, so they work.

//EDIT: I added a test that has a similar code to the first test that I have a problem with. This test goes through.

//TODO: help me understand how I should write these two tests.

```<code>/**
 * An interface describing a generic set. Duplicates are not allowed.
 */
public interface Set<T> {

    boolean add(T elem);
    boolean remove(T elem);
    boolean contains(T elem);
    int size();
}

</code>```
```<code>import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

import static java.util.Objects.hash;

/**
 * A hash table-based implementation of the Set interface.
 */
public class HashSet<T> implements Set<T> {
   private List<T>[] table;
    private int size;
    private int capacity;
    private int index;

     /**
     * Creates a hash table with the given capacity (amount of buckets).
     *
     * @throws IllegalArgumentException if capacity <= 0.
     */
    public HashSet(int capacity) {
        if (capacity <= 0) {
            throw new IllegalArgumentException(
                "capacity must be a positive, non-zero value! Provided: " + capacity);
        }
     @SuppressWarnings("unchecked") // for this declaration only
      List<T>[] t = new LinkedList[capacity];
      table = t;
      size = 0;
    }

    /**
     * Adds the given element to the set.
     *
     * Complexity: O(1) expected time.
     *
     * @param elem An element to add to the set.
     * @return true if the set did not contain the element, otherwise false.
     */
    @Override
    public boolean add(T elem) {
    if (elem == null || elem.equals("")){
            return false;
        }

        int hash = Math.abs(elem.hashCode() % table.length);

        if (table[hash]== null){
            table[hash] = new LinkedList<T>();
            table[hash].add(elem);
            size ++;
            return true;
        }
        if (table[hash].contains(elem)){
            return false;
        }else{
            table[hash].add(elem);
            size++;
            return true;
        }
    }

    /**
     * Removes the given element from the dictionary, if it is present.
     *
     * Complexity: O(1) expected time.
     *
     * @param elem An element to remove from the set.
     * @return true if the set contained the element, false otherwise.
     */
    @Override
    public boolean remove(T elem) {
        if (elem == null || elem.equals("")){
            return false;
        }

        int hash = Math.abs(elem.hashCode() % table.length);

        if (table[hash] != null && table[hash].contains(elem)){
            table[hash].remove(elem);
            size --;
            return true;
        }else{
            return false;
        }
    }

    /**
     * Check if an element is in the Set.
     *
     * Complexity: O(1) expected time.
     *
     * @param elem An element to look for.
     * @return true if the element is in the set, false otherwise.
     */
    @Override
    public boolean contains(T elem) {
        if (elem == null || elem .equals("")){
            return false;
        }
        int hash = Math.abs(elem.hashCode() % table.length);

        if (table[hash] != null && table[hash].contains(elem)){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        HashSet<?> hashSet = (HashSet<?>) o;
        return capacity == hashSet.capacity && size == hashSet.size && index == hashSet.index && Objects.equals(table, hashSet.table);
    }

    @Override
    public int hashCode() {
        return hash(capacity, size, index, table);
    }

    /**
     * Returns the number of elements in this set.
     *
     * Complexity: O(1) expected time.
     *
     * @return The number of elements in this set.
     */
    @Override
    public int size() {
        return size;
    }
}

</code>```
```<code>import org.junit.Test;
import org.junit.Before;
import static org.junit.Assert.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;

import java.util.Arrays;

/**
 * Test for the HashSet implementation of the Set interface. Runs both the
 * SetTest tests, as well as tests specific to hashing.
 *
 * This test class mostly contains only hash collision tests.
 */
public class HashSetTest extends SetTest {
    private Set<SingleHashUnequal> set;
    private SingleHashUnequal[] uniqueObjsWithEqualHashes;

    /**
     * Returns an implementation of Set that can hold at least 'minCapacity'
     * Integers.
     *
     * @param minCapacity The least amount of elements the Set must be able to
     * hold.
     * @return An implementation of Set.
     */
    @Override
    protected Set<Integer> getIntegerSet(int minCapacity) {
        return new HashSet<Integer>(minCapacity);
    }

    @Override
    @Before
    public void setUp() {
        // We are overriding the setUp method of SetTest, so we need to call
        // it explicitly to not break everything.
        super.setUp();

        int numDummies = 10;
        uniqueObjsWithEqualHashes = new SingleHashUnequal[numDummies];
        set = new HashSet<SingleHashUnequal>(numDummies * 2);
        for (int i = 0; i < numDummies; i++) {
            SingleHashUnequal dummy = new SingleHashUnequal();
            set.add(dummy);
            uniqueObjsWithEqualHashes[i] = dummy;
        }
    }

   @Test // similar test with the first test that I have a problem with.
    public void addUniqueElementsWithEqualHashesIncrementsSize() {
        // Arrange
        int capacity = uniqueObjsWithEqualHashes.length;
        Set<SingleHashUnequal> set = new HashSet<SingleHashUnequal>(capacity);
        int expectedSize = 0;
        for (SingleHashUnequal elem : uniqueObjsWithEqualHashes) {
            expectedSize++;
            // Act
            set.add(elem);
            // Assert
            assertThat(set.size(), equalTo(expectedSize));
        }
    }
    @Test
    public void removeUniqueElementsWithEqualHashesDecrementsSize() { //TESTT
        int capacity = uniqueObjsWithEqualHashes.length;
        Set<SingleHashUnequal> set = new HashSet<SingleHashUnequal>(capacity);
        int expectedSize = 0;
        for (SingleHashUnequal elem : uniqueObjsWithEqualHashes) {
            expectedSize--;
            // Act
            set.remove(elem);
            // Assert
            assertThat(set.size(), equalTo(expectedSize));
        }
    }

    @Test
    public void removeElementNotInSetWithCollidingHashDoesNotDecreaseSize() { //TESTT
        // Test that removing an element that is not in the set, but has the
        // same hash as some other element in the set, does not decrement size
        SingleHashUnequal elem = new SingleHashUnequal();
        int expectedSize = 0;
        set.remove(elem);
        assertThat(set.size(),equalTo(expectedSize));

    }
    /**
     * A helper class for testing hash collisions. Instances equal only
     * themselves and all instances have the same hashCode.
     */
    private static class SingleHashUnequal {
        private static final int HASH = 0;

        @Override
        public boolean equals(Object o) {

            return this == o;
        }

        @Override
        public int hashCode() {
            return HASH;
        }
    }
}
</code>```

答:
```<code>@Test
    public void removeUniqueElementsWithEqualHashesDecrementsSize() { //TESTT
        int capacity = uniqueObjsWithEqualHashes.length;
        Set<SingleHashUnequal> set = new HashSet<SingleHashUnequal>(capacity);
        int expectedSize = 0;
        for (SingleHashUnequal elem : uniqueObjsWithEqualHashes) {
            expectedSize--;
            // Act
            set.remove(elem);
            // Assert
            assertThat(set.size(), equalTo(expectedSize));
        }
    }
</code>```

Something seems off about this test, according to your @Before, you are already creating a new set in the line
 set = new HashSet<SingleHashUnequal>(numDummies * 2);

however, in your test, you create a new object with the same name:
Set<SingleHashUnequal> set = new HashSet<SingleHashUnequal>(capacity);
Same Object type, same name. This is generally bad practice, I don't know if somehow the objects got mixed in the compiler, but that's probably not the case.

Regardless,

```<code>Set<SingleHashUnequal> set = new HashSet<SingleHashUnequal>(capacity);
        int expectedSize = 0;
        for (SingleHashUnequal elem : uniqueObjsWithEqualHashes) {
            expectedSize--;
            // Act
            set.remove(elem);
</code>```

Here, you remove elements from a list that has no elements. According to your implementation, if the object you want to remove does not exist, nothing happens, all good. However, you still decrement expected size with expectedSize--. This means that even though nothing was removed, your size decreases to -1.

By then asserting if the values are equal, since the original size of the set still stands 0, and expected size stands at -1, it asserts that the code is wrong, even though it is the test that has its own problems.

Body:
I have written a code where I implement a hashtable of a set interface. All of my tests I going through except these two below in the test class. I have included how I have written them. For the first test I get:

java.lang.AssertionError:
Expected: <-1>
     but: was <0>
Expected :<-1>
Actual   :<0>

and then the second test I get:

java.lang.AssertionError:
Expected: <0>
     but: was <10>
Expected :<0>
Actual   :<10>

I don't know what I am supposed to write/ change in the tests, so they work.

//EDIT: I added a test that has a similar code to the first test that I have a problem with. This test goes through.

//TODO: help me understand how I should write these two tests.

/**
 * An interface describing a generic set. Duplicates are not allowed.
 */
public interface Set<T> {

    boolean add(T elem);
    boolean remove(T elem);
    boolean contains(T elem);
    int size();
}

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

import static java.util.Objects.hash;

/**
 * A hash table-based implementation of the Set interface.
 */
public class HashSet<T> implements Set<T> {
   private List<T>[] table;
    private int size;
    private int capacity;
    private int index;

     /**
     * Creates a hash table with the given capacity (amount of buckets).
     *
     * @throws IllegalArgumentException if capacity <= 0.
     */
    public HashSet(int capacity) {
        if (capacity <= 0) {
            throw new IllegalArgumentException(
                "capacity must be a positive, non-zero value! Provided: " + capacity);
        }
     @SuppressWarnings("unchecked") // for this declaration only
      List<T>[] t = new LinkedList[capacity];
      table = t;
      size = 0;
    }

    /**
     * Adds the given element to the set.
     *
     * Complexity: O(1) expected time.
     *
     * @param elem An element to add to the set.
     * @return true if the set did not contain the element, otherwise false.
     */
    @Override
    public boolean add(T elem) {
    if (elem == null || elem.equals("")){
            return false;
        }

        int hash = Math.abs(elem.hashCode() % table.length);

        if (table[hash]== null){
            table[hash] = new LinkedList<T>();
            table[hash].add(elem);
            size ++;
            return true;
        }
        if (table[hash].contains(elem)){
            return false;
        }else{
            table[hash].add(elem);
            size++;
            return true;
        }
    }

    /**
     * Removes the given element from the dictionary, if it is present.
     *
     * Complexity: O(1) expected time.
     *
     * @param elem An element to remove from the set.
     * @return true if the set contained the element, false otherwise.
     */
    @Override
    public boolean remove(T elem) {
        if (elem == null || elem.equals("")){
            return false;
        }

        int hash = Math.abs(elem.hashCode() % table.length);

        if (table[hash] != null && table[hash].contains(elem)){
            table[hash].remove(elem);
            size --;
            return true;
        }else{
            return false;
        }
    }

    /**
     * Check if an element is in the Set.
     *
     * Complexity: O(1) expected time.
     *
     * @param elem An element to look for.
     * @return true if the element is in the set, false otherwise.
     */
    @Override
    public boolean contains(T elem) {
        if (elem == null || elem .equals("")){
            return false;
        }
        int hash = Math.abs(elem.hashCode() % table.length);

        if (table[hash] != null && table[hash].contains(elem)){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        HashSet<?> hashSet = (HashSet<?>) o;
        return capacity == hashSet.capacity && size == hashSet.size && index == hashSet.index && Objects.equals(table, hashSet.table);
    }

    @Override
    public int hashCode() {
        return hash(capacity, size, index, table);
    }

    /**
     * Returns the number of elements in this set.
     *
     * Complexity: O(1) expected time.
     *
     * @return The number of elements in this set.
     */
    @Override
    public int size() {
        return size;
    }
}

import org.junit.Test;
import org.junit.Before;
import static org.junit.Assert.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;

import java.util.Arrays;

/**
 * Test for the HashSet implementation of the Set interface. Runs both the
 * SetTest tests, as well as tests specific to hashing.
 *
 * This test class mostly contains only hash collision tests.
 */
public class HashSetTest extends SetTest {
    private Set<SingleHashUnequal> set;
    private SingleHashUnequal[] uniqueObjsWithEqualHashes;

    /**
     * Returns an implementation of Set that can hold at least 'minCapacity'
     * Integers.
     *
     * @param minCapacity The least amount of elements the Set must be able to
     * hold.
     * @return An implementation of Set.
     */
    @Override
    protected Set<Integer> getIntegerSet(int minCapacity) {
        return new HashSet<Integer>(minCapacity);
    }

    @Override
    @Before
    public void setUp() {
        // We are overriding the setUp method of SetTest, so we need to call
        // it explicitly to not break everything.
        super.setUp();

        int numDummies = 10;
        uniqueObjsWithEqualHashes = new SingleHashUnequal[numDummies];
        set = new HashSet<SingleHashUnequal>(numDummies * 2);
        for (int i = 0; i < numDummies; i++) {
            SingleHashUnequal dummy = new SingleHashUnequal();
            set.add(dummy);
            uniqueObjsWithEqualHashes[i] = dummy;
        }
    }

   @Test // similar test with the first test that I have a problem with.
    public void addUniqueElementsWithEqualHashesIncrementsSize() {
        // Arrange
        int capacity = uniqueObjsWithEqualHashes.length;
        Set<SingleHashUnequal> set = new HashSet<SingleHashUnequal>(capacity);
        int expectedSize = 0;
        for (SingleHashUnequal elem : uniqueObjsWithEqualHashes) {
            expectedSize++;
            // Act
            set.add(elem);
            // Assert
            assertThat(set.size(), equalTo(expectedSize));
        }
    }
    @Test
    public void removeUniqueElementsWithEqualHashesDecrementsSize() { //TESTT
        int capacity = uniqueObjsWithEqualHashes.length;
        Set<SingleHashUnequal> set = new HashSet<SingleHashUnequal>(capacity);
        int expectedSize = 0;
        for (SingleHashUnequal elem : uniqueObjsWithEqualHashes) {
            expectedSize--;
            // Act
            set.remove(elem);
            // Assert
            assertThat(set.size(), equalTo(expectedSize));
        }
    }

    @Test
    public void removeElementNotInSetWithCollidingHashDoesNotDecreaseSize() { //TESTT
        // Test that removing an element that is not in the set, but has the
        // same hash as some other element in the set, does not decrement size
        SingleHashUnequal elem = new SingleHashUnequal();
        int expectedSize = 0;
        set.remove(elem);
        assertThat(set.size(),equalTo(expectedSize));

    }
    /**
     * A helper class for testing hash collisions. Instances equal only
     * themselves and all instances have the same hashCode.
     */
    private static class SingleHashUnequal {
        private static final int HASH = 0;

        @Override
        public boolean equals(Object o) {

            return this == o;
        }

        @Override
        public int hashCode() {
            return HASH;
        }
    }
}

Body:
@Test
    public void removeUniqueElementsWithEqualHashesDecrementsSize() { //TESTT
        int capacity = uniqueObjsWithEqualHashes.length;
        Set<SingleHashUnequal> set = new HashSet<SingleHashUnequal>(capacity);
        int expectedSize = 0;
        for (SingleHashUnequal elem : uniqueObjsWithEqualHashes) {
            expectedSize--;
            // Act
            set.remove(elem);
            // Assert
            assertThat(set.size(), equalTo(expectedSize));
        }
    }

Something seems off about this test, according to your @Before, you are already creating a new set in the line
 set = new HashSet<SingleHashUnequal>(numDummies * 2);

however, in your test, you create a new object with the same name:
Set<SingleHashUnequal> set = new HashSet<SingleHashUnequal>(capacity);
Same Object type, same name. This is generally bad practice, I don't know if somehow the objects got mixed in the compiler, but that's probably not the case.

Regardless,

Set<SingleHashUnequal> set = new HashSet<SingleHashUnequal>(capacity);
        int expectedSize = 0;
        for (SingleHashUnequal elem : uniqueObjsWithEqualHashes) {
            expectedSize--;
            // Act
            set.remove(elem);

Here, you remove elements from a list that has no elements. According to your implementation, if the object you want to remove does not exist, nothing happens, all good. However, you still decrement expected size with expectedSize--. This means that even though nothing was removed, your size decreases to -1.

By then asserting if the values are equal, since the original size of the set still stands 0, and expected size stands at -1, it asserts that the code is wrong, even though it is the test that has its own problems.


问:
Getting 'The instance of entity type cannot be tracked because another instance with same key value for is already being tracked' with AsNoTracking()
I'm creating my Telegram bot using Entity Framework Core. I have these models:

```<code>public class User
{
    public int Id { get; set; }
    public long UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string UserName { get; set; }
    public ICollection<Chat> Chats { get; set;} = new List<Chat>();
    public ICollection<Team> CreatedTeams { get; set; } = new List<Team>();
    public ICollection<Team> Teams { get; set; } = new List<Team>();
}

public class Team
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? ChatId { get; set; }
    public Chat Chat { get; set; }
    public int? CreatorId { get; set; }
    public User Creator { get; set; }
    public ICollection<User> Users { get; set; } = new List<User>();
}
</code>```

When I handle incoming messages, I check if a User with the same UserId exists in DB. If it exists, then I just get it, if not - create new one on a base of Telegram User and return it.

```<code>public async Task<User> GetNewOrExistingUserAsync(Telegram.Bot.Types.User telegramUser)
{
    var user = this.GetUserByUserId(telegramUser.Id);

    if (user is null)
    {
        await this.userRepository.AddAsync((User)telegramUser);
        return this.GetUserByUserId(telegramUser.Id);
    }

    return user;
}

private User GetUserByUserId(long userId)
{
    return this.userRepository.GetAll()
            .Include(user => user.Chats)
            .Include(user => user.Teams)
            .Include(user => user.CreatedTeams)
            .AsNoTracking()
            .FirstOrDefault(user => user.UserId == userId);
 }
</code>```

After that I get Team by name specified in message:

```<code>public Team GetChatTeamByName(string name, long chatId)
{
    return this.teamRepository.GetAll()
         .Include(team => team.Creator)
         .Include(team => team.Users)
         .AsNoTracking()
         .FirstOrDefault(team => team.Chat.ChatId == chatId && team.Name.Equals(name));
}
</code>```

And finally I add user to team (I check, if it already exists in team, but I receive this error even without this check):

```<code>team.Users.Add(user);
await this.teamRepository.UpdateAsync(team);
</code>```

Here I get this error: 'The instance of entity type 'User' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked'. UpdateAsync() uses Entities.Update() method and saves changes. Error occurs after Entities.Update() call. I do not understand, where it starts tracking user - as you can see, I use AsNoTracking() in all related queries. I could assume, that it starts tracking after adding new user, but error occurs even when user is already in DB.

I've tried to use Entry<User>(user).State = EntityState.Detached; as people suggest, right before adding user to team, or after it, but error is the same. The context in my ASP app is Transient, but this error occurs even if it Scoped. Could you help me please with it? Or are there any other ways to add user to team without calling Update() method?

The whole method is:

```<code>public async Task<Message> AddUserToTeamAsync(ITelegramBotClient botClient, Message message)
{
    var user = await this.userService.GetNewOrExistingUserAsync(message.From);

    var teamName = message.Text.SplitToWords()[1];
    var team = this.teamService.GetChatTeamByName(teamName, message.Chat.Id);

    team.Users.Add(user);
    await this.teamRepository.UpdateAsync(team);
    .....
}
</code>```

Update.GetAll() method:

```<code>public virtual IQueryable<T> GetAll()
{
    return this.Entities;
}
</code>```

答:
You don't seem to fully comprehend what AsNoTracking does: It explicitly disconnects the entity from the database. So if you want to Update that entity, you shouldn't disconnect it in the first place.

It's a relational database. If you want to add an existing user to a team, you need to track the existing object. Else the database will try to create a new one with exactly the same values, and there will be a collision.

DEBATABLE Side note: why are you using Include, instead of lazy loading? We are running several large application at my company and almost never have to use Include.

EDIT: I did a small test

namespace UserTeams
{
    public class User
    {
        public int Id { get; set; }
        public long UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string UserName { get; set; }
        public ICollection<Team> CreatedTeams { get; set; } = new List<Team>();
        public ICollection<Team> Teams { get; set; } = new List<Team>();
    }

    public class Team
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int? CreatorId { get; set; }
        public User Creator { get; set; }
        public ICollection<User> Users { get; set; } = new List<User>();
    }
}
```
<pre class="lang-cs prettyprint-override"><code>using Microsoft.EntityFrameworkCore;

namespace UserTeams
{
    internal class MyContext : DbContext
    {
        public DbSet<User> Users { get; set; }
        public DbSet<Team> Teams { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Server=localhost\SQLEXPRESS;Database=Test;Trusted_Connection=True;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>().HasMany(user => user.Teams).WithMany(team => team.Users);
            modelBuilder.Entity<User>().HasMany(user => user.CreatedTeams).WithOne(team => team.Creator);

            modelBuilder.Entity<Team>().HasOne(team => team.Creator)
                .WithMany(user => user.CreatedTeams)
                .HasForeignKey(team => team.CreatorId);
            modelBuilder.Entity<Team>().HasMany(team => team.Users).WithMany(user => user.Teams);
        }
    }
}
</code>```

// See https://aka.ms/new-console-template for more information
using UserTeams;

using (var myContext = new MyContext())
{
    myContext.Users.Add(new User
    {
        UserId = 123,
    });

    myContext.Teams.Add(new Team
    {
        Name = "myTeam",
    });

    myContext.SaveChanges();
}

using (var myContext = new MyContext())
{
    var user = myContext.Users.First(u => u.UserId == 123);

    var team = myContext.Teams.First(t => t.Name == "myTeam");

    team.Users.Add(user);
    user.Teams.Add(team);
    myContext.SaveChanges();
}
```

I get no collisions.

Body:
I'm creating my Telegram bot using Entity Framework Core. I have these models:

public class User
{
    public int Id { get; set; }
    public long UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string UserName { get; set; }
    public ICollection<Chat> Chats { get; set;} = new List<Chat>();
    public ICollection<Team> CreatedTeams { get; set; } = new List<Team>();
    public ICollection<Team> Teams { get; set; } = new List<Team>();
}

public class Team
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? ChatId { get; set; }
    public Chat Chat { get; set; }
    public int? CreatorId { get; set; }
    public User Creator { get; set; }
    public ICollection<User> Users { get; set; } = new List<User>();
}

When I handle incoming messages, I check if a User with the same UserId exists in DB. If it exists, then I just get it, if not - create new one on a base of Telegram User and return it.

public async Task<User> GetNewOrExistingUserAsync(Telegram.Bot.Types.User telegramUser)
{
    var user = this.GetUserByUserId(telegramUser.Id);

    if (user is null)
    {
        await this.userRepository.AddAsync((User)telegramUser);
        return this.GetUserByUserId(telegramUser.Id);
    }

    return user;
}

private User GetUserByUserId(long userId)
{
    return this.userRepository.GetAll()
            .Include(user => user.Chats)
            .Include(user => user.Teams)
            .Include(user => user.CreatedTeams)
            .AsNoTracking()
            .FirstOrDefault(user => user.UserId == userId);
 }

After that I get Team by name specified in message:

public Team GetChatTeamByName(string name, long chatId)
{
    return this.teamRepository.GetAll()
         .Include(team => team.Creator)
         .Include(team => team.Users)
         .AsNoTracking()
         .FirstOrDefault(team => team.Chat.ChatId == chatId && team.Name.Equals(name));
}

And finally I add user to team (I check, if it already exists in team, but I receive this error even without this check):

team.Users.Add(user);
await this.teamRepository.UpdateAsync(team);

Here I get this error: 'The instance of entity type 'User' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked'. UpdateAsync() uses Entities.Update() method and saves changes. Error occurs after Entities.Update() call. I do not understand, where it starts tracking user - as you can see, I use AsNoTracking() in all related queries. I could assume, that it starts tracking after adding new user, but error occurs even when user is already in DB.

I've tried to use Entry<User>(user).State = EntityState.Detached; as people suggest, right before adding user to team, or after it, but error is the same. The context in my ASP app is Transient, but this error occurs even if it Scoped. Could you help me please with it? Or are there any other ways to add user to team without calling Update() method?

The whole method is:

public async Task<Message> AddUserToTeamAsync(ITelegramBotClient botClient, Message message)
{
    var user = await this.userService.GetNewOrExistingUserAsync(message.From);

    var teamName = message.Text.SplitToWords()[1];
    var team = this.teamService.GetChatTeamByName(teamName, message.Chat.Id);

    team.Users.Add(user);
    await this.teamRepository.UpdateAsync(team);
    .....
}

Update.GetAll() method:

public virtual IQueryable<T> GetAll()
{
    return this.Entities;
}

Body:
You don't seem to fully comprehend what AsNoTracking does: It explicitly disconnects the entity from the database. So if you want to Update that entity, you shouldn't disconnect it in the first place.

It's a relational database. If you want to add an existing user to a team, you need to track the existing object. Else the database will try to create a new one with exactly the same values, and there will be a collision.

DEBATABLE Side note: why are you using Include, instead of lazy loading? We are running several large application at my company and almost never have to use Include.

EDIT: I did a small test

namespace UserTeams
{
    public class User
    {
        public int Id { get; set; }
        public long UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string UserName { get; set; }
        public ICollection<Team> CreatedTeams { get; set; } = new List<Team>();
        public ICollection<Team> Teams { get; set; } = new List<Team>();
    }

    public class Team
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int? CreatorId { get; set; }
        public User Creator { get; set; }
        public ICollection<User> Users { get; set; } = new List<User>();
    }
}

using Microsoft.EntityFrameworkCore;

namespace UserTeams
{
    internal class MyContext : DbContext
    {
        public DbSet<User> Users { get; set; }
        public DbSet<Team> Teams { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Server=localhost\SQLEXPRESS;Database=Test;Trusted_Connection=True;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>().HasMany(user => user.Teams).WithMany(team => team.Users);
            modelBuilder.Entity<User>().HasMany(user => user.CreatedTeams).WithOne(team => team.Creator);

            modelBuilder.Entity<Team>().HasOne(team => team.Creator)
                .WithMany(user => user.CreatedTeams)
                .HasForeignKey(team => team.CreatorId);
            modelBuilder.Entity<Team>().HasMany(team => team.Users).WithMany(user => user.Teams);
        }
    }
}

// See https://aka.ms/new-console-template for more information
using UserTeams;

using (var myContext = new MyContext())
{
    myContext.Users.Add(new User
    {
        UserId = 123,
    });

    myContext.Teams.Add(new Team
    {
        Name = "myTeam",
    });

    myContext.SaveChanges();
}

using (var myContext = new MyContext())
{
    var user = myContext.Users.First(u => u.UserId == 123);

    var team = myContext.Teams.First(t => t.Name == "myTeam");

    team.Users.Add(user);
    user.Teams.Add(team);
    myContext.SaveChanges();
}

I get no collisions.


问:
how to make jupyter notebook always focus on the latest output?
when we execute a program in jupyter notebook and have lot of print, jupyter didn't auto scroll to the latest output. I have to scroll to know what is the latest output. how can I make it always showing the latest output?</p>

答:
Jupyter notebook does not have the feature you want probably you will need to integrate some plugin. Search around the internet you will find what you want. Here one example check this repo:

https://github.com/ipython-contrib/jupyter_contrib_nbextensions


问:
BeautifulSoup: How to include the encoding on output?
I would like to include the encoding tag in an XML document using BeautifulSoup.BeautifulStoneSoup, but I'm not sure how!

```<code><?xml version="1.0" encoding="UTF-8"?>
<mytag>stuff</mytag>
</code>```

It outputs the encoding tag when I read a document that already has it, but I'm making a new soup.

Thanks!

Edit: I'll give an example of what I'm currently doing.

```<code>from BeautifulSoup import BeautifulStoneSoup, Tag
soup = BeautifulStoneSoup()
mytag = Tag(soup, 'mytag')
soup.append(mytag)

str(soup)
# '<mytag></mytag>'

soup.prettify() # No encoding given
# '<mytag>\n</mytag>'

soup.prettify(encoding='UTF-8')
# '<mytag>\n</mytag>' # Where's the encoding?
</code>```

Even if I create the soup like BeautifulStoneSoup(fromEncoding='UTF-8'), there is still no <?xml?> tag.

Is there another way to get that tag without creating and passing the tag as a string directly, or is that the only way?

答:
Do you mean something like this?

```<code>from BeautifulSoup import BeautifulStoneSoup
soup = BeautifulStoneSoup('<?xml version="1.0" encoding="UTF-8"?>')
# make some more soup
</code>```

Or,

```<code>soup = BeautifulStoneSoup()
# make some more soup
soup.insert(0, '<?xml version="1.0" encoding="UTF-8"?>')
</code>```

From the BeautifulSoup documentation:

Beautiful Soup tries the following encodings, in order of priority, to turn your document into Unicode:

An encoding you pass in as the fromEncoding argument to the soup constructor.

An encoding discovered in the document itself: for instance, in an XML declaration or (for HTML documents) an http-equiv META tag. If Beautiful Soup finds this kind of encoding within the document, it parses the document again from the beginning and gives the new encoding a try. The only exception is if you explicitly specified an encoding, and that encoding actually worked: then it will ignore any encoding it finds in the document.

An encoding sniffed by looking at the first few bytes of the file. If an encoding is detected at this stage, it will be one of the UTF-* encodings, EBCDIC, or ASCII.

An encoding sniffed by the chardet library, if you have it installed.

UTF-8

Windows-1252

Beautiful Soup will almost always guess right if it can make a guess at all. But for documents with no declarations and in strange encodings, it will often not be able to guess.

N.B. item #2, which I read as: BeautifulSoup will use the encoding in the xml declaration automatically, if you don't explicitly specify one with the fromEncoding argument. YMMV.

There are other, potentially useful, unicode related examples in the earlier referenced documentation, as well.

Edit: @TorelTwiddler, if there is another way to add an xml declaration using BeautifulSoup without passing the tag as a string directly, I am not aware of it.

That said, consider the following:

```<code>soup = BeautifulStoneSoup('<?xml version="1.0" encoding=""?>') # <- no encoding
mytag = Tag(soup, 'mytag')
soup.append(mytag)

print str(soup)
# "<?xml version='1.0' encoding='utf-8'?><mytag></mytag>"
# Wha!? :)
print soup.prettify(encoding='euc-jp')
# <?xml version='1.0' encoding='euc-jp'?>
# <mytag>
# </mytag>
</code>```

Perhaps that'll help you get where you want to go.

Body:
I would like to include the encoding tag in an XML document using BeautifulSoup.BeautifulStoneSoup, but I'm not sure how!

<?xml version="1.0" encoding="UTF-8"?>
<mytag>stuff</mytag>

It outputs the encoding tag when I read a document that already has it, but I'm making a new soup.

Thanks!

Edit: I'll give an example of what I'm currently doing.

from BeautifulSoup import BeautifulStoneSoup, Tag
soup = BeautifulStoneSoup()
mytag = Tag(soup, 'mytag')
soup.append(mytag)

str(soup)
# '<mytag></mytag>'

soup.prettify() # No encoding given
# '<mytag>\n</mytag>'

soup.prettify(encoding='UTF-8')
# '<mytag>\n</mytag>' # Where's the encoding?

Even if I create the soup like BeautifulStoneSoup(fromEncoding='UTF-8'), there is still no <?xml?> tag.

Is there another way to get that tag without creating and passing the tag as a string directly, or is that the only way?

Body:
Do you mean something like this?

from BeautifulSoup import BeautifulStoneSoup
soup = BeautifulStoneSoup('<?xml version="1.0" encoding="UTF-8"?>')
# make some more soup

Or,

soup = BeautifulStoneSoup()
# make some more soup
soup.insert(0, '<?xml version="1.0" encoding="UTF-8"?>')

From the BeautifulSoup documentation:

Beautiful Soup tries the following encodings, in order of priority, to turn your document into Unicode:

An encoding you pass in as the fromEncoding argument to the soup constructor.

An encoding discovered in the document itself: for instance, in an XML declaration or (for HTML documents) an http-equiv META tag. If Beautiful Soup finds this kind of encoding within the document, it parses the document again from the beginning and gives the new encoding a try. The only exception is if you explicitly specified an encoding, and that encoding actually worked: then it will ignore any encoding it finds in the document.

An encoding sniffed by looking at the first few bytes of the file. If an encoding is detected at this stage, it will be one of the UTF-* encodings, EBCDIC, or ASCII.

An encoding sniffed by the chardet library, if you have it installed.

UTF-8

Windows-1252

Beautiful Soup will almost always guess right if it can make a guess at all. But for documents with no declarations and in strange encodings, it will often not be able to guess.

N.B. item #2, which I read as: BeautifulSoup will use the encoding in the xml declaration automatically, if you don't explicitly specify one with the fromEncoding argument. YMMV.

There are other, potentially useful, unicode related examples in the earlier referenced documentation, as well.

Edit: @TorelTwiddler, if there is another way to add an xml declaration using BeautifulSoup without passing the tag as a string directly, I am not aware of it.

That said, consider the following:

soup = BeautifulStoneSoup('<?xml version="1.0" encoding=""?>') # <- no encoding
mytag = Tag(soup, 'mytag')
soup.append(mytag)

print str(soup)
# "<?xml version='1.0' encoding='utf-8'?><mytag></mytag>"
# Wha!? :)
print soup.prettify(encoding='euc-jp')
# <?xml version='1.0' encoding='euc-jp'?>
# <mytag>
# </mytag>

Perhaps that'll help you get where you want to go.