问:
Error while receiving data in nested recyclerview
I made a nested recycler view so that each store is taken separately, in the parentitem first the name and photo of the store and in the childitem the products of this store.  what it looks like.

under the uid of the client there is the uid of the stores, and under them their goods are already going.
I need to create a parent item in the main recycler in the fragment where there will be photos of each store and this item has its own recycler where there should be child items (products from this store) What is in the products

MagLogo is the logo of the store from which the product is from, tovarcartShopuid is the uid of the store where the product is from.

when running the snippet it gives the following error

```<code>E/AndroidRuntime: FATAL EXCEPTION: main

    Process: mychati.app, PID: 26357

    com.google.firebase.database.DatabaseException: Expected a List while deserializing, but got a class java.util.HashMap

        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToParameterizedType(CustomClassMapper.java:251)

        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToType(CustomClassMapper.java:177)

        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(CustomClassMapper.java:102)

        at com.google.firebase.database.DataSnapshot.getValue(DataSnapshot.java:229)

        at mychati.app.Client.repo.FirebaseRepo$1.onDataChange(FirebaseRepo.java:46)

        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)

        at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)

        at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)

        at android.os.Handler.handleCallback(Handler.java:938)

        at android.os.Handler.dispatchMessage(Handler.java:99)

        at android.os.Looper.loop(Looper.java:236)

        at android.app.ActivityThread.main(ActivityThread.java:8056)

        at java.lang.reflect.Method.invoke(Native Method)

        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656)

        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)

</code>```

FirebaseRepo

```<code>public class FirebaseRepo {

    private DatabaseReference databaseReference;

    private OnRealDbTaskComplete onRealDbTaskComplete;

    private FirebaseAuth mAuth;

    public FirebaseRepo(OnRealDbTaskComplete onRealDbTaskComplete){

        this.onRealDbTaskComplete=onRealDbTaskComplete;

        databaseReference= FirebaseDatabase.getInstance().getReference().child("DoCart");

        mAuth=FirebaseAuth.getInstance();

    }

    public void getAllData(){

        databaseReference.child(mAuth.getCurrentUser().getUid()).addValueEventListener(new ValueEventListener() {

            @Override

            public void onDataChange(@NonNull DataSnapshot snapshot) {

                List<ParentItem>parentItemList=new ArrayList<>();

                for (DataSnapshot ds:snapshot.getChildren()){

                    ParentItem parentItem=new ParentItem();

                    parentItem.setMagLogo(ds.child("MagLogo").getValue(String.class));

                    parentItem.setMagName(ds.child("MagName").getValue(String.class));

                    GenericTypeIndicator<ArrayList<ChildItem>> genericTypeIndicator=new GenericTypeIndicator<ArrayList<ChildItem>>() {

                    };

                    parentItem.setChildItemList(ds.getValue(genericTypeIndicator));

                    parentItemList.add(parentItem);

                }

                onRealDbTaskComplete.onSuccess(parentItemList);

            }

            @Override

            public void onCancelled(@NonNull DatabaseError error) {

onRealDbTaskComplete.onFailure(error);

            }

        });

    }

    public interface OnRealDbTaskComplete{

        void onSuccess(List<ParentItem>parentItemList);

        void onFailure(DatabaseError error);

    }

}

</code>```

ParentItem

```<code>

                    GenericTypeIndicator<ArrayList<ChildItem>> genericTypeIndicator=new GenericTypeIndicator<ArrayList<ChildItem>>() {

                    };

                    parentItem.setChildItemList(ds.getValue(genericTypeIndicator));

                    parentItemList.add(parentItem);

                }

                onRealDbTaskComplete.onSuccess(parentItemList);

            }

            @Override

            public void onCancelled(@NonNull DatabaseError error) {

onRealDbTaskComplete.onFailure(error);

            }

        });

    }

    public interface OnRealDbTaskComplete{

        void onSuccess(List<ParentItem>parentItemList);

        void onFailure(DatabaseError error);

    }

}
</code>```

ParentItem

```<code>
public class ParentItem {

    private String MagLogo,MagName;

    private List<ChildItem>childItemList;

    public ParentItem(){}

    public ParentItem(String magLogo, String magName,List<ChildItem> childItemList) {

        MagLogo = magLogo;

        MagName = magName;

        this.childItemList = childItemList;

    }

    public List<ChildItem> getChildItemList() {

        return childItemList;

    }

    public void setChildItemList(List<ChildItem> childItemList) {

        this.childItemList = childItemList;

    }

    public String getMagLogo() {

        return MagLogo;

    }

    public void setMagLogo(String magLogo) {

        MagLogo = magLogo;

    }

    public String getMagName() {

        return MagName;

    }

    public void setMagName(String magName) {

        MagName = magName;

    }

}
</code>```

ChildItem

```<code>public class ChildItem {

    private String tovarImage,tovarcartShopuid,tovarname,Price,ProductId,TovarValue,MyUID;

    public ChildItem(){}

    public ChildItem(String tovarImage, String tovarcartShopuid, String tovarname, String price, String productId, String tovarValue, String myUID) {

        this.tovarImage = tovarImage;

        this.tovarcartShopuid = tovarcartShopuid;

        this.tovarname = tovarname;

       this. Price = price;

        this.   ProductId = productId;

        this. TovarValue = tovarValue;

        this.  MyUID = myUID;

    }

    public String getTovarImage() {

        return tovarImage;

    }

    public void setTovarImage(String tovarImage) {

        this.tovarImage = tovarImage;

    }

    public String getTovarcartShopuid() {

        return tovarcartShopuid;

    }

    public void setTovarcartShopuid(String tovarcartShopuid) {

        this.tovarcartShopuid = tovarcartShopuid;

    }

    public String getTovarname() {

        return tovarname;

    }

    public void setTovarname(String tovarname) {

        this.tovarname = tovarname;

    }

    public String getPrice() {

        return Price;

    }

    public void setPrice(String price) {

        Price = price;

    }

    public String getProductId() {

        return ProductId;

    }

    public void setProductId(String productId) {

        ProductId = productId;

    }

    public String getTovarValue() {

        return TovarValue;

    }

    public void setTovarValue(String tovarValue) {

        TovarValue = tovarValue;

    }

    public String getMyUID() {

        return MyUID;

    }

    public void setMyUID(String myUID) {

        MyUID = myUID;

    }

}

</code>```

ChildAdapter

```<code>public class ChildAdapter extends RecyclerView.Adapter<ChildAdapter.ChildViewHolder> {

public List<ChildItem>childItemList;

public void setChildItemList(List<ChildItem>childItemList){

    this.childItemList=childItemList;

    this.childItemList.removeAll(Collections.singleton(null));

}

    @NonNull

    @Override

    public ChildViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.child_item,parent,false);

return new ChildViewHolder(view);

    }

    @Override

    public void onBindViewHolder(@NonNull ChildViewHolder holder, int position) {

ChildItem childItem=childItemList.get(position);

holder.txttovarName.setText(childItem.getTovarname());

holder.txttovarValue.setText(childItem.getTovarValue());

holder.txttovarPrice.setText(childItem.getPrice());

holder.txttovarName.setHint(childItem.getTovarcartShopuid());

holder.txttovarPrice.setHint(childItem.getProductId());

        Transformation transformation=new RoundedTransformationBuilder().borderColor(Color.WHITE).borderWidthDp(3).cornerRadius(15).oval(false).build();

        Picasso.get().load(childItem.getTovarImage()).transform(transformation).into(holder.imagetovarchild);

    }

    @Override

    public int getItemCount() {

 if (childItemList !=null){

     return childItemList.size();

 }else {

     return 0;

 }

    }

    public class ChildViewHolder extends RecyclerView.ViewHolder{

private TextView txttovarName,txttovarValue,txttovarPrice,tovarplus,tovarminus;

private RoundedImageView imagetovarchild;

        public ChildViewHolder(@NonNull View itemView) {

            super(itemView);

            imagetovarchild=itemView.findViewById(R.id.imagetovarchild);

            txttovarName=itemView.findViewById(R.id.textnamechild);

            txttovarPrice=itemView.findViewById(R.id.textpricechildtovar);

            txttovarValue=itemView.findViewById(R.id.tovarcartchild);

            tovarminus=itemView.findViewById(R.id.tovarminuschildto);

            tovarplus=itemView.findViewById(R.id.tovarpluschildto);

        }

    }

}

</code>```

ParentAdapter

```<code>public class ParentAdapter extends RecyclerView.Adapter<ParentAdapter.ParentviewHolder> {

    private List<ParentItem>parentItemList;

    public void setParentItemList(List<ParentItem>parentItemList){

        this.parentItemList=parentItemList;

    }

    @NonNull

    @Override

    public ParentviewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

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

return new ParentviewHolder(view);

    }

    @Override

    public void onBindViewHolder(@NonNull ParentviewHolder holder, int position) {

ParentItem parentItem=parentItemList.get(position);

        Transformation transformation=new RoundedTransformationBuilder().borderColor(Color.WHITE).borderWidthDp(3).cornerRadius(15).oval(false).build();

        Picasso.get().load(parentItem.getMagLogo()).transform(transformation).into(holder.roundedImagemaglogoparent);

        holder.nestedrecer.setHasFixedSize(true);

        holder.nestedrecer.setLayoutManager(new LinearLayoutManager(holder.itemView.getContext()));

        ChildAdapter childAdapter=new ChildAdapter();

        childAdapter.setChildItemList(parentItem.getChildItemList());

        holder.nestedrecer.setAdapter(childAdapter);

        childAdapter.notifyDataSetChanged();

    }

    @Override

    public int getItemCount() {

        if (parentItemList !=null){

            return parentItemList.size();

        }else{

            return 0;

        }

    }

    public class ParentviewHolder extends RecyclerView.ViewHolder{

private RoundedImageView roundedImagemaglogoparent;

private TextView textitogParent;

private ImageView imagedeletemag;

private RecyclerView nestedrecer;

        public ParentviewHolder(@NonNull View itemView) {

            super(itemView);

            textitogParent=itemView.findViewById(R.id.textitogParent);

            roundedImagemaglogoparent=itemView.findViewById(R.id. roundedImagemaglogoparent);

            nestedrecer=itemView.findViewById(R.id.nestedrecer);

            imagedeletemag=itemView.findViewById(R.id.imagedeletemag);

        }

    }

}

</code>```

CartFragment(Where the nested recyclerview should be visible)

```<code>
public class CartFragment extends Fragment {

private FirebaseViewModel firebaseViewModel;

    private DatabaseReference karzinaRef;

    private DatabaseReference shopRef;

    private LottieAnimationView lottieAnimationView;

    private RoundedImageView shopimege;

    private int overTotalPrice=0;

    private AppCompatButton buybutton;

private int overTovar;

    private TextView textpricecarti,textkarzininziv,textViewnocart;

    private RecyclerView reccart;

    private FirebaseAuth mAuth;

    private DatabaseReference hophh;

    private ParentAdapter parentAdapter;

    private ImageView deletezakazcart;

View cart;

    // TODO: Rename parameter arguments, choose names that match

    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER

    private static final String ARG_PARAM1 = "param1";

    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters

    private String mParam1;

    private String mParam2;

    public CartFragment() {

        // Required empty public constructor

    }

    /**

     * Use this factory method to create a new instance of

     * this fragment using the provided parameters.

     *

     * @param param1 Parameter 1.

     * @param param2 Parameter 2.

     * @return A new instance of fragment CartFragment.

     */

    // TODO: Rename and change types and number of parameters

    public static CartFragment newInstance(String param1, String param2) {

        CartFragment fragment = new CartFragment();

        Bundle args = new Bundle();

        args.putString(ARG_PARAM1, param1);

        args.putString(ARG_PARAM2, param2);

        fragment.setArguments(args);

        return fragment;

    }

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        if (getArguments() != null) {

            mParam1 = getArguments().getString(ARG_PARAM1);

            mParam2 = getArguments().getString(ARG_PARAM2);

        }

    }

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,

                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment

   cart= inflater.inflate(R.layout.fragment_cart, container, false);

reccart=cart.findViewById(R.id.reccart);

        deletezakazcart=cart.findViewById(R.id.deletedocart);

        karzinaRef= FirebaseDatabase.getInstance().getReference().child("DoCart");

        shopRef=FirebaseDatabase.getInstance().getReference().child("shops");

        mAuth=FirebaseAuth.getInstance();

lottieAnimationView=cart.findViewById(R.id.lottieAnimationViewnottovarcart);

textViewnocart=cart.findViewById(R.id.texxtnottovercart);

parentAdapter=new ParentAdapter();

reccart.setAdapter(parentAdapter);

reccart.setHasFixedSize(true);

reccart.setLayoutManager(new LinearLayoutManager(getContext()));

firebaseViewModel=new ViewModelProvider(this).get(FirebaseViewModel.class);

firebaseViewModel.getAllData();

firebaseViewModel.getParentItemMutableLiveDate().observe(getViewLifecycleOwner(), new Observer<List<ParentItem>>() {

    @Override

    public void onChanged(List<ParentItem> parentItemList) {

        parentAdapter.setParentItemList(parentItemList);

        parentAdapter.notifyDataSetChanged();

    }

});

firebaseViewModel.getDatabaseErrorMutableLiveDate().observe(getViewLifecycleOwner(), new Observer<DatabaseError>() {

    @Override

    public void onChanged(DatabaseError error) {

    }

});

   return cart;

}
}

</code>```

haven't tried anything yet

Body:
I made a nested recycler view so that each store is taken separately, in the parentitem first the name and photo of the store and in the childitem the products of this store.  what it looks like.

under the uid of the client there is the uid of the stores, and under them their goods are already going.
I need to create a parent item in the main recycler in the fragment where there will be photos of each store and this item has its own recycler where there should be child items (products from this store) What is in the products

MagLogo is the logo of the store from which the product is from, tovarcartShopuid is the uid of the store where the product is from.

when running the snippet it gives the following error

E/AndroidRuntime: FATAL EXCEPTION: main

    Process: mychati.app, PID: 26357

    com.google.firebase.database.DatabaseException: Expected a List while deserializing, but got a class java.util.HashMap

        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToParameterizedType(CustomClassMapper.java:251)

        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToType(CustomClassMapper.java:177)

        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(CustomClassMapper.java:102)

        at com.google.firebase.database.DataSnapshot.getValue(DataSnapshot.java:229)

        at mychati.app.Client.repo.FirebaseRepo$1.onDataChange(FirebaseRepo.java:46)

        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)

        at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)

        at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)

        at android.os.Handler.handleCallback(Handler.java:938)

        at android.os.Handler.dispatchMessage(Handler.java:99)

        at android.os.Looper.loop(Looper.java:236)

        at android.app.ActivityThread.main(ActivityThread.java:8056)

        at java.lang.reflect.Method.invoke(Native Method)

        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656)

        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)

FirebaseRepo

public class FirebaseRepo {

    private DatabaseReference databaseReference;

    private OnRealDbTaskComplete onRealDbTaskComplete;

    private FirebaseAuth mAuth;

    public FirebaseRepo(OnRealDbTaskComplete onRealDbTaskComplete){

        this.onRealDbTaskComplete=onRealDbTaskComplete;

        databaseReference= FirebaseDatabase.getInstance().getReference().child("DoCart");

        mAuth=FirebaseAuth.getInstance();

    }

    public void getAllData(){

        databaseReference.child(mAuth.getCurrentUser().getUid()).addValueEventListener(new ValueEventListener() {

            @Override

            public void onDataChange(@NonNull DataSnapshot snapshot) {

                List<ParentItem>parentItemList=new ArrayList<>();

                for (DataSnapshot ds:snapshot.getChildren()){

                    ParentItem parentItem=new ParentItem();

                    parentItem.setMagLogo(ds.child("MagLogo").getValue(String.class));

                    parentItem.setMagName(ds.child("MagName").getValue(String.class));

                    GenericTypeIndicator<ArrayList<ChildItem>> genericTypeIndicator=new GenericTypeIndicator<ArrayList<ChildItem>>() {

                    };

                    parentItem.setChildItemList(ds.getValue(genericTypeIndicator));

                    parentItemList.add(parentItem);

                }

                onRealDbTaskComplete.onSuccess(parentItemList);

            }

            @Override

            public void onCancelled(@NonNull DatabaseError error) {

onRealDbTaskComplete.onFailure(error);

            }

        });

    }

    public interface OnRealDbTaskComplete{

        void onSuccess(List<ParentItem>parentItemList);

        void onFailure(DatabaseError error);

    }

}

ParentItem

                    GenericTypeIndicator<ArrayList<ChildItem>> genericTypeIndicator=new GenericTypeIndicator<ArrayList<ChildItem>>() {

                    };

                    parentItem.setChildItemList(ds.getValue(genericTypeIndicator));

                    parentItemList.add(parentItem);

                }

                onRealDbTaskComplete.onSuccess(parentItemList);

            }

            @Override

            public void onCancelled(@NonNull DatabaseError error) {

onRealDbTaskComplete.onFailure(error);

            }

        });

    }

    public interface OnRealDbTaskComplete{

        void onSuccess(List<ParentItem>parentItemList);

        void onFailure(DatabaseError error);

    }

}

ParentItem

public class ParentItem {

    private String MagLogo,MagName;

    private List<ChildItem>childItemList;

    public ParentItem(){}

    public ParentItem(String magLogo, String magName,List<ChildItem> childItemList) {

        MagLogo = magLogo;

        MagName = magName;

        this.childItemList = childItemList;

    }

    public List<ChildItem> getChildItemList() {

        return childItemList;

    }

    public void setChildItemList(List<ChildItem> childItemList) {

        this.childItemList = childItemList;

    }

    public String getMagLogo() {

        return MagLogo;

    }

    public void setMagLogo(String magLogo) {

        MagLogo = magLogo;

    }

    public String getMagName() {

        return MagName;

    }

    public void setMagName(String magName) {

        MagName = magName;

    }

}

ChildItem

public class ChildItem {

    private String tovarImage,tovarcartShopuid,tovarname,Price,ProductId,TovarValue,MyUID;

    public ChildItem(){}

    public ChildItem(String tovarImage, String tovarcartShopuid, String tovarname, String price, String productId, String tovarValue, String myUID) {

        this.tovarImage = tovarImage;

        this.tovarcartShopuid = tovarcartShopuid;

        this.tovarname = tovarname;

       this. Price = price;

        this.   ProductId = productId;

        this. TovarValue = tovarValue;

        this.  MyUID = myUID;

    }

    public String getTovarImage() {

        return tovarImage;

    }

    public void setTovarImage(String tovarImage) {

        this.tovarImage = tovarImage;

    }

    public String getTovarcartShopuid() {

        return tovarcartShopuid;

    }

    public void setTovarcartShopuid(String tovarcartShopuid) {

        this.tovarcartShopuid = tovarcartShopuid;

    }

    public String getTovarname() {

        return tovarname;

    }

    public void setTovarname(String tovarname) {

        this.tovarname = tovarname;

    }

    public String getPrice() {

        return Price;

    }

    public void setPrice(String price) {

        Price = price;

    }

    public String getProductId() {

        return ProductId;

    }

    public void setProductId(String productId) {

        ProductId = productId;

    }

    public String getTovarValue() {

        return TovarValue;

    }

    public void setTovarValue(String tovarValue) {

        TovarValue = tovarValue;

    }

    public String getMyUID() {

        return MyUID;

    }

    public void setMyUID(String myUID) {

        MyUID = myUID;

    }

}

ChildAdapter

public class ChildAdapter extends RecyclerView.Adapter<ChildAdapter.ChildViewHolder> {

public List<ChildItem>childItemList;

public void setChildItemList(List<ChildItem>childItemList){

    this.childItemList=childItemList;

    this.childItemList.removeAll(Collections.singleton(null));

}

    @NonNull

    @Override

    public ChildViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.child_item,parent,false);

return new ChildViewHolder(view);

    }

    @Override

    public void onBindViewHolder(@NonNull ChildViewHolder holder, int position) {

ChildItem childItem=childItemList.get(position);

holder.txttovarName.setText(childItem.getTovarname());

holder.txttovarValue.setText(childItem.getTovarValue());

holder.txttovarPrice.setText(childItem.getPrice());

holder.txttovarName.setHint(childItem.getTovarcartShopuid());

holder.txttovarPrice.setHint(childItem.getProductId());

        Transformation transformation=new RoundedTransformationBuilder().borderColor(Color.WHITE).borderWidthDp(3).cornerRadius(15).oval(false).build();

        Picasso.get().load(childItem.getTovarImage()).transform(transformation).into(holder.imagetovarchild);

    }

    @Override

    public int getItemCount() {

 if (childItemList !=null){

     return childItemList.size();

 }else {

     return 0;

 }

    }

    public class ChildViewHolder extends RecyclerView.ViewHolder{

private TextView txttovarName,txttovarValue,txttovarPrice,tovarplus,tovarminus;

private RoundedImageView imagetovarchild;

        public ChildViewHolder(@NonNull View itemView) {

            super(itemView);

            imagetovarchild=itemView.findViewById(R.id.imagetovarchild);

            txttovarName=itemView.findViewById(R.id.textnamechild);

            txttovarPrice=itemView.findViewById(R.id.textpricechildtovar);

            txttovarValue=itemView.findViewById(R.id.tovarcartchild);

            tovarminus=itemView.findViewById(R.id.tovarminuschildto);

            tovarplus=itemView.findViewById(R.id.tovarpluschildto);

        }

    }

}

ParentAdapter

public class ParentAdapter extends RecyclerView.Adapter<ParentAdapter.ParentviewHolder> {

    private List<ParentItem>parentItemList;

    public void setParentItemList(List<ParentItem>parentItemList){

        this.parentItemList=parentItemList;

    }

    @NonNull

    @Override

    public ParentviewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

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

return new ParentviewHolder(view);

    }

    @Override

    public void onBindViewHolder(@NonNull ParentviewHolder holder, int position) {

ParentItem parentItem=parentItemList.get(position);

        Transformation transformation=new RoundedTransformationBuilder().borderColor(Color.WHITE).borderWidthDp(3).cornerRadius(15).oval(false).build();

        Picasso.get().load(parentItem.getMagLogo()).transform(transformation).into(holder.roundedImagemaglogoparent);

        holder.nestedrecer.setHasFixedSize(true);

        holder.nestedrecer.setLayoutManager(new LinearLayoutManager(holder.itemView.getContext()));

        ChildAdapter childAdapter=new ChildAdapter();

        childAdapter.setChildItemList(parentItem.getChildItemList());

        holder.nestedrecer.setAdapter(childAdapter);

        childAdapter.notifyDataSetChanged();

    }

    @Override

    public int getItemCount() {

        if (parentItemList !=null){

            return parentItemList.size();

        }else{

            return 0;

        }

    }

    public class ParentviewHolder extends RecyclerView.ViewHolder{

private RoundedImageView roundedImagemaglogoparent;

private TextView textitogParent;

private ImageView imagedeletemag;

private RecyclerView nestedrecer;

        public ParentviewHolder(@NonNull View itemView) {

            super(itemView);

            textitogParent=itemView.findViewById(R.id.textitogParent);

            roundedImagemaglogoparent=itemView.findViewById(R.id. roundedImagemaglogoparent);

            nestedrecer=itemView.findViewById(R.id.nestedrecer);

            imagedeletemag=itemView.findViewById(R.id.imagedeletemag);

        }

    }

}

CartFragment(Where the nested recyclerview should be visible)

public class CartFragment extends Fragment {

private FirebaseViewModel firebaseViewModel;

    private DatabaseReference karzinaRef;

    private DatabaseReference shopRef;

    private LottieAnimationView lottieAnimationView;

    private RoundedImageView shopimege;

    private int overTotalPrice=0;

    private AppCompatButton buybutton;

private int overTovar;

    private TextView textpricecarti,textkarzininziv,textViewnocart;

    private RecyclerView reccart;

    private FirebaseAuth mAuth;

    private DatabaseReference hophh;

    private ParentAdapter parentAdapter;

    private ImageView deletezakazcart;

View cart;

    // TODO: Rename parameter arguments, choose names that match

    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER

    private static final String ARG_PARAM1 = "param1";

    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters

    private String mParam1;

    private String mParam2;

    public CartFragment() {

        // Required empty public constructor

    }

    /**

     * Use this factory method to create a new instance of

     * this fragment using the provided parameters.

     *

     * @param param1 Parameter 1.

     * @param param2 Parameter 2.

     * @return A new instance of fragment CartFragment.

     */

    // TODO: Rename and change types and number of parameters

    public static CartFragment newInstance(String param1, String param2) {

        CartFragment fragment = new CartFragment();

        Bundle args = new Bundle();

        args.putString(ARG_PARAM1, param1);

        args.putString(ARG_PARAM2, param2);

        fragment.setArguments(args);

        return fragment;

    }

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        if (getArguments() != null) {

            mParam1 = getArguments().getString(ARG_PARAM1);

            mParam2 = getArguments().getString(ARG_PARAM2);

        }

    }

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,

                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment

   cart= inflater.inflate(R.layout.fragment_cart, container, false);

reccart=cart.findViewById(R.id.reccart);

        deletezakazcart=cart.findViewById(R.id.deletedocart);

        karzinaRef= FirebaseDatabase.getInstance().getReference().child("DoCart");

        shopRef=FirebaseDatabase.getInstance().getReference().child("shops");

        mAuth=FirebaseAuth.getInstance();

lottieAnimationView=cart.findViewById(R.id.lottieAnimationViewnottovarcart);

textViewnocart=cart.findViewById(R.id.texxtnottovercart);

parentAdapter=new ParentAdapter();

reccart.setAdapter(parentAdapter);

reccart.setHasFixedSize(true);

reccart.setLayoutManager(new LinearLayoutManager(getContext()));

firebaseViewModel=new ViewModelProvider(this).get(FirebaseViewModel.class);

firebaseViewModel.getAllData();

firebaseViewModel.getParentItemMutableLiveDate().observe(getViewLifecycleOwner(), new Observer<List<ParentItem>>() {

    @Override

    public void onChanged(List<ParentItem> parentItemList) {

        parentAdapter.setParentItemList(parentItemList);

        parentAdapter.notifyDataSetChanged();

    }

});

firebaseViewModel.getDatabaseErrorMutableLiveDate().observe(getViewLifecycleOwner(), new Observer<DatabaseError>() {

    @Override

    public void onChanged(DatabaseError error) {

    }

});

   return cart;

}
}

haven't tried anything yet


来源: stackexchange

问:
How to force a tauri app to open a UAC prompt before running to force administrator?
My tauri app includes it's backend with the frontend code, but the backend code requires administrator to run. I don't want the user to have to right click and run as an administrator every time they want to run the app, so I am wondering how I could make a UAC appear before the app starts to give the app admin.</p>

ContentLicense: CC BY-SA 4.0


问:
Chrome desktop latest feature: link tooltip stays on screen forever
Chrome desktop latest feature: tooltip stay on screen forever. This feature seems for mobile device.

When clicking a link (ajax), a tooltip (link title) shows up and sometimes it stays on screen forever. Obviously desktop does not need it.

Is there a way for selenium to turn the feature  off?

Can Chrome version be reverted to a previous version?


问:
Scipy error - Negative answer on scipy minimization of a negative function
I have dataframe of prices of 2 stock in a 2 stock portfolio

```<code>prices0.head()
</code>```

as follows

```<code>    AAPL    META
Date
2013-01-03  16.649982   27.770000
2013-01-04  16.186199   28.760000
2013-01-07  16.090984   29.420000
2013-01-08  16.134287   29.059999
2013-01-09  15.882127   30.590000
</code>```

I compute the price returns by percentage change

```<code>returns0= prices0.pct_change()[1:]
returns0
</code>```
```<code>    AAPL    META
Date
2013-01-04  -0.027855   0.035650
2013-01-07  -0.005882   0.022949
2013-01-08  0.002691    -0.012237
2013-01-09  -0.015629   0.052650
2013-01-10  0.012397    0.023210
... ... ...
2021-12-28  -0.005767   0.000116
2021-12-29  0.000502    -0.009474
2021-12-30  -0.006578   0.004141
2021-12-31  -0.003535   -0.023260
2022-01-03  0.025004    0.006511
</code>```

Furthermore I compute mean of returns and covariance matrix of the returns0dataframe

```<code>meanreturns0= np.mean(returns0,axis=0)
</code>```
```<code>covreturns0= returns0.cov()
</code>```

the mean returns are positive and covariance matrix is obtained which I feed into a Function which gives output of portfolio returns and portfolio standard deviation with 50% weightage to each stock

```<code>def portperf(weights, meanreturns, covreturns):
    returns = np.sum(meanreturns*weights)*(252)
    risk = np.sqrt(np.dot(weights.T,np.dot(covreturns, weights)))*np.sqrt(252)
    return (returns,risk)

portperf(weights, meanreturns0, covreturns0)
</code>```

output is

```<code>(0.3202930997975036, 0.2658945212290512)
</code>```

which is a positive value

Now as a final computation I wanted to optimize the weights to get highest return for which I took Sharpe ratio

Sharpe ratio = Portfolio return - risk free rate / Portfolio standard deviation

to maximize sharpe ratio I defined the function below and took the negative of the sharpe ratio as output because moving forward I used scipy library optimize tool's minimize SLSQP method to minimize a negative function to get a positive answer

```<code>def negativeSR(weights, meanreturns, covreturns, riskfreerate):
    portret, portrisk = portperf(weights, meanreturns, covreturns)
    return -(portret-riskfreerate)/portrisk
</code>```
```<code>negativeSR(weights, meanreturns0, covreturns0, 0.0013)
</code>```

output: ( as you can see is a negative value (deliberately) for usage in minimization method)

```<code>    AAPL    META
Date
2013-01-03  16.649982   27.770000
2013-01-04  16.186199   28.760000
2013-01-07  16.090984   29.420000
2013-01-08  16.134287   29.059999
2013-01-09  15.882127   30.590000
</code>```0

Scipy method for minimization of negative sharpe ratio to get positive sharpe ratio :

```<code>    AAPL    META
Date
2013-01-03  16.649982   27.770000
2013-01-04  16.186199   28.760000
2013-01-07  16.090984   29.420000
2013-01-08  16.134287   29.059999
2013-01-09  15.882127   30.590000
</code>```1

final output I got is confusing :

```<code>    AAPL    META
Date
2013-01-03  16.649982   27.770000
2013-01-04  16.186199   28.760000
2013-01-07  16.090984   29.420000
2013-01-08  16.134287   29.059999
2013-01-09  15.882127   30.590000
</code>```2

fun:

```<code>-1.2099816890480395
</code>```

is the sharpe ratio which i was expecting to be positive value as seen in https://youtu.be/vAmlFBpipT8?list=PLqpCwow11-OooQGB3vuiCdsRLQ5i-6AEH&t=952 Quantpy's video on maximizing sharpe ratio

but my output seems to be negativebut the x: array ( which are weights btw) are positive

What is the problem here ?

Body:
I have dataframe of prices of 2 stock in a 2 stock portfolio

prices0.head()

as follows

    AAPL    META
Date
2013-01-03  16.649982   27.770000
2013-01-04  16.186199   28.760000
2013-01-07  16.090984   29.420000
2013-01-08  16.134287   29.059999
2013-01-09  15.882127   30.590000

I compute the price returns by percentage change

returns0= prices0.pct_change()[1:]
returns0

    AAPL    META
Date
2013-01-04  -0.027855   0.035650
2013-01-07  -0.005882   0.022949
2013-01-08  0.002691    -0.012237
2013-01-09  -0.015629   0.052650
2013-01-10  0.012397    0.023210
... ... ...
2021-12-28  -0.005767   0.000116
2021-12-29  0.000502    -0.009474
2021-12-30  -0.006578   0.004141
2021-12-31  -0.003535   -0.023260
2022-01-03  0.025004    0.006511

Furthermore I compute mean of returns and covariance matrix of the returns0dataframe

meanreturns0= np.mean(returns0,axis=0)

covreturns0= returns0.cov()

the mean returns are positive and covariance matrix is obtained which I feed into a Function which gives output of portfolio returns and portfolio standard deviation with 50% weightage to each stock

def portperf(weights, meanreturns, covreturns):
    returns = np.sum(meanreturns*weights)*(252)
    risk = np.sqrt(np.dot(weights.T,np.dot(covreturns, weights)))*np.sqrt(252)
    return (returns,risk)

portperf(weights, meanreturns0, covreturns0)

output is

(0.3202930997975036, 0.2658945212290512)

which is a positive value

Now as a final computation I wanted to optimize the weights to get highest return for which I took Sharpe ratio

Sharpe ratio = Portfolio return - risk free rate / Portfolio standard deviation

to maximize sharpe ratio I defined the function below and took the negative of the sharpe ratio as output because moving forward I used scipy library optimize tool's minimize SLSQP method to minimize a negative function to get a positive answer

def negativeSR(weights, meanreturns, covreturns, riskfreerate):
    portret, portrisk = portperf(weights, meanreturns, covreturns)
    return -(portret-riskfreerate)/portrisk

negativeSR(weights, meanreturns0, covreturns0, 0.0013)

output: ( as you can see is a negative value (deliberately) for usage in minimization method)

-1.1996979039771614

Scipy method for minimization of negative sharpe ratio to get positive sharpe ratio :

def maxSR(meanreturns, covreturns, riskfreerate, constraintSet=(0,1)):
    "Minimize the negative SR, by altering the weights of the portfolio"
    numAssets = len(meanreturns)
    args = (meanreturns, covreturns, riskfreerate)
    constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1})
    bound = constraintSet
    bounds = tuple(bound for asset in range(numAssets))
    result = sc.minimize(negativeSR, numAssets*[1./numAssets], args=args,
                        method='SLSQP', bounds=bounds, constraints=constraints)
    return result

maxSR(meanreturns0, covreturns0, 0.0013)

final output I got is confusing :

 fun: -1.2099816890480395
     jac: array([-0.00447838, -0.00575559])
 message: 'Optimization terminated successfully'
    nfev: 9
     nit: 3
    njev: 3
  status: 0
 success: True
       x: array([0.60672397, 0.39327603])

fun:

-1.2099816890480395

is the sharpe ratio which i was expecting to be positive value as seen in https://youtu.be/vAmlFBpipT8?list=PLqpCwow11-OooQGB3vuiCdsRLQ5i-6AEH&t=952 Quantpy's video on maximizing sharpe ratio

but my output seems to be negativebut the x: array ( which are weights btw) are positive

What is the problem here ?


问:
What am I doing wrong with Discord API auth in Bubble.io?
So I have an API call that gets a users information with authentication, but when i initialize it, it says that im unauthorized (401). any help or insight?

Tried changing the method of authentication, but nothing seems to work


问:
Syntax of Array.sort for 2D array
I am trying to understand the logic of the following lambda expression below to sort a 2D array. From what I understand from the code below is that it will sort the 2D array based off the second value i.e. {1, 3} --> 3, {0, 1} --> 1, {3, 4} --> 4. But why is there subtraction i.e. b[1] - a[1]?

```<code>int[][] B = {{1,3},{0,1},{3,4}};
Arrays.sort(B, (a,b) -> b[1] - a[1]);

</code>```

Title: Syntax of Array.sort for 2D array

Body:
I am trying to understand the logic of the following lambda expression below to sort a 2D array. From what I understand from the code below is that it will sort the 2D array based off the second value i.e. {1, 3} --> 3, {0, 1} --> 1, {3, 4} --> 4. But why is there subtraction i.e. b[1] - a[1]?

int[][] B = {{1,3},{0,1},{3,4}};
Arrays.sort(B, (a,b) -> b[1] - a[1]);


问:
Flutter application to print reciept on thermal printer using bluetooth_print package is not working in background. How to do that?
Using the following package (bluetooth_print: ^4.3.0) we have developed a flutter android mobile application for restaurant owner. It will print a order receipt whenever a new order is placed and notification is received from firebase.

It is working fine in foreground when the screen is on. But it is throwing an error while in background(after pressing home button). I guess it is facing an issue while accessing native code. This is the error message:

```<code>No implementation found for method "startScan" on channel "bluetooth_print/methods"
</code>```

We tried to run this code as background service using many packages like flutter_background_service & background_fetch. But nothing seem to be working.

Body:
Using the following package (bluetooth_print: ^4.3.0) we have developed a flutter android mobile application for restaurant owner. It will print a order receipt whenever a new order is placed and notification is received from firebase.

It is working fine in foreground when the screen is on. But it is throwing an error while in background(after pressing home button). I guess it is facing an issue while accessing native code. This is the error message:

No implementation found for method "startScan" on channel "bluetooth_print/methods"

We tried to run this code as background service using many packages like flutter_background_service & background_fetch. But nothing seem to be working.


问:
OMNeT++: Unable to get to talk a wireless host to a wired host via an AP
I am a newbie to OMNeT++. I am trying to work out the following network setup, so that the wirelessHost can send UDP packets to the wiredHost over the network.

NED for the same is as follows.

package inettutorial.simulations.poi;

import inet.networklayer.configurator.ipv4.Ipv4NetworkConfigurator;
import inet.node.ethernet.Eth10G;
import inet.node.inet.Router;
import inet.node.inet.StandardHost;
import inet.node.inet.WirelessHost;
import inet.node.wireless.AccessPoint;
import inet.physicallayer.wireless.unitdisk.UnitDiskRadioMedium;
import inet.visualizer.canvas.integrated.IntegratedCanvasVisualizer;

network poi {
    parameters:
        @display("bgb=514,316;bgg=100,1,grey95");
        @figure[title](type=label; pos=0,-1; anchor=sw; color=darkblue);

        @figure[rcvdPkText](type=indicatorText; pos=380,20; anchor=w; font=,18; textFormat="packets received: %g"; initialValue=0);
        @statistic[packetReceived](source=wiredHost.app[0].packetReceived; record=figure(count); targetFigure=rcvdPkText);

    submodules:
        wirelessHost: WirelessHost {
            @display("p=403,224");
            numWlanInterfaces = 1;
            numApps = 1;
        }
        router: Router {
            @display("p=193,224");
            numEthInterfaces = 2;
        }
        accessPoint: AccessPoint {
            @display("p=303,217;r=2000");
        }
        wiredHost: StandardHost {
            @display("p=73,224");
            numEthInterfaces = 1;
            numApps = 1;
        }

        visualiser: IntegratedCanvasVisualizer {
            @display("p=379,57");
        }

        configurator: Ipv4NetworkConfigurator {
            @display("p=104,35");
        }

        unitDiskRadioMedium: UnitDiskRadioMedium {
            @display("p=216,100;r=10000");
        }

    connections:
        accessPoint.ethg++ <--> Eth10G <--> router.ethg[0];
        router.ethg[1] <--> Eth10G <--> wiredHost.ethg[0];
}
```
<p>And the initialisation goes as follows (<code>omnetpp.ini</code>)</p>
<pre class="lang-ini prettyprint-override"><code>[General]
network = poi

**.wlan[*].radio.typename = "UnitDiskRadio"
**.wlan[*].radio.radioMediumModule = "unitDiskRadioMedium"
**.wlan[*].typename = "AckingWirelessInterface"
**.wlan[*].mac.useAck = false

#*.configurator.config = xmldoc("nw_config.xml")

# Configurator settings
*.configurator.dumpAddresses = true
*.configurator.dumpTopology = true
*.configurator.dumpLinks = true
*.configurator.dumpRoutes = true

# Routing settings
*.*.ipv4.arp.typename = "GlobalArp"
*.*.ipv4.routingTable.netmaskRoutes = ""

# Visualiser Settings
*.visualiser.interfaceTableVisualizer.displayInterfaceTables = true
#*.visualiser.interfaceTableVisualizer.nodeFilter = "not (*switch* or *Switch* or *AP*)"

#*.wirelessHost.ipv4.arp.typename = "GlobalArp"

*.wirelessHost.app[0].typename = "UdpBasicApp"
*.wirelessHost.app[0].destAddresses = "wiredHost"
*.wirelessHost.app[0].destPort = 5000
*.wirelessHost.app[0].messageLength = 500B
*.wirelessHost.app[0].sendInterval = 1s
*.wirelessHost.app[0].packetName = "UDPData"

*.wirelessHost.wlan[*].radio.receiver.ignoreInterference = true

*.wiredHost.app[0].typename = "UdpSink"
*.wiredHost.app[0].localPort = 5000

*.wirelessHost.wlan[0].radio.transmitter.communicationRange = 500m
*.accessPoint.wlan[0].radio.transmitter.communicationRange = 500m
**.wlan[0].mac.headerLength = 1B

**.**.bitrate = 10Gbps
</code>```

But, when I run the simulation, all I see is UDP packets are flowing from wirelessHost to accessPoint and nothing beyond that. What am I missing?

Body:
I am a newbie to OMNeT++. I am trying to work out the following network setup, so that the wirelessHost can send UDP packets to the wiredHost over the network.

NED for the same is as follows.

package inettutorial.simulations.poi;

import inet.networklayer.configurator.ipv4.Ipv4NetworkConfigurator;
import inet.node.ethernet.Eth10G;
import inet.node.inet.Router;
import inet.node.inet.StandardHost;
import inet.node.inet.WirelessHost;
import inet.node.wireless.AccessPoint;
import inet.physicallayer.wireless.unitdisk.UnitDiskRadioMedium;
import inet.visualizer.canvas.integrated.IntegratedCanvasVisualizer;

network poi {
    parameters:
        @display("bgb=514,316;bgg=100,1,grey95");
        @figure[title](type=label; pos=0,-1; anchor=sw; color=darkblue);

        @figure[rcvdPkText](type=indicatorText; pos=380,20; anchor=w; font=,18; textFormat="packets received: %g"; initialValue=0);
        @statistic[packetReceived](source=wiredHost.app[0].packetReceived; record=figure(count); targetFigure=rcvdPkText);

    submodules:
        wirelessHost: WirelessHost {
            @display("p=403,224");
            numWlanInterfaces = 1;
            numApps = 1;
        }
        router: Router {
            @display("p=193,224");
            numEthInterfaces = 2;
        }
        accessPoint: AccessPoint {
            @display("p=303,217;r=2000");
        }
        wiredHost: StandardHost {
            @display("p=73,224");
            numEthInterfaces = 1;
            numApps = 1;
        }

        visualiser: IntegratedCanvasVisualizer {
            @display("p=379,57");
        }

        configurator: Ipv4NetworkConfigurator {
            @display("p=104,35");
        }

        unitDiskRadioMedium: UnitDiskRadioMedium {
            @display("p=216,100;r=10000");
        }

    connections:
        accessPoint.ethg++ <--> Eth10G <--> router.ethg[0];
        router.ethg[1] <--> Eth10G <--> wiredHost.ethg[0];
}

And the initialisation goes as follows (omnetpp.ini)

[General]
network = poi

**.wlan[*].radio.typename = "UnitDiskRadio"
**.wlan[*].radio.radioMediumModule = "unitDiskRadioMedium"
**.wlan[*].typename = "AckingWirelessInterface"
**.wlan[*].mac.useAck = false

#*.configurator.config = xmldoc("nw_config.xml")

# Configurator settings
*.configurator.dumpAddresses = true
*.configurator.dumpTopology = true
*.configurator.dumpLinks = true
*.configurator.dumpRoutes = true

# Routing settings
*.*.ipv4.arp.typename = "GlobalArp"
*.*.ipv4.routingTable.netmaskRoutes = ""

# Visualiser Settings
*.visualiser.interfaceTableVisualizer.displayInterfaceTables = true
#*.visualiser.interfaceTableVisualizer.nodeFilter = "not (*switch* or *Switch* or *AP*)"

#*.wirelessHost.ipv4.arp.typename = "GlobalArp"

*.wirelessHost.app[0].typename = "UdpBasicApp"
*.wirelessHost.app[0].destAddresses = "wiredHost"
*.wirelessHost.app[0].destPort = 5000
*.wirelessHost.app[0].messageLength = 500B
*.wirelessHost.app[0].sendInterval = 1s
*.wirelessHost.app[0].packetName = "UDPData"

*.wirelessHost.wlan[*].radio.receiver.ignoreInterference = true

*.wiredHost.app[0].typename = "UdpSink"
*.wiredHost.app[0].localPort = 5000

*.wirelessHost.wlan[0].radio.transmitter.communicationRange = 500m
*.accessPoint.wlan[0].radio.transmitter.communicationRange = 500m
**.wlan[0].mac.headerLength = 1B

**.**.bitrate = 10Gbps

But, when I run the simulation, all I see is UDP packets are flowing from wirelessHost to accessPoint and nothing beyond that. What am I missing?


问:
Type error occurring when initialising firestore
how do i fix these errors in this code:

```<code>import * as firebase from "firebase/app";
import "firebase/firestore";

const firestore = firebase.firestore();
</code>```

Errors:
Property 'firestore' does not exist on type 'typeof import("/Users/.../node_modules/firebase/app/dist/app/index")'.ts(2339)

Property 'firestore' does not exist on type 'typeof import("/Users/.../node_modules/firebase/app/dist/app/index")'.ts(2339)

i am using react and typescript.

i also tried this:

```<code>import firebase from 'firebase/app';
import 'firebase/firestore';
const firestore = firebase.firestore();
</code>```

Body:
how do i fix these errors in this code:

import * as firebase from "firebase/app";
import "firebase/firestore";

const firestore = firebase.firestore();

Errors:
Property 'firestore' does not exist on type 'typeof import("/Users/.../node_modules/firebase/app/dist/app/index")'.ts(2339)

Property 'firestore' does not exist on type 'typeof import("/Users/.../node_modules/firebase/app/dist/app/index")'.ts(2339)

i am using react and typescript.

i also tried this:

import firebase from 'firebase/app';
import 'firebase/firestore';
const firestore = firebase.firestore();


问:
vcpkg installed gtk-4 VS debugger failed with read access violation
I successfully installed gtk:x86-windows 4.6.8 by vcpkg. Then, I created a console application in Visual Studio 2022 on Windows 11 and added additional include directories as D:\Resources\vcpkg\installed\x86-windows\include\pango-1.0;D:\Resources\vcpkg\installed\x86-windows\include\cairo;D:\Resources\vcpkg\installed\x86-windows\include\gtk-4.0;D:\Resources\vcpkg\installed\x86-windows\include\glib-2.0;D:\Resources\vcpkg\installed\x86-windows\include\gio-win32-2.0;D:\Resources\vcpkg\installed\x86-windows\lib\glib-2.0\include;D:\Resources\vcpkg\installed\x86-windows\include\gdk-pixbuf-2.0;D:\Resources\vcpkg\installed\x86-windows\include\graphene-1.0;D:\Resources\vcpkg\installed\x86-windows\lib\graphene-1.0\include;D:\Resources\vcpkg\installed\x86-windows\include\harfbuzz;%(AdditionalIncludeDirectories) to make the header files included in <gtk-4.0/gtk/gtk.h> available. Then I ran a minimal example from ToshioCP's GTK4 Tutorial by Local Windows Debugger with Debug x86 mode:

#include <gtk-4.0/gtk/gtk.h>

int
main(int argc, char** argv) {
    GtkApplication* app;
    int stat;

    app = gtk_application_new("com.github.ToshioCP.pr1", G_APPLICATION_DEFAULT_FLAGS);
    stat = g_application_run(G_APPLICATION(app), argc, argv);
    g_object_unref(app);
    return stat;
}
```

But it failed
vsdebugwindow screenshot at gdataset.c.

I've tried to switch to the Release mode but the problem still occurs. I've also tried other examples from gtk.org and the problem always occurs. The Autos shows that the value of d->len is <Unable to read memory>.

Anyone has a hint?

Body:
I successfully installed gtk:x86-windows 4.6.8 by vcpkg. Then, I created a console application in Visual Studio 2022 on Windows 11 and added additional include directories as D:\Resources\vcpkg\installed\x86-windows\include\pango-1.0;D:\Resources\vcpkg\installed\x86-windows\include\cairo;D:\Resources\vcpkg\installed\x86-windows\include\gtk-4.0;D:\Resources\vcpkg\installed\x86-windows\include\glib-2.0;D:\Resources\vcpkg\installed\x86-windows\include\gio-win32-2.0;D:\Resources\vcpkg\installed\x86-windows\lib\glib-2.0\include;D:\Resources\vcpkg\installed\x86-windows\include\gdk-pixbuf-2.0;D:\Resources\vcpkg\installed\x86-windows\include\graphene-1.0;D:\Resources\vcpkg\installed\x86-windows\lib\graphene-1.0\include;D:\Resources\vcpkg\installed\x86-windows\include\harfbuzz;%(AdditionalIncludeDirectories) to make the header files included in <gtk-4.0/gtk/gtk.h> available. Then I ran a minimal example from ToshioCP's GTK4 Tutorial by Local Windows Debugger with Debug x86 mode:

#include <gtk-4.0/gtk/gtk.h>

int
main(int argc, char** argv) {
    GtkApplication* app;
    int stat;

    app = gtk_application_new("com.github.ToshioCP.pr1", G_APPLICATION_DEFAULT_FLAGS);
    stat = g_application_run(G_APPLICATION(app), argc, argv);
    g_object_unref(app);
    return stat;
}

But it failed
vsdebugwindow screenshot at gdataset.c.

I've tried to switch to the Release mode but the problem still occurs. I've also tried other examples from gtk.org and the problem always occurs. The Autos shows that the value of d->len is <Unable to read memory>.

Anyone has a hint?


问:
Request contains an invalid argument. while using Safe Browsing Api with Rails 7
I want to build this simple project where users can check url safety

using Safe Browsing API but It doesn't work correctly even though

I've tried multiple ways but no success.

This's my controller method below.

```<code>def check_url
    if params[:link].present?
      api_key = ENV[""]
      # Set up the request parameters
      url = params[:link]

      formatted_url = canonicalize_url(url)

      threat_types = ["MALWARE", "THREAT_TYPE_UNSPECIFIED", "SOCIAL_ENGINEERING", "UNWANTED_SOFTWARE", "POTENTIALLY_HARMFUL_APPLICATION"]
      platform_types = ["ANY_PLATFORM"]
      body = {
        client: {
          clientId: api_key,
          clientVersion: "1.0.0",
        },
        threatInfo: {
          threatTypes: threat_types,
          platformTypes: platform_types,
          threatEntryTypes: %w[URL THREAT_ENTRY_TYPE_UNSPECIFIED EXECUTABLE],
          threatEntries: [
            { url: formatted_url },
          ],
        },
      }

      # Set up the request headers
      headers = {
        "Content-Type" => "application/json",
        "Authorization" => "Bearer #{"api_key"}",
      }

      # Make the request to the Safe Browsing API
      response = HTTP.post(
        "https://safebrowsing.googleapis.com/v4/threatMatches:find",
        json: body,
        headers: headers,
      )

      # Check the response
      if response.code == 200
        data = JSON.parse(response.body)
        puts JSON.pretty_generate(data)
        if data["matches"].empty?
          # render plain: "The URL is safe"å

          puts "The URL is safe"
          @url_is_safe = true
        else
          # render plain: "The URL is not safe"
          puts "The URL is not safe"
        end
      else
        # render plain: "An error occurred"
        puts "An error occurred"
      end
    else
      puts "link variable is empty"
    end
    puts "Response code: #{response.code}"
    puts "Response body: #{response.body}"

    puts "Request parameters: #{body}"
    puts "Request headers: #{headers}"
  end
</code>```

I added a method to format :link variable, which is url in this case,

called canonicalize_url(url)

And this is the error shown in the logs

Print out responses as you can see in the code, so I can understand the errors.

Please let me know if you had any questions or requests, Thanks!

Body:
I want to build this simple project where users can check url safety

using Safe Browsing API but It doesn't work correctly even though

I've tried multiple ways but no success.

This's my controller method below.

def check_url
    if params[:link].present?
      api_key = ENV[""]
      # Set up the request parameters
      url = params[:link]

      formatted_url = canonicalize_url(url)

      threat_types = ["MALWARE", "THREAT_TYPE_UNSPECIFIED", "SOCIAL_ENGINEERING", "UNWANTED_SOFTWARE", "POTENTIALLY_HARMFUL_APPLICATION"]
      platform_types = ["ANY_PLATFORM"]
      body = {
        client: {
          clientId: api_key,
          clientVersion: "1.0.0",
        },
        threatInfo: {
          threatTypes: threat_types,
          platformTypes: platform_types,
          threatEntryTypes: %w[URL THREAT_ENTRY_TYPE_UNSPECIFIED EXECUTABLE],
          threatEntries: [
            { url: formatted_url },
          ],
        },
      }

      # Set up the request headers
      headers = {
        "Content-Type" => "application/json",
        "Authorization" => "Bearer #{"api_key"}",
      }

      # Make the request to the Safe Browsing API
      response = HTTP.post(
        "https://safebrowsing.googleapis.com/v4/threatMatches:find",
        json: body,
        headers: headers,
      )

      # Check the response
      if response.code == 200
        data = JSON.parse(response.body)
        puts JSON.pretty_generate(data)
        if data["matches"].empty?
          # render plain: "The URL is safe"å

          puts "The URL is safe"
          @url_is_safe = true
        else
          # render plain: "The URL is not safe"
          puts "The URL is not safe"
        end
      else
        # render plain: "An error occurred"
        puts "An error occurred"
      end
    else
      puts "link variable is empty"
    end
    puts "Response code: #{response.code}"
    puts "Response body: #{response.body}"

    puts "Request parameters: #{body}"
    puts "Request headers: #{headers}"
  end

I added a method to format :link variable, which is url in this case,

called canonicalize_url(url)

And this is the error shown in the logs

Print out responses as you can see in the code, so I can understand the errors.

Please let me know if you had any questions or requests, Thanks!


问:
How to pass MAKE variables to guile
I'm using GNU Make with Guile. How do I pass Make variables to Guile?

```<code>%.txt:
    @echo $* $(guile (string-upcase $*))
</code>```

What I want to see is this:

```<code>$ make foo.txt
foo FOO
</code>```

What I get is an error, Unbound variable: foo. My Guile invocation expands to (string-upcase foo), and foo is unbound. I can put quotes around the variable and then I get the result I'm looking for:

```<code>$(guile (string-upcase "$*"))
</code>```

This feels wrong. What if the string contains double quotes? It feels like there would be a more formal mechanism for passing values into Guile.

https://www.gnu.org/software/make/manual/html_node/Guile-Types.html goes into some detail about passing values from Guile to to Make, but I can't immediately see anything about passing them in.

Title: How to pass MAKE variables to guile

Body:
I'm using GNU Make with Guile. How do I pass Make variables to Guile?

%.txt:
    @echo $* $(guile (string-upcase $*))

What I want to see is this:

$ make foo.txt
foo FOO

What I get is an error, Unbound variable: foo. My Guile invocation expands to (string-upcase foo), and foo is unbound. I can put quotes around the variable and then I get the result I'm looking for:

$(guile (string-upcase "$*"))

This feels wrong. What if the string contains double quotes? It feels like there would be a more formal mechanism for passing values into Guile.

https://www.gnu.org/software/make/manual/html_node/Guile-Types.html goes into some detail about passing values from Guile to to Make, but I can't immediately see anything about passing them in.


问:
Transfer Private Key to other devices - Flutter Encryption
I am building an app which uses asymmetric encryption (each user has a private/public keypair)

Users use those keys to interact with encrypted data coming from the database.

Problem

User changes device.

The private key (stored locally in old device) is not available now.

What I know

I have read this post so I know that one way to do it is using a brain key and deriving it from a user's password.

Problem => I am also using Google & Apple Login, which don't require a password, so I can't derive the brain key.

What I Need

The easiest way to transfer or derive the private key from the other phone's local storage (QR Code? Custom API? How does WhatsApp do it?).

Or a way to derive the brain key with other types of logins (if possible). To find the equivalent of a password when using Google or Apple login APIs, something that is secret but constant for every login on every device.

Note: The app is already live and has ~500 users with different types of logins. Encryption will be introduced in the new version.

Solutions I have thought of

Transferring through QR Codes...The old device generates a QR Code that contains the private key. The new device scans that code and gets the key.

Nothing is transferred through the internet...so is this safe?

Another solution is to require an 'app paassword' no matter the login type. In that way you can derive a password with social logins too.

Will this be too much strain for the user? Do other apps use this method?


问:
Swift playground app on iPad udp send receive
I got the following class from https://medium.com/@michaelrobertellis/how-to-make-a-swift-ios-udp-listener-using-apples-network-framework-f7cef6f4e45f it’s about to receive UDP on iOS.

```<code>//
//  UDPListener.swift
//
//  Created by Michael Robert Ellis on 12/16/21.
//

import Foundation
import Network
import Combine

class UDPListener: ObservableObject {

    var listener: NWListener?
    var connection: NWConnection?
    var queue = DispatchQueue.global(qos: .userInitiated)
    /// New data will be place in this variable to be received by observers
    @Published private(set) public var messageReceived: Data?
    /// When there is an active listening NWConnection this will be `true`
    @Published private(set) public var isReady: Bool = false
    /// Default value `true`, this will become false if the UDPListener ceases listening for any reason
    @Published public var listening: Bool = true

    /// A convenience init using Int instead of NWEndpoint.Port
    convenience init(on port: Int) {
        self.init(on: NWEndpoint.Port(integerLiteral: NWEndpoint.Port.IntegerLiteralType(port)))
    }
    /// Use this init or the one that takes an Int to start the listener
    init(on port: NWEndpoint.Port) {
        let params = NWParameters.udp
        params.allowFastOpen = true
        self.listener = try? NWListener(using: params, on: port)
        self.listener?.stateUpdateHandler = { update in
            switch update {
            case .ready:
                self.isReady = true
                print("Listener connected to port \(port)")
            case .failed, .cancelled:
                // Announce we are no longer able to listen
                self.listening = false
                self.isReady = false
                print("Listener disconnected from port \(port)")
            default:
                print("Listener connecting to port \(port)...")
            }
        }
        self.listener?.newConnectionHandler = { connection in
            print("Listener receiving new message")
            self.createConnection(connection: connection)
        }
        self.listener?.start(queue: self.queue)
    }

    func createConnection(connection: NWConnection) {
        self.connection = connection
        self.connection?.stateUpdateHandler = { (newState) in
            switch (newState) {
            case .ready:
                print("Listener ready to receive message - \(connection)")
                self.receive()
            case .cancelled, .failed:
                print("Listener failed to receive message - \(connection)")
                // Cancel the listener, something went wrong
                self.listener?.cancel()
                // Announce we are no longer able to listen
                self.listening = false
            default:
                print("Listener waiting to receive message - \(connection)")
            }
        }
        self.connection?.start(queue: .global())
    }

    func receive() {
        self.connection?.receiveMessage { data, context, isComplete, error in
            if let unwrappedError = error {
                print("Error: NWError received in \(#function) - \(unwrappedError)")
                return
            }
            guard isComplete, let data = data else {
                print("Error: Received nil Data with context - \(String(describing: context))")
                return
            }
            self.messageReceived = data
            if self.listening {
                self.receive()
            }
        }
    }

    func cancel() {
        self.listening = false
        self.connection?.cancel()
    }
}
</code>```

I have no idea how to encapsulate it in the Swift playground app on iPad to make use of it.
Any lead will appreciate.

How to use this UDP listener class.

Body:
I got the following class from https://medium.com/@michaelrobertellis/how-to-make-a-swift-ios-udp-listener-using-apples-network-framework-f7cef6f4e45f it’s about to receive UDP on iOS.

//
//  UDPListener.swift
//
//  Created by Michael Robert Ellis on 12/16/21.
//

import Foundation
import Network
import Combine

class UDPListener: ObservableObject {

    var listener: NWListener?
    var connection: NWConnection?
    var queue = DispatchQueue.global(qos: .userInitiated)
    /// New data will be place in this variable to be received by observers
    @Published private(set) public var messageReceived: Data?
    /// When there is an active listening NWConnection this will be `true`
    @Published private(set) public var isReady: Bool = false
    /// Default value `true`, this will become false if the UDPListener ceases listening for any reason
    @Published public var listening: Bool = true

    /// A convenience init using Int instead of NWEndpoint.Port
    convenience init(on port: Int) {
        self.init(on: NWEndpoint.Port(integerLiteral: NWEndpoint.Port.IntegerLiteralType(port)))
    }
    /// Use this init or the one that takes an Int to start the listener
    init(on port: NWEndpoint.Port) {
        let params = NWParameters.udp
        params.allowFastOpen = true
        self.listener = try? NWListener(using: params, on: port)
        self.listener?.stateUpdateHandler = { update in
            switch update {
            case .ready:
                self.isReady = true
                print("Listener connected to port \(port)")
            case .failed, .cancelled:
                // Announce we are no longer able to listen
                self.listening = false
                self.isReady = false
                print("Listener disconnected from port \(port)")
            default:
                print("Listener connecting to port \(port)...")
            }
        }
        self.listener?.newConnectionHandler = { connection in
            print("Listener receiving new message")
            self.createConnection(connection: connection)
        }
        self.listener?.start(queue: self.queue)
    }

    func createConnection(connection: NWConnection) {
        self.connection = connection
        self.connection?.stateUpdateHandler = { (newState) in
            switch (newState) {
            case .ready:
                print("Listener ready to receive message - \(connection)")
                self.receive()
            case .cancelled, .failed:
                print("Listener failed to receive message - \(connection)")
                // Cancel the listener, something went wrong
                self.listener?.cancel()
                // Announce we are no longer able to listen
                self.listening = false
            default:
                print("Listener waiting to receive message - \(connection)")
            }
        }
        self.connection?.start(queue: .global())
    }

    func receive() {
        self.connection?.receiveMessage { data, context, isComplete, error in
            if let unwrappedError = error {
                print("Error: NWError received in \(#function) - \(unwrappedError)")
                return
            }
            guard isComplete, let data = data else {
                print("Error: Received nil Data with context - \(String(describing: context))")
                return
            }
            self.messageReceived = data
            if self.listening {
                self.receive()
            }
        }
    }

    func cancel() {
        self.listening = false
        self.connection?.cancel()
    }
}

I have no idea how to encapsulate it in the Swift playground app on iPad to make use of it.
Any lead will appreciate.

How to use this UDP listener class.


问:
Set Default Zoom in Flutter Web to 150%
Is there anyway to set the default zoom of a flutter web app to 150% by default?

I tried Viewport and tried to edit the Index.html file but it didn't work because Flutter overrides those already.

Title: Set Default Zoom in Flutter Web to 150%


问:
Error while adding scopes to ServiceAccountCredentials
I started to write my code to learn how to work with Google Cloud and Google Sheets.
But from the beginning this problem appeared:

```<code>Argument of type "list[str]" cannot be assigned to parameter "scopes" of type "str" in function "from_json_keyfile_name"
</code>```

my code:

from oauth2client.service_account import ServiceAccountCredentials

credentials_file = 'creds.json'
scope = ['https://www.googleapis.com/auth/spreadsheets',
     'https://www.googleapis.com/auth/drive']

credentials = ServiceAccountCredentials.from_json_keyfile_name(
     credentials_file, scope)
```

As I saw on the Internet everyone use list[str] for scopes parameter. Am I wrong?
Please help me:(

I tried to write scopes respectively but there are other parameters.
Also I checked code from: https://github.com/alexey-goloburdin/youtube-google-sheets-python/blob/master/run.py and tried to write the same code, but it did not solved the error

Body:
I started to write my code to learn how to work with Google Cloud and Google Sheets.
But from the beginning this problem appeared:

Argument of type "list[str]" cannot be assigned to parameter "scopes" of type "str" in function "from_json_keyfile_name"

my code:

from oauth2client.service_account import ServiceAccountCredentials

credentials_file = 'creds.json'
scope = ['https://www.googleapis.com/auth/spreadsheets',
     'https://www.googleapis.com/auth/drive']

credentials = ServiceAccountCredentials.from_json_keyfile_name(
     credentials_file, scope)

As I saw on the Internet everyone use list[str] for scopes parameter. Am I wrong?
Please help me:(

I tried to write scopes respectively but there are other parameters.
Also I checked code from: https://github.com/alexey-goloburdin/youtube-google-sheets-python/blob/master/run.py and tried to write the same code, but it did not solved the error


问:
Building a C++ project across different branches
My project has more than 1000 files. In this let's say there is a file A.cpp & A.h. When I move to a new branch on my machine & I compile, it compiles everything including A.cpp  even though I had just compiled A.cpp on an old branch.
I heard some companies while downloading cpp files also downloads the corresponding .obj & .lib files, there by speeding up the compilation very fast .
Is this true? What is it called so that I can to incorporate it

I started with https://interrupt.memfault.com/blog/improving-compilation-times-c-cpp-projects but the ideas there are not on this line of thought.


问:
Child[1] in XPATH returns mulltiple nodes
Let's say I have the following HTML layout:

```<code><div>
    <button text='main' .../>
    <button .../>
</div>
</code>```

Now let's say that the task is to find the button with text 'main' then go to the first ancestor div node and then go back down to the same 'main' button.

If I write the following:

```<code>find_elements(By.XPATH, "//button[text()='main']//ancestor::div[1]//child::button[1]")
</code>```

It returns both buttons that are children of the div. Why is that?

It returns the first button (which actually I need), only if I use the absolute path in the end:

```<code>find_elements(By.XPATH, "//button[text()='main']//ancestor::div[1]/child:button[1]")
</code>```

Is it possible to get the first button going down the hierarchy relying on the relative path?

Maybe I don't understand something, but it seems like magic for me. If we remake the layout like this:

```<code><div>
    <button text='main' .../>
    <button .../>
    <a ...>
        <button />
    </a>
</div>
</code>```

and then take children of div like this:

```<code>find_elements(By.XPATH, "//button[text()='main']//ancestor::div[1]//child::button")
</code>```

it returns all three buttons, despite that I have read in a lot of articles that //child returns immediate child! What is going on here?

Body:
Let's say I have the following HTML layout:

    <button text='main' .../>
    <button .../>

Now let's say that the task is to find the button with text 'main' then go to the first ancestor div node and then go back down to the same 'main' button.

If I write the following:

find_elements(By.XPATH, "//button[text()='main']//ancestor::div[1]//child::button[1]")

It returns both buttons that are children of the div. Why is that?

It returns the first button (which actually I need), only if I use the absolute path in the end:

find_elements(By.XPATH, "//button[text()='main']//ancestor::div[1]/child:button[1]")

Is it possible to get the first button going down the hierarchy relying on the relative path?

Maybe I don't understand something, but it seems like magic for me. If we remake the layout like this:

    <button text='main' .../>
    <button .../>

        <button />

and then take children of div like this:

find_elements(By.XPATH, "//button[text()='main']//ancestor::div[1]//child::button")

it returns all three buttons, despite that I have read in a lot of articles that //child returns immediate child! What is going on here?


问:
I am trying to write code which places a buy and a sell order at the pre-market high and low from the hour before the DAX open in pine script
Here is the code, I am new to coding so it may not be very correct or make a lot of sense. It compiles but I am having issues as the code still places orders after "0903"am, I only want orders to be placed for the first 2 minutes from the open of the market.

```<code>
//@version=5
strategy(title="Session high/low boxes", overlay=true)

// InSession() returns 'true' when the current bar happens inside
// the specified session, corrected for the given time zone (optional).
// Returns 'false' when the bar doesn't happen in that time period,
// or when the chart's time frame is 1 day or higher.

InSession(sessionTime, sessionTimeZone=syminfo.timezone) => not na(time(timeframe.period, sessionTime, sessionTimeZone))
t = time(timeframe.period, "0900-0902", "GMT+1")
z = time("0903")
// STEP 1:
// Define custom session trading times with inputs
sessionTime = input.session("0800-0900", title="Session time")
sessionZone = input.string("GMT+1", title="Session time zone")

// Other inputs for the boxes' visual appearance
boxBorderSize   = input.int(2, title="Box border size", minval=0)
upBoxColor      = input.color(color.new(color.green, 85), title="Up box")
upBorderColor   = input.color(color.green, title="Up border")
downBoxColor    = input.color(color.new(color.red, 85), title="Down box")
downBorderColor = input.color(color.red, title="Down border")

// Create variables
var sessionHighPrice = 0.0
var sessionLowPrice  = 0.0
var sessionOpenPrice = 0.0
var box sessionBox = na

// STEP 2:
// See if the session is currently active and just started
inSession    = InSession(sessionTime, sessionZone) and timeframe.isintraday
sessionStart = inSession and not inSession[1]

// STEP 3:
// When a new session starts, set the session high and low to the data
// of the bar in the session.
if sessionStart
    sessionHighPrice := high
    sessionLowPrice  := low
    sessionOpenPrice := open
// Else, during the session, track the highest high and lowest low
else if inSession
    sessionHighPrice := math.max(sessionHighPrice, high)
    sessionLowPrice  := math.min(sessionLowPrice, low)

// STEP 4:
// When a session begins, make a new box for that session
if sessionStart
    sessionBox := box.new(left=bar_index, top=na, right=na, bottom=na,
         border_width=boxBorderSize)

// STEP 5:
// During the session, update that session's existing box
if inSession
    box.set_top(sessionBox, sessionHighPrice)
    box.set_bottom(sessionBox, sessionLowPrice)

    box.set_right(sessionBox, bar_index + 1)

    //See if bar closed higher than session open. When it did, make
    //box green (and use red otherwise).
    if close > sessionOpenPrice
        box.set_bgcolor(sessionBox, upBoxColor)
        box.set_border_color(sessionBox, upBorderColor)
    else
        box.set_bgcolor(sessionBox, downBoxColor)
        box.set_border_color(sessionBox, downBorderColor)

if time == t
    var stoploss1 = sessionHighPrice - 9
    var stoploss2 = sessionLowPrice + 9
    var takeprofit1 = sessionHighPrice + 9.55
    var takeprofit2 = sessionLowPrice - 10.51

    strategy.entry("Enter Long", strategy.long, limit=sessionHighPrice)
    strategy.entry("Enter Short", strategy.short, stop=sessionLowPrice)

    //exit
    strategy.exit("Enter Long", stop=stoploss1, limit=takeprofit1)
    strategy.exit("Enter Short", stop=stoploss2, limit=takeprofit2)

//Remove orders at 9:02 am if they have not been placed yet.
else if time >= z
    strategy.cancel("Enter Long")
    strategy.cancel("Enter Short")

</code>```

Thank you!!!

I tried changing all the variables around and use a time frame instead of a single time so that orders were not placed after 0903, however this didn't work

Body:
Here is the code, I am new to coding so it may not be very correct or make a lot of sense. It compiles but I am having issues as the code still places orders after "0903"am, I only want orders to be placed for the first 2 minutes from the open of the market.

//@version=5
strategy(title="Session high/low boxes", overlay=true)

// InSession() returns 'true' when the current bar happens inside
// the specified session, corrected for the given time zone (optional).
// Returns 'false' when the bar doesn't happen in that time period,
// or when the chart's time frame is 1 day or higher.

InSession(sessionTime, sessionTimeZone=syminfo.timezone) => not na(time(timeframe.period, sessionTime, sessionTimeZone))
t = time(timeframe.period, "0900-0902", "GMT+1")
z = time("0903")
// STEP 1:
// Define custom session trading times with inputs
sessionTime = input.session("0800-0900", title="Session time")
sessionZone = input.string("GMT+1", title="Session time zone")

// Other inputs for the boxes' visual appearance
boxBorderSize   = input.int(2, title="Box border size", minval=0)
upBoxColor      = input.color(color.new(color.green, 85), title="Up box")
upBorderColor   = input.color(color.green, title="Up border")
downBoxColor    = input.color(color.new(color.red, 85), title="Down box")
downBorderColor = input.color(color.red, title="Down border")

// Create variables
var sessionHighPrice = 0.0
var sessionLowPrice  = 0.0
var sessionOpenPrice = 0.0
var box sessionBox = na

// STEP 2:
// See if the session is currently active and just started
inSession    = InSession(sessionTime, sessionZone) and timeframe.isintraday
sessionStart = inSession and not inSession[1]

// STEP 3:
// When a new session starts, set the session high and low to the data
// of the bar in the session.
if sessionStart
    sessionHighPrice := high
    sessionLowPrice  := low
    sessionOpenPrice := open
// Else, during the session, track the highest high and lowest low
else if inSession
    sessionHighPrice := math.max(sessionHighPrice, high)
    sessionLowPrice  := math.min(sessionLowPrice, low)

// STEP 4:
// When a session begins, make a new box for that session
if sessionStart
    sessionBox := box.new(left=bar_index, top=na, right=na, bottom=na,
         border_width=boxBorderSize)

// STEP 5:
// During the session, update that session's existing box
if inSession
    box.set_top(sessionBox, sessionHighPrice)
    box.set_bottom(sessionBox, sessionLowPrice)

    box.set_right(sessionBox, bar_index + 1)

    //See if bar closed higher than session open. When it did, make
    //box green (and use red otherwise).
    if close > sessionOpenPrice
        box.set_bgcolor(sessionBox, upBoxColor)
        box.set_border_color(sessionBox, upBorderColor)
    else
        box.set_bgcolor(sessionBox, downBoxColor)
        box.set_border_color(sessionBox, downBorderColor)

if time == t
    var stoploss1 = sessionHighPrice - 9
    var stoploss2 = sessionLowPrice + 9
    var takeprofit1 = sessionHighPrice + 9.55
    var takeprofit2 = sessionLowPrice - 10.51

    strategy.entry("Enter Long", strategy.long, limit=sessionHighPrice)
    strategy.entry("Enter Short", strategy.short, stop=sessionLowPrice)

    //exit
    strategy.exit("Enter Long", stop=stoploss1, limit=takeprofit1)
    strategy.exit("Enter Short", stop=stoploss2, limit=takeprofit2)

//Remove orders at 9:02 am if they have not been placed yet.
else if time >= z
    strategy.cancel("Enter Long")
    strategy.cancel("Enter Short")

Thank you!!!

I tried changing all the variables around and use a time frame instead of a single time so that orders were not placed after 0903, however this didn't work


问:
Highlight active parent menu item and not highlight nonactive children menu items
I'm trying to get the music note current page indicator to not be on the child elements when the parent element is active. It works fine when a submenu page is active with the submenu element that is currently active and its parent element having the indicator on them. In the attached picture I want the music notes to not be on the submenu pages since the parent About page is active.

Here's the JS for the navigation:

```<code>( function() {
    const siteNavigation = document.getElementById( 'site-navigation' );

    // Return early if the navigation doesn't exist.
    if ( ! siteNavigation ) {
        return;
    }

    const button = siteNavigation.getElementsByTagName( 'button' )[ 0 ];

    // Return early if the button doesn't exist.
    if ( 'undefined' === typeof button ) {
        return;
    }

    const menu = siteNavigation.getElementsByTagName( 'ul' )[ 0 ];

    // Hide menu toggle button if menu is empty and return early.
    if ( 'undefined' === typeof menu ) {
        button.style.display = 'none';
        return;
    }

    if ( ! menu.classList.contains( 'nav-menu' ) ) {
        menu.classList.add( 'nav-menu' );
    }

    // Toggle the .toggled class and the aria-expanded value each time the button is clicked.
    button.addEventListener( 'click', function() {
        siteNavigation.classList.toggle( 'toggled' );

        if ( button.getAttribute( 'aria-expanded' ) === 'true' ) {
            button.setAttribute( 'aria-expanded', 'false' );
        } else {
            button.setAttribute( 'aria-expanded', 'true' );
        }
    } );

    // Remove the .toggled class and set aria-expanded to false when the user clicks outside the navigation.
    document.addEventListener( 'click', function( event ) {
        const isClickInside = siteNavigation.contains( event.target );

        if ( ! isClickInside ) {
            siteNavigation.classList.remove( 'toggled' );
            button.setAttribute( 'aria-expanded', 'false' );
        }
    } );

    // Get all the link elements within the menu.
    const links = menu.getElementsByTagName( 'a' );

    // Get all the link elements with children within the menu.
    const linksWithChildren = menu.querySelectorAll( '.menu-item-has-children > a, .page_item_has_children > a' );

    // Toggle focus each time a menu link is focused or blurred.
    for ( const link of links ) {
        link.addEventListener( 'focus', toggleFocus, true );
        link.addEventListener( 'blur', toggleFocus, true );
    }

    // Toggle focus each time a menu link with children receive a touch event.
    for ( const link of linksWithChildren ) {
        link.addEventListener( 'touchstart', toggleFocus, false );
    }

    /**
     * Sets or removes .focus class on an element.
     */
    function toggleFocus() {
        if ( event.type === 'focus' || event.type === 'blur' ) {
            let self = this;
            // Move up through the ancestors of the current link until we hit .nav-menu.
            while ( ! self.classList.contains( 'nav-menu' ) ) {
                // On li elements toggle the class .focus.
                if ( 'li' === self.tagName.toLowerCase() ) {
                    self.classList.toggle( 'focus' );
                }
                self = self.parentNode;
            }
        }

        if ( event.type === 'touchstart' ) {
            const menuItem = this.parentNode;
            event.preventDefault();
            for ( const link of menuItem.parentNode.children ) {
                if ( menuItem !== link ) {
                    link.classList.remove( 'focus' );
                }
            }
            menuItem.classList.toggle( 'focus' );
        }
    }

</code>```

Here's the css:

```<code>li.current-menu-item a:before, li.current-menu-ancestor> a:before{
    content: "";
    background-image: url('https://vailyouthsymphony.org/wp-content/uploads/2022/03/Music-note-1.png');
    background-size: 100% 100% ;
    display: inline-block;
    height: 1em;
    width: 1em;
}
</code>```

The actual website is vailyouthsymphony.org if you want to visit it.

This is some JS troubleshooting I tried: The main thing I was trying to do was remove the "current-menu-item" from the sub menu items since logically that should remove the indicator from that but that didn't work without the indicator not showing up when a sub page was the active page.

```<code>    var submenuElem = document.getElementsByClassName('sub-menu');
    var childrenElem = submenuElem.getElementsByClassName('menu-item') ;
        var check = submenuElem[ 0 ].children;
       console.log(check [ 2 ].classList);
       console.log(submenuElem[ 0 ].children.length)
       console.log(submenuElem[ 0 ].classList);
       if( parentElem.classList.contains('current-menu-item') ){
       submenuElem[ 0 ].children [ 2 ].classList.remove('current-menu-item');

           for (var i = 0; i < submenuElem[ 0 ].children.length; i++) {
        var babyElem = submenuElem[ 0 ].children;
        babyElem[ i ].classList.remove('current-menu-item');
 }
 };

</code>```

I tried changing some of the css selectors too to no avail.
If you need more information or clarification let me know. I'd love some help with this!

Body:
I'm trying to get the music note current page indicator to not be on the child elements when the parent element is active. It works fine when a submenu page is active with the submenu element that is currently active and its parent element having the indicator on them. In the attached picture I want the music notes to not be on the submenu pages since the parent About page is active.

Here's the JS for the navigation:

( function() {
    const siteNavigation = document.getElementById( 'site-navigation' );

    // Return early if the navigation doesn't exist.
    if ( ! siteNavigation ) {
        return;
    }

    const button = siteNavigation.getElementsByTagName( 'button' )[ 0 ];

    // Return early if the button doesn't exist.
    if ( 'undefined' === typeof button ) {
        return;
    }

    const menu = siteNavigation.getElementsByTagName( 'ul' )[ 0 ];

    // Hide menu toggle button if menu is empty and return early.
    if ( 'undefined' === typeof menu ) {
        button.style.display = 'none';
        return;
    }

    if ( ! menu.classList.contains( 'nav-menu' ) ) {
        menu.classList.add( 'nav-menu' );
    }

    // Toggle the .toggled class and the aria-expanded value each time the button is clicked.
    button.addEventListener( 'click', function() {
        siteNavigation.classList.toggle( 'toggled' );

        if ( button.getAttribute( 'aria-expanded' ) === 'true' ) {
            button.setAttribute( 'aria-expanded', 'false' );
        } else {
            button.setAttribute( 'aria-expanded', 'true' );
        }
    } );

    // Remove the .toggled class and set aria-expanded to false when the user clicks outside the navigation.
    document.addEventListener( 'click', function( event ) {
        const isClickInside = siteNavigation.contains( event.target );

        if ( ! isClickInside ) {
            siteNavigation.classList.remove( 'toggled' );
            button.setAttribute( 'aria-expanded', 'false' );
        }
    } );

    // Get all the link elements within the menu.
    const links = menu.getElementsByTagName( 'a' );

    // Get all the link elements with children within the menu.
    const linksWithChildren = menu.querySelectorAll( '.menu-item-has-children > a, .page_item_has_children > a' );

    // Toggle focus each time a menu link is focused or blurred.
    for ( const link of links ) {
        link.addEventListener( 'focus', toggleFocus, true );
        link.addEventListener( 'blur', toggleFocus, true );
    }

    // Toggle focus each time a menu link with children receive a touch event.
    for ( const link of linksWithChildren ) {
        link.addEventListener( 'touchstart', toggleFocus, false );
    }

    /**
     * Sets or removes .focus class on an element.
     */
    function toggleFocus() {
        if ( event.type === 'focus' || event.type === 'blur' ) {
            let self = this;
            // Move up through the ancestors of the current link until we hit .nav-menu.
            while ( ! self.classList.contains( 'nav-menu' ) ) {
                // On li elements toggle the class .focus.
                if ( 'li' === self.tagName.toLowerCase() ) {
                    self.classList.toggle( 'focus' );
                }
                self = self.parentNode;
            }
        }

        if ( event.type === 'touchstart' ) {
            const menuItem = this.parentNode;
            event.preventDefault();
            for ( const link of menuItem.parentNode.children ) {
                if ( menuItem !== link ) {
                    link.classList.remove( 'focus' );
                }
            }
            menuItem.classList.toggle( 'focus' );
        }
    }

Here's the css:

li.current-menu-item a:before, li.current-menu-ancestor> a:before{
    content: "";
    background-image: url('https://vailyouthsymphony.org/wp-content/uploads/2022/03/Music-note-1.png');
    background-size: 100% 100% ;
    display: inline-block;
    height: 1em;
    width: 1em;
}

The actual website is vailyouthsymphony.org if you want to visit it.

This is some JS troubleshooting I tried: The main thing I was trying to do was remove the "current-menu-item" from the sub menu items since logically that should remove the indicator from that but that didn't work without the indicator not showing up when a sub page was the active page.

    var submenuElem = document.getElementsByClassName('sub-menu');
    var childrenElem = submenuElem.getElementsByClassName('menu-item') ;
        var check = submenuElem[ 0 ].children;
       console.log(check [ 2 ].classList);
       console.log(submenuElem[ 0 ].children.length)
       console.log(submenuElem[ 0 ].classList);
       if( parentElem.classList.contains('current-menu-item') ){
       submenuElem[ 0 ].children [ 2 ].classList.remove('current-menu-item');

           for (var i = 0; i < submenuElem[ 0 ].children.length; i++) {
        var babyElem = submenuElem[ 0 ].children;
        babyElem[ i ].classList.remove('current-menu-item');
 }
 };

I tried changing some of the css selectors too to no avail.
If you need more information or clarification let me know. I'd love some help with this!


问:
Getting bottlenecked using graph edit distance for networkx graphs. Any good alternatives?
I am currently getting bottlenecked using graph edit distance for networkx graphs. My code currently looks like this (I am appending 50 pairwise graph analysis results to a list of dictionaries).

```<code>lst_of_dct = []
for i in range(len(pair_list)):
    dict = {}
    # extract edges values for graphs 1 & 2
    edge_1 = [list(e) for e in pair_list[i][0].edges]
    edge_2 = [list(e) for e in pair_list[i][1].edges]
    dict["my_graph1"] = edge_1
    dict["my_graph2"] = edge_2
    node1 = pair_list[i][0].nodes
    node2 = pair_list[i][1].nodes
    dict["labels_1"] = node1
    dict["labels_2"] = node2
    for v in nx.optimize_graph_edit_distance(pair_list[i][0], pair_list[i][1]):
        ged = v
    #ged = nx.graph_edit_distance(pair_list[i][0], pair_list[i][1])
    dict["ged"] = ged
    lst_of_dct.append(dict)
    print('1')
</code>```

After about 3 iterations of my for loop, it just gets stuck calculating the fourth GED. I calculated the GED individually on a scratch sheet to see how long it takes without the for loop, and the graph pair for the fourth iteration only takes ~3 seconds. I was just wondering why am I getting bottlenecked at the fourth iteration if it only takes ~3 seconds to calculate without a for loop?

I guess this really isn't a what have I tried problem. Just a matter of why is this happening? Things I could try but would be kind of annoying would be to iterate 5 for loops at a time... which would result in 20 different for loops appending the same dictionary again and again. I think this is not a great idea, but this could be a last result if it comes down to it. I could just hard-code it in, but I would rather not have to do this because I am expected to do this same procedure for a much larger dataset in the future.

Body:
I am currently getting bottlenecked using graph edit distance for networkx graphs. My code currently looks like this (I am appending 50 pairwise graph analysis results to a list of dictionaries).

lst_of_dct = []
for i in range(len(pair_list)):
    dict = {}
    # extract edges values for graphs 1 & 2
    edge_1 = [list(e) for e in pair_list[i][0].edges]
    edge_2 = [list(e) for e in pair_list[i][1].edges]
    dict["my_graph1"] = edge_1
    dict["my_graph2"] = edge_2
    node1 = pair_list[i][0].nodes
    node2 = pair_list[i][1].nodes
    dict["labels_1"] = node1
    dict["labels_2"] = node2
    for v in nx.optimize_graph_edit_distance(pair_list[i][0], pair_list[i][1]):
        ged = v
    #ged = nx.graph_edit_distance(pair_list[i][0], pair_list[i][1])
    dict["ged"] = ged
    lst_of_dct.append(dict)
    print('1')

After about 3 iterations of my for loop, it just gets stuck calculating the fourth GED. I calculated the GED individually on a scratch sheet to see how long it takes without the for loop, and the graph pair for the fourth iteration only takes ~3 seconds. I was just wondering why am I getting bottlenecked at the fourth iteration if it only takes ~3 seconds to calculate without a for loop?

I guess this really isn't a what have I tried problem. Just a matter of why is this happening? Things I could try but would be kind of annoying would be to iterate 5 for loops at a time... which would result in 20 different for loops appending the same dictionary again and again. I think this is not a great idea, but this could be a last result if it comes down to it. I could just hard-code it in, but I would rather not have to do this because I am expected to do this same procedure for a much larger dataset in the future.


问:
How to fix deprecated error utf8_encode()
In php 8.2.0 function utf8_encode() is deprecated

Replace with this function

iconv('ISO-8859-1', 'UTF-8', $string);

In API libraries etc this will work

It corrects the utf8_encode() deprecated function error


问:
SpringBatch RepositoryItemReader is not recoginizing the coustom JPA method with @Query?
SpringBatch RepositoryItemReader is not recognizing the custom JPA method with @Query?

@Bean
@StepScope
@Primary
public RepositoryItemReader<KPOMBatchJob> kpomBatchJobItemReader() {
    log.info("Kpom RepositoryItemReader in use");
    RepositoryItemReader<KPOMBatchJob> reader = new RepositoryItemReader<KPOMBatchJob>();
    reader.setRepository(kpomBatchJobDAO);
    reader.setMethodName("filterByAppId");
    return getRepositoryItemReader(reader, "bio");
}
```
<p><code>FYI</code>,</p>
<pre class="lang-java prettyprint-override"><code>@Repository
public interface KPOMBatchJobDAO extends JpaRepository<KPOMBatchJob, Serializable> {
    @Query("select k from KPOMBatchJob k where k.appId in (select CONCAT('A-', s.appId) from Application s)")
    List<KPOMBatchJob> filterByAppId();
}
</code>```

Call to method filterByAppId works fine, but if I try to use this method in spring batch RepositoryItemReader, then it's not working.

Am I missing anything?

Body:
SpringBatch RepositoryItemReader is not recognizing the custom JPA method with @Query?

@Bean
@StepScope
@Primary
public RepositoryItemReader<KPOMBatchJob> kpomBatchJobItemReader() {
    log.info("Kpom RepositoryItemReader in use");
    RepositoryItemReader<KPOMBatchJob> reader = new RepositoryItemReader<KPOMBatchJob>();
    reader.setRepository(kpomBatchJobDAO);
    reader.setMethodName("filterByAppId");
    return getRepositoryItemReader(reader, "bio");
}

FYI,

@Repository
public interface KPOMBatchJobDAO extends JpaRepository<KPOMBatchJob, Serializable> {
    @Query("select k from KPOMBatchJob k where k.appId in (select CONCAT('A-', s.appId) from Application s)")
    List<KPOMBatchJob> filterByAppId();
}

Call to method filterByAppId works fine, but if I try to use this method in spring batch RepositoryItemReader, then it's not working.

Am I missing anything?