Saturday, December 18, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Use generic stored procedure with dapper in Asp.net core

Posted: 18 Dec 2021 08:28 AM PST

I want a sample code that has CRUD operations with Generic Store Procedure with dapper in asp.net core. Can you help me?

Why my app works in a strange way on iphones

Posted: 18 Dec 2021 08:28 AM PST

do Iphones in Japan differ from rest of the world? I have made an App. It looks good on all Iphone physical devices and works fine. But today i tried to install my app on i phone that was bought in japan. And my app is not working as it should. All the buttons changed their color and not all the buttons are active. This is so strange.

Libcurl - What does "curl_multi_perform"

Posted: 18 Dec 2021 08:27 AM PST

I'm trying to understand how curl_multi_perform works. The documentation says that:

This function performs transfers on all the added handles that need attention in an non-blocking fashion. The easy handles have previously been added to the multi handle with curl_multi_add_handle.

When an application has found out there's data available for the multi_handle or a timeout has elapsed, the application should call this function to read/write whatever there is to read or write right now etc.

Question 1: What does the "application should call" mean? How can an application cause something? Did you mean the programmer should call ?

OK, I found two simple usage examples - "curl_multi_perform":

1 - https://everything.curl.dev/libcurl/drive/multi

int transfers_running;  do {     curl_multi_wait ( multi_handle, NULL, 0, 1000, NULL);     curl_multi_perform ( multi_handle, &transfers_running );  } while (transfers_running);  

2 - enter link description here

int still_running;  do {    CURLMcode mc = curl_multi_perform(multi_handle, &still_running);       if(!mc && still_running)      /* wait for activity, timeout or "nothing" */      mc = curl_multi_poll(multi_handle, NULL, 0, 1000, NULL);       if(mc) {      fprintf(stderr, "curl_multi_poll() failed, code %d.\n", (int)mc);      break;    }     /* if there are still transfers, loop! */  } while(still_running);  

-Firstly:

  • in the first example curl_multi_perform is called after curl_multi_wait.
  • in the second example curl_multi_perform is called before curl_multi_wait.

Nothing is clear.

  • Secondly:

Why do I need to call curl_multi_perform in a loop ?? I do not understand.

Why is one call not enough ?

error Property 'getItem' does not exist in type 'string'.ts(2339)

Posted: 18 Dec 2021 08:27 AM PST

I'm using firebase to register links on a website, I'm trying to pass the uuid to create a sub collection, but without success, what can it be??

constructor(private af: AngularFirestore) {}    async add(urls: Urls, uuid: string): Promise<void> {      await this.af.collection(`${this.collection}/${uuid.getItem('idCustomer')}/menu`).add({ ...urls });        await this.getUrls(`${this.collection}/${uuid.getItem('idCustomer')}/menu`);  }  

Need help figuring out how to make just the text portion of the popup window vertically scrollable

Posted: 18 Dec 2021 08:26 AM PST

I'm trying to learn CSS and web design and I am stuck on how to make this work. I have a page that calls up a pop-up information window. However, there is a lot of text and it ends up pushing the window out of frame and therefore a user can't access the 'X' to close the window. I'd like to make it so the window doesn't expand, but the text portion can be vertically scrolled through. I've tried many various things dealing with overflow and overflow-y, but nothing seems to work. The HTML part of the code is:

    <div class="popup" id="popup-experience">                  <div class="popup__content">                      <div class="popup__left">                          <img src="img/some.jpg" alt="some photo" class="popup__img">                          <!-- <img src="img/some-other.jpg" alt="some other photo" class="popup__img"> -->                      </div>                      <div class="popup__right">                          <a href="#section-resume" class="popup__close">&times;</a>                          <h2 class="heading-secondary u-margin-bottom-small">Work Experience</h2>                          <h3 class="heading-tertiary u-margin-bottom-small">Below is a list of my experience</h3>                          <p class="popup__text">                              Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Sed blandit libero volutpat sed cras ornare arcu dui. Ultrices sagittis orci a scelerisque purus semper eget duis. Et netus et malesuada fames ac turpis egestas sed tempus. Mauris a diam maecenas sed. Eget dolor morbi non arcu risus. Volutpat sed cras ornare arcu dui vivamus arcu felis bibendum. Bibendum ut tristique et egestas quis ipsum suspendisse ultrices. Venenatis tellus in metus vulputate eu scelerisque. Orci nulla pellentesque dignissim enim sit. Vestibulum sed arcu non odio euismod. Dolor morbi non arcu risus. Rhoncus est pellentesque elit ullamcorper dignissim cras. Cursus mattis molestie a iaculis. Phasellus egestas tellus rutrum tellus pellentesque eu tincidunt tortor. Felis imperdiet proin fermentum leo vel.    Auctor elit sed vulputate mi sit amet mauris commodo quis. Diam volutpat commodo sed egestas. Libero id faucibus nisl tincidunt eget nullam. Sed arcu non odio euismod lacinia at quis risus. Suscipit tellus mauris a diam maecenas sed enim ut. Molestie a iaculis at erat pellentesque adipiscing commodo elit. Nulla malesuada pellentesque elit eget gravida cum. Risus viverra adipiscing at in tellus integer feugiat scelerisque varius. Sagittis vitae et leo duis ut diam quam nulla porttitor. Amet consectetur adipiscing elit pellentesque habitant morbi tristique senectus. Est placerat in egestas erat imperdiet sed. A diam maecenas sed enim ut sem viverra aliquet. Enim eu turpis egestas pretium.    Adipiscing commodo elit at imperdiet dui accumsan sit amet. Turpis massa tincidunt dui ut ornare lectus sit. Venenatis a condimentum vitae sapien pellentesque habitant morbi tristique senectus. Non pulvinar neque laoreet suspendisse interdum. Nullam eget felis eget nunc lobortis mattis. Dictum fusce ut placerat orci nulla pellentesque. Id leo in vitae turpis massa sed elementum tempus egestas. Ultrices tincidunt arcu non sodales neque. Aliquet lectus proin nibh nisl. Morbi tincidunt ornare massa eget egestas purus viverra accumsan. Hac habitasse platea dictumst quisque sagittis purus sit. Nibh cras pulvinar mattis nunc sed blandit libero. Quis viverra nibh cras pulvinar. Sapien faucibus et molestie ac. Sit amet justo donec enim diam vulputate ut. Commodo sed egestas egestas fringilla phasellus faucibus. Enim nunc faucibus a pellentesque sit. Aenean pharetra magna ac placerat.                          </p>                          <a href="#popup-nextpage" class="btn btn--green">Go to next area &rarr;</a>                      </div>                  </div>              </div>  

The CSS is:

.popup {      height: 100vh;      width: 100%;        overflow:auto;      position: fixed;      top: 0;      left: 0;      background-color: rgba($color-black, .8);      z-index: 9999;      opacity: 0;      visibility: hidden;      transition: all .3s;        @supports (-webkit-backdrop-filter: blur(10px)) or (backdrop-filter: blur(10px)) {          -webkit-backdrop-filter: blur(10px);          backdrop-filter: blur(10px);          background-color: rgba($color-black, .3);      }        &__content {          @include absCenter;            width: 75%;          background-color: $color-white;          box-shadow: 0 2rem 4rem rgba($color-black, .2);          border-radius: 3px;          display: table;          overflow: hidden;          opacity: 0;          transform: translate(-50%, -50%) scale(.25);          transition: all .5s .2s;      }        &__left {          width: 33.333333%;          display: table-cell;      }        &__right {          width: 66.6666667%;          display: table-cell;          vertical-align: middle;          padding: 3rem 5rem;      }        &__img {          display: block;          width: 100%;      }        &__text {          font-size: 1.4rem;          margin-bottom: 4rem;            -moz-column-count: 2;          -moz-column-gap: 4rem; //1em = 14px;          -moz-column-rule: 1px solid $color-grey-light-2;            column-count: 2;          column-gap: 4rem; //1em = 14px;          column-rule: 1px solid $color-grey-light-2;            -moz-hyphens: auto;          -ms-hyphens: auto;          -webkit-hyphens: auto;          hyphens: auto;      }        &__text-small{          // font-size: 1.09rem;          font-size: 1.2rem;          margin-bottom: 4rem;            -moz-column-count: 2;          -moz-column-gap: 4rem; //1em = 14px;          -moz-column-rule: 1px solid $color-grey-light-2;            column-count: 2;          column-gap: 4rem; //1em = 14px;          column-rule: 1px solid $color-grey-light-2;            -moz-hyphens: auto;          -ms-hyphens: auto;          -webkit-hyphens: auto;          hyphens: auto;      }        //Open states      &:target {          opacity: 1;          visibility: visible;      }        &:target &__content {          opacity: 1;          transform: translate(-50%, -50%) scale(1);      }        &__close {          &:link,          &:visited {              color: $color-grey-dark;              position: absolute;              top: 2.5rem;              right: 2.5rem;              font-size: 3rem;              text-decoration: none;              display: inline-block;              transition: all .2s;              line-height: 1;          }            &:hover {              color: $color-primary;          }      }  }  

So I want just the Lorem ipsum part to be vertically scrollable. Any thoughts/help would be appreciated!

HTML onclick button takes two clicks

Posted: 18 Dec 2021 08:26 AM PST

I saw the answers from similar questions but they did not help me

I have a button that when clicked, will change the background color of the button and hide/show some content

HTML

<button class="pro-saved-team-btn" id="{{ teams[loop.index0] | replace(' ', '') + 'button' }}"                              onclick="show_team('{{ team | replace(' ', '') }}', '{{ team | replace(' ', '') + 'button' }}')">                          {{ team.title() }}  </button>  

JS in HTML

<script>          function show_team(team, team_btn) {              x = document.getElementById(team);              btn = document.getElementById(team_btn);              if (x.style.display === "none") {                  x.style.display = "block";                  btn.style.backgroundColor = '#1DA1F2';              } else {                  x.style.display = "none";                  btn.style.backgroundColor = '#161616';              }          }      </script>  

I know the function works but I need to click on the button twice for the background color to change.

Anyone know how to fix this so it works after only one click?

jest-junit Validation warning

Posted: 18 Dec 2021 08:26 AM PST

When I run jest :

script in package.json is "test": "jest --runInBand --coverage=False --verbose=False --silent"

My console always throws this warning before it executes the test

● Validation Warning:

Unknown option "jest-junit" with value {"outputDirectory": ".", "outputName": "junit.xml", "suiteNameTemplate": "{filepath}"} was found.
This is probably a typing mistake. Fixing it will remove this message.

I am unable to fix it.

FirestoreRecyclerAdapter Recyclerview UI doesn't change after adding a message to the chatroom

Posted: 18 Dec 2021 08:26 AM PST

I'm able to add a message to firestore, but when I clicked the send button in the chatroom the recyclerview doesn't update in realtime so the new message doesn't appear. The message does appear when I reopen the chatroom which isn't best pratice. Normally FirestoreRecyclerAdapter should automatically updated the query when changes are made and update the recyclerview. I'm working in Android Studio with Java and using fragments instead of activities.

ChatRoomFragment:

public class ChatRoomFragment extends Fragment {      private static final String TAG = "Notable:ChatRoom";      private FirebaseFirestore db;      private Query query;      private FirestoreRecyclerAdapter<Message, MessageAdapter.MessageHolder> adapter;      private FirebaseAuth mAuth;      private FirebaseUser currentUser;        @Override      public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {          View view = inflater.inflate(R.layout.chatroom_fragment, container, false);          MaterialToolbar topBar = view.findViewById(R.id.topAppBar);          Button sendButton = view.findViewById(R.id.send_message);          EditText input = view.findViewById(R.id.message_edit_text);          RecyclerView chatRecyclerView = view.findViewById(R.id.chat_recyclerview);          mAuth = FirebaseAuth.getInstance();          currentUser = mAuth.getCurrentUser();          db = FirebaseFirestore.getInstance();          //FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder().setPersistenceEnabled(true).setCacheSizeBytes(FirebaseFirestoreSettings.CACHE_SIZE_UNLIMITED).build();          //db.setFirestoreSettings(settings);          String key = mAuth.getCurrentUser().getUid();          LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());          layoutManager.setStackFromEnd(true);          chatRecyclerView.setLayoutManager(layoutManager);            String title = this.getArguments().getString("buttonText");          topBar.setTitle(title);            query = db.collection("messages").whereEqualTo("chatGroup", title).orderBy("messageTime");          adapter = new MessageAdapter(getActivity(), query, key);          //https://medium.com/@akhilkc9/simple-android-chat-application-using-firestorerecycleradapter-7f632da2eaee          adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {              @Override              public void onItemRangeChanged(int positionStart, int itemCount) {                  super.onItemRangeChanged(positionStart, itemCount);                  chatRecyclerView.scrollToPosition(itemCount);              }          });          chatRecyclerView.setAdapter(adapter);            sendButton.setOnClickListener(new View.OnClickListener() {              @Override              public void onClick(View view) {                  String text = input.getText().toString();                  if(!text.equals("")){                      db.collection("users").document(key).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {                          @Override                          public void onSuccess(DocumentSnapshot documentSnapshot) {                              if (documentSnapshot.exists()){                                  String firstName = documentSnapshot.get("firstname").toString();                                  db.collection("messages").add(new Message(firstName, text, key, title));                              }else{                                  Log.w(TAG, "No such document");                              }                          }                      });                  }                  input.setText("");              }          });            return view;      }        @Override      public void onStart() {          super.onStart();          if(adapter!=null) adapter.startListening();      }        @Override      public void onStop() {          super.onStop();          if(adapter!=null) adapter.stopListening();      }  }  

MessageAdapter:

public class MessageAdapter extends FirestoreRecyclerAdapter<Message, MessageAdapter.MessageHolder> {      private final String TAG = "MessageAdapter";      Context context;      String userId;      StorageReference storageReference;      private RequestOptions requestOptions = new RequestOptions();      private final int MESSAGE_IN_VIEW_TYPE  = 1;      private final int MESSAGE_OUT_VIEW_TYPE = 2;        public MessageAdapter(@NonNull Context context, Query query, String userID) {          super(new FirestoreRecyclerOptions.Builder<Message>().setQuery(query, Message.class).build());          this.context = context;          this.userId = userID;      }        @Override      public int getItemViewType(int position) {          if(getItem(position).getMessageUserId().equals(userId)){              return MESSAGE_IN_VIEW_TYPE;          }          return MESSAGE_OUT_VIEW_TYPE;      }        @Override      public MessageHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {          View view = null;          if(viewType==MESSAGE_IN_VIEW_TYPE){              view = LayoutInflater.from(parent.getContext())                      .inflate(R.layout.chat_item, parent, false);          }else{              view = LayoutInflater.from(parent.getContext())                      .inflate(R.layout.chat_item_other, parent, false);          }          return new MessageHolder(view);      }        //Voordeel van Recyclerview is dat het automatisch een Viewholder heeft, dit heeft gridview niet automatisch      @Override      protected void onBindViewHolder(@NonNull MessageHolder holder, int position, @NonNull Message model) {          final TextView mText = holder.mText;          final TextView mUsername = holder.mUsername;          final TextView mTime = holder.mTime;          final TextView mDate = holder.mDate;          final ImageView imgProfile = holder.imgProfile;            if(mUsername != null && imgProfile != null){              mUsername.setText(model.getMessageUser());              //Glide.with(context).setDefaultRequestOptions(requestOptions).load(R.drawable.placeholder).diskCacheStrategy(DiskCacheStrategy.DATA).into(imgProfile);              //storageReference.child(model.getMessageUserId())          }          mText.setText(model.getMessageText());          mDate.setText(DateFormat.format("dd MMM", model.getMessageTime()));          mTime.setText(DateFormat.format("h:mm", model.getMessageTime()));        }        static class MessageHolder extends RecyclerView.ViewHolder {            TextView mText;          TextView mUsername;          TextView mTime;          TextView mDate;          ImageView imgProfile;            public MessageHolder(View itemView) {              super(itemView);              mText = itemView.findViewById(R.id.message_text);              mUsername = itemView.findViewById(R.id.message_user);              mTime = itemView.findViewById(R.id.message_time);              mDate = itemView.findViewById(R.id.message_date);              imgProfile = itemView.findViewById(R.id.imgDps);          }      }  }  

chatroom_fragment.xml :

<?xml version="1.0" encoding="utf-8"?>  <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:app="http://schemas.android.com/apk/res-auto"      xmlns:tools="http://schemas.android.com/tools"      android:layout_width="match_parent"      android:layout_height="match_parent">        <com.google.android.material.appbar.AppBarLayout          android:id="@+id/layout_group_chat"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:fitsSystemWindows="true"          android:orientation="vertical"          app:layout_constraintTop_toTopOf="parent">            <com.google.android.material.appbar.MaterialToolbar              android:id="@+id/topAppBar"              android:layout_width="match_parent"              android:layout_height="?attr/actionBarSize"              app:title="@string/chat_group"              style="@style/Widget.MaterialComponents.Toolbar.Primary" />      </com.google.android.material.appbar.AppBarLayout>        <androidx.recyclerview.widget.RecyclerView          android:id="@+id/chat_recyclerview"          android:layout_width="match_parent"          android:layout_height="match_parent"          android:layout_marginBottom="16dp"          app:layout_constrainedHeight="true"          app:layout_constraintBottom_toTopOf="@+id/text_indicator"          app:layout_constraintTop_toBottomOf="@+id/layout_group_chat" />        <TextView          android:id="@+id/text_indicator"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:layout_marginStart="16dp"          android:visibility="gone"          app:layout_constraintBottom_toTopOf="@id/view"          app:layout_constraintStart_toStartOf="parent" />        <View          android:id="@+id/view"          android:layout_width="match_parent"          android:layout_height="1dp"          android:background="#e0e0e0"          app:layout_constraintBottom_toTopOf="@+id/layout_chatbox" />        <RelativeLayout          android:id="@+id/layout_chatbox"          android:layout_width="match_parent"          android:layout_height="wrap_content"          app:layout_constraintBottom_toBottomOf="parent"          app:layout_constraintStart_toStartOf="parent">              <EditText              android:layout_marginStart="16dp"              android:id="@+id/message_edit_text"              android:layout_width="match_parent"              android:layout_height="wrap_content"              android:layout_centerVertical="true"              android:background="@android:color/transparent"              android:hint="@string/hint_message"              android:inputType="text"              android:maxLines="6"              tools:ignore="Autofill" />            <Button              android:id="@+id/send_message"              android:layout_width="74dp"              android:layout_height="48dp"              android:layout_alignParentEnd="true"              android:background="?attr/selectableItemBackground"              android:text="@string/send"              android:textColor="@color/design_default_color_primary" />        </RelativeLayout>      </androidx.constraintlayout.widget.ConstraintLayout>  

Livewire file upload validation always fails the first time but works the second time

Posted: 18 Dec 2021 08:26 AM PST

Weird issue with my Livewire: the validation, when I send a file, always fails on the first time. If I have the criteria that it must be a pdf, I will put the PDF, submit the form, get a message telling me I have the wrong format, I won't change anything, resubmit and it will go through with no issue.

Does anyone knows why it might be happening?

<?php    namespace App\Http\Livewire\Branch\Documents;    use App\Models\BranchDocument;  use Livewire\Component;  use Livewire\WithFileUploads;    class Upload extends Component  {      use WithFileUploads;        public BranchDocument $document;      public $file;      public $saved = false;        public function render()      {          return view('livewire.branch.documents.upload');      }        public function save() {          $this->validate([              'file' => 'mimes:jpg,bmp,png,pdf|max:10240', // 1MB Max          ]);            $this->document->file = $this->file;            $this->saved = true;      }  }  
<div x-data="{ open: false }">      <li class="@if(!$saved) hover:bg-gray-100  py-2 px-2 rounded cursor-pointer @endif" @click="open = true">          <div class="relative">            <div class="relative flex space-x-3">              <div class="min-w-0 flex-1 flex justify-between space-x-4 items-center">                <div>                  <p class="text-sm text-porange">{{ $document->document_type->title }}@if($saved)<span class="text-sm text-gray-600"> - {{ __('Document sent!') }}</span>@endif</p>                  <p class="text-xs text-gray-600">{{ $document->created_at->diffForHumans() }}</p>                </div>                  <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" >                      @if(!$saved)                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />                      @else                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />                      @endif                  </svg>              </div>            </div>          </div>        </li>          @if(!$saved)        <div x-show="open" class="fixed z-10 inset-0 overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">          <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">            <!--              Background overlay, show/hide based on modal state.                Entering: "ease-out duration-300"                From: "opacity-0"                To: "opacity-100"              Leaving: "ease-in duration-200"                From: "opacity-100"                To: "opacity-0"            -->            <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true"></div>              <!-- This element is to trick the browser into centering the modal contents. -->            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>              <!--              Modal panel, show/hide based on modal state.                Entering: "ease-out duration-300"                From: "opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"                To: "opacity-100 translate-y-0 sm:scale-100"              Leaving: "ease-in duration-200"                From: "opacity-100 translate-y-0 sm:scale-100"                To: "opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"            -->            <div @click.away="open = false" class="inline-block align-bottom bg-white rounded-lg px-4 py-4 text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full sm:p-6">              <div>                <div class="text-center">                  <h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-title">                    {{ __('Upload ":title"', ['title' => $document->document_type->title])}}                  </h3>                </div>              </div>              <form wire:submit.prevent="save">                <input type="file" wire:model="file" class="file-input-business block mx-auto mt-4"/>              @error('file') <span class="error">{{ $message }}</span> @enderror                <div class="mt-5 sm:mt-6 sm:grid sm:grid-cols-2 sm:gap-3 sm:grid-flow-row-dense">                <button type="submit" type="button" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-porange text-base font-medium text-white hover:bg-porange-darker focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-porange sm:col-start-2 sm:text-sm">                  {{ __('Send')}}                </button>                <button @click="open = false" type="button" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-porange sm:mt-0 sm:col-start-1 sm:text-sm">                  {{ __('Cancel')}}                </button>              </div>          </form>            </div>          </div>        </div>        @endif  </div>  

Thank you!

What is the difference between long and long int in c?

Posted: 18 Dec 2021 08:27 AM PST

I know that an integer has a range of -2147483648 to 2147483647 and a long has the range of -9223372036854775808 to 9223372036854775807 but what range does a long int have?

Vscode with custom settings.xml Maven file per project in a workspace

Posted: 18 Dec 2021 08:28 AM PST

I have a Vscode workspace with a bunch of Maven projects, and which one has its own Maven settings.xml file.

As each project has its own settings file with the same name but in its own root folder I got success configuring both the workspace as each of the projects with such an option: {"maven.executable.options": "-s my_settings.xml"}.

Although, I can run successfully any of Maven commands for all projects, Vscode reports problems in the pom.xml files about missing artifacts and the same errors are reported when I run tests from the "Testing" in the Side Bar.

When I copy one of the project's settings file to the ~/.m2/settings.xml that given project works fine, no errors at all.

So, I conclude Vscode doesn't respect the "maven.executable.options" for all of project operations inside IDE, like tests and maybe others operations but only for directly launched Maven commands.

I don't want to merge all those settings.xml files into a big one in my local ~/.m2/settgins.xml each time I have to open a given set of projects.

Is there a way to teach Vscode to use different settings.xml for each project and make it work properly in all Vscode operations (not only Maven commands)?

Why is this cookie not being deleted using JavaScript

Posted: 18 Dec 2021 08:27 AM PST

I'm stumped at this situation. I have a cookie with the following information:

Name: sessionid  Value: *redacted*  Path: /  Domain: localhost  

I try to delete it with the following code in the Console:

document.cookie = "sessionid=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/;domain=localhost"  

But after I click the refresh button in the Application tab, it seems to have had no effect, and the cookie still has the same value as before.

What am I missing?

Screenshot

Project references NuGet package(s) that are missing on this computer

Posted: 18 Dec 2021 08:27 AM PST

This morning I received the following error when trying to build my Visual Studio ASP.NET solution:

This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is ..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props.

I performed a NuGet Package Restore as instructed but the results stated that: all packages are already installed and there is nothing to restore.

The NuGet Package Manager settings are as follows:

NuGet Package Settings

How can I solve this issue?

GOLANG unmarshal dynamic JSON

Posted: 18 Dec 2021 08:26 AM PST

I am very new to GOLANG.

I have been trying for quite some time now to unmarshal an ethereum RPC JSON which has a dynamic structure. No GOLANG struct and map setup I did worked and I am able to get the stateDiff entries (3) but all lower structs seem not to be filled ith any data. So I am able to loop through all the 3 entries but then don't know how to access the values below and when dumping the unmarshal result, I see that GOLANG is not delivering the data anyway into StateDiff

JSON FILE:

{     "jsonrpc":"2.0",     "id":1,     "result":{        "output":"0x0000000000000000000000000000000000000000000000000000000000000001",        "stateDiff":{           "0x0000000000000000000000000000000000000000":{              "balance":{                 "*":{                    "from":"0x45acecdfadb71366cf",                    "to":"0x45aced3909536ccacf"                 }              },              "code":"=",              "nonce":"=",              "storage":{                               }           },           "0x07865c6e87b9f70255377e024ace6630c1eaa37f":{              "balance":"=",              "code":"=",              "nonce":"=",              "storage":{                 "0x86a60af761556602732bbdeaef13ba6e2481f83362d3489389f51353d86a6ac3":{                    "*":{                       "from":"0x0000000000000000000000000000000000000000000000000000000000000000",                       "to":"0x0000000000000000000000000000000000000000000000000000000000002710"                    }                 },                 "0xb0cf6f3c0836765b9dee3d1537458f10fe99447508adc172c1f633ac7352aaa8":{                    "*":{                       "from":"0x00000000000000000000000000000000000000000000000000092f379a04d2b0",                       "to":"0x00000000000000000000000000000000000000000000000000092f379a04aba0"                    }                 }              }           },           "0x6dbe810e3314546009bd6e1b29f9031211cda5d2":{              "balance":{                 "*":{                    "from":"0x41c41fc2c0247860",                    "to":"0x41c3c66723c4155c"                 }              },              "code":"=",              "nonce":{                 "*":{                    "from":"0x741",                    "to":"0x742"                 }              },              "storage":{                               }           }        },        "trace":[                   ],        "vmTrace":null     }  }  

I have tried to unmarshal the JSON into the following structure (among many) and i can't get the values such as result>stateDiff>0x0000000000000000000000000000000000000000>balance>*>from Struct below is just one of many i tried. I can't get anything below the entry 0x0000000000000000000000000000000000000000

    type Storage struct {      star struct {          from string `json:"from"`          to   string `json:"to"`      } `json:"*"`  }  type StateDiff struct {      balance []struct {          star struct {              from string `json:"from"`              to   string `json:"to"`          } `json:"*"`      } `json:"balance"`      code    string     `json:"code"`      nonce   string     `json:"nonce"`      storage []*Storage `json:"storage"`  }  type res_trace_replayTransaction struct {      Jsonrpc string `json:"jsonrpc"`      ID      int    `json:"id"`      Result  struct {          Output  string                `json:"output"`          SD      map[string]*StateDiff `json:"stateDiff"`          Trace   []interface{}         `json:"trace"`          VMTrace interface{}           `json:"vmTrace"`      } `json:"result"`  }  

How can I stop html outputting?

Posted: 18 Dec 2021 08:28 AM PST

I am writing an anti-ddos php script, and I want to write a custom load page, but the html page of the orginal html page would be rendered. Is there anyway for me to prevent the html showing up while showing up my php load page

<?php require "antiddos.php"?>  

Why is transition property not working in this case?

Posted: 18 Dec 2021 08:26 AM PST

I'm creating a hamburger menu and I'm using JavaScript to handle the ON and OFF of the menu. Here's how my code looks like:

const hamburger_menu = document.querySelector('.hamburger-menu');  const side_nav = document.querySelector('.side-nav');    hamburger_menu.addEventListener('click', () => {      side_nav.classList.toggle('open');  })  

When the hamburger menu is clicked, the script will toggle the 'open' class on the hidden menu. I want the menu to have a transition effect when appearing. Here's how my SCSS looks like:

.side-nav {      background: $black;      display: none;      padding: 5rem;      position: absolute;      top: 10.4rem;      right: 0;      bottom: -1.6rem;      left: 0;      opacity: 0;      transition: all .3s ease;      z-index: 100;        &.open {          display: block;          opacity: 1;      }  }  

Somehow the transition effect is not working. Is there anyone knows the reason?

Reified inline function in Kotlin still leading to compiler error on 'is' check

Posted: 18 Dec 2021 08:26 AM PST

I have the following function:

inline fun <reified T> create(preference: Preference<T>, title: String = ""): DebugOption{          val type = when (preference) {              is Preference<String> -> Type.STRING              is Preference<Boolean> -> Type.BOOLEAN              else -> Type.STRING          }            return DebugOption(type, preference, displayTitle = StringModel(title))      }  

I was expecting to be able to easily perform this 'is' check, since the generic type is reified, but I am still getting a compiler error:

Cannot check for instance of erased type: Preference<String>  Cannot check for instance of erased type: Preference<Boolean>  

So I am confused how am I misusing 'reified' / what am I missing here. Is there a problem with using reified generic types as the type parameter of another class?

CIFilter color cube data loading

Posted: 18 Dec 2021 08:27 AM PST

I have around 50 3D LUTs (stored as png images, each being 900KB in size) and use CIColorCube filter to generate a filtered image. I use UICollectionView to display filtered thumbnails (100x100) for each LUT (like in Photos app). The problem is UICollectionView scrolling becomes extremely slow(no where close to smoothness of Photos app) when I generate filtered images as user scrolls. I thought of pre generating filtered images but the problem is it takes around 150 milliseconds to generate cubeData from LUT png, so for 50 thumbnails it takes around 7-8 seconds to prepare filtered thumbnails which is long. And this is exactly the culprit for scrolling performance as well. I am wondering what I can do to make it smooth like in Photos app or other photo editing apps. Here is my code to generate cube data from LUT png. I believe there is more of a CoreImage/Metal trick to fix the issue than UIKit/DispatchQueue/NSOperation based fixes.

      public static func colorCubeDataFromLUTPNGImage(_ image : UIImage, lutSize:Int) -> Data? {            let size = lutSize            let lutImage = image.cgImage!          let lutWidth    = lutImage.width          let lutHeight   = lutImage.height          let rowCount    = lutHeight / size          let columnCount = lutWidth / size            if ((lutWidth % size != 0) || (lutHeight % size != 0) || (rowCount * columnCount != size)) {              NSLog("Invalid colorLUT")              return nil          }            let bitmap  = getBytesFromImage(image: image)!          let floatSize = MemoryLayout<Float>.size            let cubeData = UnsafeMutablePointer<Float>.allocate(capacity: size * size * size * 4 * floatSize)          var z = 0          var bitmapOffset = 0            for _ in 0 ..< rowCount {              for y in 0 ..< size {                  let tmp = z                  for _ in 0 ..< columnCount {                      for x in 0 ..< size {                            let alpha   = Float(bitmap[bitmapOffset]) / 255.0                          let red     = Float(bitmap[bitmapOffset+1]) / 255.0                          let green   = Float(bitmap[bitmapOffset+2]) / 255.0                          let blue    = Float(bitmap[bitmapOffset+3]) / 255.0                            let dataOffset = (z * size * size + y * size + x) * 4                            cubeData[dataOffset + 3] = alpha                          cubeData[dataOffset + 2] = red                          cubeData[dataOffset + 1] = green                          cubeData[dataOffset + 0] = blue                          bitmapOffset += 4                      }                      z += 1                  }                  z = tmp              }              z += columnCount          }        let colorCubeData = Data(bytesNoCopy: cubeData, count: size * size * size * 4 * floatSize, deallocator: Data.Deallocator.free)            return colorCubeData  }      fileprivate static func getBytesFromImage(image:UIImage?) -> [UInt8]?  {      var pixelValues: [UInt8]?      if let imageRef = image?.cgImage {          let width = Int(imageRef.width)          let height = Int(imageRef.height)          let bitsPerComponent = 8          let bytesPerRow = width * 4          let totalBytes = height * bytesPerRow            let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Little.rawValue          let colorSpace = CGColorSpaceCreateDeviceRGB()          var intensities = [UInt8](repeating: 0, count: totalBytes)            let contextRef = CGContext(data: &intensities, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo)          contextRef?.draw(imageRef, in: CGRect(x: 0.0, y: 0.0, width: CGFloat(width), height: CGFloat(height)))            pixelValues = intensities      }      return pixelValues!  }  

And here is my code for UICollectionViewCell setup:

   func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {      let lutPath = self.lutPaths[indexPath.item]            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FilterCell", for: indexPath) as! FilterCell            if let lutImage = UIImage(contentsOfFile: lutPath) {          let renderer = CIFilter(name: "CIColorCube")!          let lutData = ColorCubeHelper.colorCubeDataFromLUTPNGImage(lutImage, lutSize: 64)                   renderer.setValue(lutData!, forKey: "inputCubeData")          renderer.setValue(64, forKey: "inputCubeDimension")          renderer.setValue(inputCIImage, forKey: kCIInputImageKey)          let outputImage = renderer.outputImage!                    let cgImage = self.ciContext.createCGImage(outputImage, from: outputImage.extent)!          cell.configure(image: UIImage(cgImage: cgImage))                } else {          NSLog("LUT not found at \(indexPath.item)")      }            return cell  }  

How to communicate with chrome extension background page in electron?

Posted: 18 Dec 2021 08:28 AM PST

Since electron doesn't implement chrome.runtime.onMessageExternal. How can we communicate with chrome extension background page in main or renderer process?

JavaFX contoller. Getting an error when I define my controller outside of the FXML file, but project works as expected, and w/o runtime errors

Posted: 18 Dec 2021 08:26 AM PST


IntelliJ Showing Error when I Don't Add a Controller in the FXML Doc



It seems that I shouldn't have to define a controller for the top level FXML element, especially since its possible to build a project without any FXML at all.

In a nutshell, I'm instantiating a controller manually in my Application class, which works perfectly, however; I am getting an error, and I need to find out if there is validity to this error, or if the error is what it seems to be: An error caused by IntelliJ not recognizing that I have defined the controller in a place other than the FXML document.


IntelliJ Displays the following err-msg in the problems console:

"No controller is specified for the top-level object."



PROJECT'S APPLICATION CLASS:


package org.foo.foo;    import javafx.application.Application;  import javafx.fxml.FXMLLoader;  import javafx.scene.Scene;  import javafx.stage.Stage;    import java.io.IOException;    public class ApplicationClass extends Application  {      @Override      public void start(Stage stage) throws IOException      {          FXMLLoader fxmlLoader = new FXMLLoader(            ApplicationClass.class.getResource("hello-view.fxml")          );                // HERE IS WHERE I ADD THE CONTROLLER:          fxmlLoader.setController(new ControllerClass());                Scene scene = new Scene(fxmlLoader.load(), 320, 240);            stage.setTitle("Hello!");          stage.setScene(scene);          stage.show();      }        public static void main(String[] args){ launch(); }  }      


PROJECT'S CONTROLLER CLASS:


package org.foo.foo;    import javafx.fxml.FXML;  import javafx.scene.control.Label;    public class ControllerClass  {      @FXML      private Label welcomeText;              @FXML      protected void onHelloButtonClick()      {          welcomeText.setText("Welcome to JavaFX Application!");      }  }        


PROJECT'S FXML DOCUMENT:


  <?xml version="1.0" encoding="UTF-8"?>    <?import javafx.geometry.Insets?>  <?import javafx.scene.control.Button?>  <?import javafx.scene.control.Label?>  <?import javafx.scene.layout.VBox?>    <VBox alignment="CENTER"      spacing="20.0"      xmlns:fx="http://javafx.com/fxml">  <!--            Default Controller that I remove, so that I can load it via the   laoder in my Application Class:      fx:controller="test.chambers.andrew.testclass.ControllerClass"    -->      <padding>        <Insets bottom="20.0" left="20.0" right="20.0" top="20.0"/>      </padding>        <Label fx:id="welcomeText"/>        <Button text="Hello!" onAction="#onHelloButtonClick"/>  </VBox>    

localStorage and onload JavaScript

Posted: 18 Dec 2021 08:28 AM PST

I tried to make a function that displays an alert on the 1st page load <body onload="alertbox()>", and its working on 2nd page load instead of 1st. What should i use instead of "onload" to make it work only on 1st laod?

I'm beginner, sorry if it's a dumb question.

var alertboxStatus = localStorage.getItem("alertbox", alertboxStatus);  localStorage.setItem("alertbox", alertboxStatus)    function alertbox()  {    if (alertboxStatus == "null" || alertboxStatus == "")     {      alert("Alert!");      alertboxStatus = "displayed";      localStorage.setItem("alertbox", alertboxStatus);    }  };  

I also tried this: But it's also working on second page load. Am i doing sth wrong with locationStorage.setItem?

document.addEventListener('DOMContentLoaded', function ()   {    if (alertboxStatus == "null" || alertboxStatus == "")     {      alert("alert");      alertboxStatus = "displayed";      localStorage.setItem("alertbox", alertboxStatus);    }  }, false);  

Changing "null" to null worked

Including an ejs file inside of another ejs file returns as string

Posted: 18 Dec 2021 08:27 AM PST

I have an ejs file that contains a single line of code which includes another ejs file.

<%= include('header.ejs') %>  

Header.ejs contains html code containing my website's header file. However, when I open the original file I get header.ejs as a string and not rendered properly. Does this have to do with something with how I rendered my ejs or did I do something else wrong?

Make out-of-keyboard symbols read/writable in python

Posted: 18 Dec 2021 08:28 AM PST

So I was just building an IDE in python using tkinter. When I tried to open a .py file in it using tkinter.filedialog's askopenfilename, which contained characters that are not present in keyboard (which I got by clicking win_key + period), it didn't open and threw an error:

return codecs.charmap_decode(input,self.errors,decoding_table)[0]  UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 9588: character maps to <undefined>  

I am sure it is not able to read the symbol ← and →.

My code for opening the file:

def open_function(event=None):              if saved == False:                  file_not_saved = askyesnocancel("File not saved", "Your file is not saved. Do you want to save your file?")                  if file_not_saved == 1:                      save_function()                  elif file_not_saved == None:                      return              path = askopenfilename(title="Open File", filetypes=[("Python files (*.py)", "*.py")])              if path != "":                  with open(path, "r") as file:                      code = file.read()                      editing_area.delete("1.0", "end")                      editing_area.insert("1.0", code)                      set_file_path(path)                      set_file_name(basename(path))                  set_saved(True)              elif path == "":                  showerror("Error", "Some file path error occured. Please open your file again.")  

So my question obviously is how to make python's with open function read out-of-keyboard characters.

I am using python 3.10.1

Any help would be appreciated!!

How to fix protonvpn TypeError: __init__() got an unexpected keyword argument 'log_dir_path'?

Posted: 18 Dec 2021 08:27 AM PST

I am using linux (Manjaro kde plasma).

When trying to run protonvpn from the task manager, it fails to start and does not give any errors, When run using the command line it outputs the following:

Traceback (most recent call last):    File "/usr/lib/python3.9/site-packages/protonvpn_gui/main.py", line 262, in do_activate      if not protonvpn.check_session_exists():    File "/usr/lib/python3.9/site-packages/protonvpn_nm_lib/api.py", line 344, in check_session_exists      return self._env.api_session.is_valid    File "/usr/lib/python3.9/site-packages/protonvpn_nm_lib/core/environment.py", line 55, in api_session      self.__api_session = APISession()    File "/usr/lib/python3.9/site-packages/protonvpn_nm_lib/core/session/session.py", line 211, in __init__      self.__session_create()    File "/usr/lib/python3.9/site-packages/protonvpn_nm_lib/core/session/session.py", line 232, in __session_create      self.__proton_api = Session(  TypeError: __init__() got an unexpected keyword argument 'log_dir_path'  

i have tried restarting and reinstalling/rebuilding which has not changed anything.

Is there any way to check whether a localised string is a valid number in Java?

Posted: 18 Dec 2021 08:26 AM PST

Correct string representations of numbers depend on the Locale: "2.5" is a valid number in the US, but not in Germany. The German representation of this number is "2,5". Is there any way in Java to detect that a given string is a valid number with respect to a certain Locale?

var decimal = DecimalFormat.getInstance(Locale.Germany).parse("2.5");  

The DecimalFormat just ignores the "." and reads the number as 25, which is not what I need. I need a way to tell that this is not a valid number representation in Germany. How can I get such a test?

The solutions proposed as answers to the question here either ignore the locale altogether, or propose a home-made parsing algorithm which does neither consider the complexities nor the multiple differences in the locales. Is there a library which does that job simple and complete?

asyncio create task and aiohttp , 'no running event loop'

Posted: 18 Dec 2021 08:27 AM PST

Im trying to make a Pyqt5 app with aiohttp request, and asyncio tasks. Im using quamash package too and it requires Python 3.7 so i installed this version.(it didn't work on Python 3.10) The main reason i use asyncio and quamash is because i want to do requests and without freezing the GUI of the app.

I get this error when i click the Start button and close the app:

Task exception was never retrieved  future: <Task finished coro=<App.rotator() done, defined at C:\Users\Zsolt\Documents\python-example\stack_exmaple.py:37> exception=RuntimeError('no running event loop')>  Traceback (most recent call last):    File "C:\Users\Zsolt\Documents\python-example\stack_exmaple.py", line 41, in rotator      response = await get()    File "C:\Users\Zsolt\Documents\python-example\stack_exmaple.py", line 51, in get      async with session.get(pokemon_url) as resp:    File "C:\Users\Zsolt\AppData\Local\Programs\Python\Python37\lib\site-packages\aiohttp\client.py", line 1138, in __aenter__      self._resp = await self._coro    File "C:\Users\Zsolt\AppData\Local\Programs\Python\Python37\lib\site-packages\aiohttp\client.py", line 533, in _request      async with ceil_timeout(real_timeout.connect):    File "C:\Users\Zsolt\AppData\Local\Programs\Python\Python37\lib\site-packages\aiohttp\helpers.py", line 734, in ceil_timeout      return async_timeout.timeout(None)    File "C:\Users\Zsolt\AppData\Local\Programs\Python\Python37\lib\site-packages\async_timeout\__init__.py", line 30, in timeout      loop = _get_running_loop()    File "C:\Users\Zsolt\AppData\Local\Programs\Python\Python37\lib\site-packages\async_timeout\__init__.py", line 236, in _get_running_loop      return asyncio.get_running_loop()  RuntimeError: no running event loop  

Here is the full code:

from PyQt5.QtWidgets import *  from PyQt5.QtGui import QKeySequence, QPalette, QColor  from PyQt5.QtCore import Qt  from PyQt5 import QtGui, QtCore  import asyncio  import aiohttp  import quamash  import os.path  import json  import sys    class App(QWidget):        run = 0      response = ''      def __init__(self, loop):          super().__init__()            btn = QPushButton('Start', self)          btn.resize(btn.sizeHint())          btn.clicked.connect(self.start)            self.setGeometry(200, 200, 700, 400)          self.display = QLabel(self)          self.display.resize(200, 500)          self.display.move(1, 50)            self.count = 0          self.show()          self.loop = loop          self.tasks = []          self.tasks.append(loop.create_task(self.rotator()))        async def rotator(self):          while await asyncio.sleep(0, True):              if (self.run == 1):                  self.count += 1                  response = await get()                  self.display.setText(str(response))                          def start (self):          self.run = 1                async def get():      async with aiohttp.ClientSession() as session:          pokemon_url = 'https://pokeapi.co/api/v2/pokemon/151'          async with session.get(pokemon_url) as resp:              pokemon = await resp.json()              print(pokemon)              return pokemon          app = QApplication(sys.argv)  app.setApplicationName("Sample ;)")    loop = quamash.QEventLoop(app)  asyncio.set_event_loop(loop)    with loop:      window = App(loop)      window.show()      loop.run_forever()    

If i comment out the response = await get() it works, it counts the self.count += 1 and it shows the variable on self.display.setText(str(self.count)) . But i need to get it to work with the aiohttp request so it should print out the response from the request.

AWS Step Function - Dynamic parallelism MaxConcurrency Field

Posted: 18 Dec 2021 08:26 AM PST

We are using Step functions dynamic parallelism with Map state to achieve concurrency. Is it possible to pass the values to "MaxConcurrency" field from its upstream task(lambda or read from file ) in map state stepfunctions .

Current code:

"Type": "Map",  "InputPath": "$.detail",  "ItemsPath": "$.shipped",  "MaxConcurrency": 3,  "ResultPath": "$.detail.shipped",  

Expectation(pass input to MaxConcurrency from lambda task or read file task ):

 "Type": "Map",   "InputPath": "$.detail",   "ItemsPath": "$.shipped",   "MaxConcurrency": "$.input",   "ResultPath": "$.detail.shipped"  

Getting error as it supports only integer.

How to pass true or false value in django rest framework serializer

Posted: 18 Dec 2021 08:26 AM PST

here is my serializer code;

class RegisterSerializer(serializers.ModelSerializer):      password1 = serializers.CharField(required=True, write_only=True)      password2 = serializers.CharField(required=True, write_only=True)      email = serializers.EmailField(required=True)      is_company = serializers.BooleanField(required=False)        class Meta:          model = CustomUser          fields = [              "email",              "first_name",              "last_name",              "is_company",              "profile_pic",              "password1",              "password2",          ]        def validate_email(self, email):          email = get_adapter().clean_email(email)          if allauth_settings.UNIQUE_EMAIL:              if email and email_address_exists(email):                  raise serializers.ValidationError(                      ("A user is already registered with this e-mail address.",)                  )          return email        def validate_password1(self, password):          return get_adapter().clean_password(password)        def validate(self, data):          if data["password1"] != data["password2"]:              raise serializers.ValidationError(                  ("The two password fields didn't match.",)              )          return data        def get_cleaned_data(self):          return {              "first_name": self.validated_data.get("first_name", ""),              "last_name": self.validated_data.get("last_name", ""),              "is_company": self.validated_data.get("is_company", ""),              "profile_pic": self.validated_data.get("profile_pic", ""),              "password1": self.validated_data.get("password1", ""),              "email": self.validated_data.get("email", ""),          }        def save(self, request):          adapter = get_adapter()          user = adapter.new_user(request)          self.cleaned_data = self.get_cleaned_data()          adapter.save_user(request, user, self)          if self.cleaned_data.get("profile_pic"):              user.profile_pic = self.cleaned_data.get("profile_pic")          setup_user_email(request, user, [])          user.save()          return user    

Basically what I am trying to do is, when I make a request with a json format in something like postman;

{      "first_name": firstname,      "last_name": lastname,      "email": myemail,      "password1": password1,      "password2": password2,      "is_company": true  }  

when I pass true to is_company, I want that to change is_company value to true; but I keep getting false. I have tried using form data, but still get false I have also tried passing 'true' or 'True' but still keep getting false.

Note that I am using django-rest-auth for the authentication, and I am passing RegisterSerializer to the django-rest-auth settings in my settings.py;

REST_AUTH_REGISTER_SERIALIZERS = {      "REGISTER_SERIALIZER": "users.api.serializer.RegisterSerializer",  }  

How to return an int value stuck in a for loop but a callback in Kotlin?

Posted: 18 Dec 2021 08:26 AM PST

I am trying to get the size of this firebase collection size of documents, and for some reason in Kotlin, I can't seem to get this to work. I have declared a variable to be zero in an int function and I put it inside a for loop where it increments to the size of the range. Then when I return the value, it is zero. Here is the code I have provided, please help me as to why it is returning zero.

This is just what is being passed to the function

var postSize = 0   

That is the global variable, now for below

val db = FirebaseFirestore.getInstance()  val first = db.collection("Post").orderBy("timestamp")  getPostSize(first)  

This is the function

private fun getPostSize(first: Query){     first.get().addOnSuccessListener { documents ->         for(document in documents) {         Log.d(TAG, "${document.id} => ${document.data}")         getActualPostSize(postSize++)     }   }  return postSize  }    private fun getActualPostSize(sizeOfPost: Int): Int {  // The number does push to what I am expecting right here if I called a print statement        return sizeOfPost // However here it just returns it to be zero again. Why @tenffour04? Why?   }  

It is my understanding, according to the other question that this was linked to, that I was suppose to do something like this.

How to randomize between two set colors?

Posted: 18 Dec 2021 08:27 AM PST

I want to know how to be able to have my program generate random color between two set colors and all inbetween the two. For example just the way that I would say:

fill(random(255),0,0));  

in order to get a range reds.

I want to be able to choose two colors, let's say orange and blue, and have it generate colors from these two sets of colors. So for it to randomly generate a color from that shade of blue, any shade in between that and into a specific shade of orange.

How do I go about doing that?

No comments:

Post a Comment