Thursday, July 1, 2021

Posts from Recent Questions - Stack Overflow for 07/01/2021

View this email in your browser
Updates from https://stackoverflow.com/questions

Recent Questions - Stack Overflow



In the 07/01/2021 edition:

How to add a interactive transparent UIDatePicker up or under a UILabel in Xamarin.ios?

By Robin Khan on Jul 01, 2021 03:58 am

I need to open a UIDatePicker programatically in my Xamarin.ios project. Unfortunately it is not allowed and there is no public api. But I got some tricks which are native code from Open UIDatePicker programmatically in iOS 14 I am trying to implement this trick: https://stackoverflow.com/a/65430977/13026962 I managed to add a UIDatePicker on top of my label. This is my code:

            lblFromDate.AddGestureRecognizer(new UITapGestureRecognizer(tapDateControl));              lblFromDate.UserInteractionEnabled = false;              var datePicker = new UIDatePicker(new CGRect(x: lblFromDate.Frame.X, y:              lblFromDate.Frame.Y, width: lblFromDate.Frame.Width, height: lblFromDate.Frame.Height));              datePicker.Mode = UIDatePickerMode.Date;              datePicker.ValueChanged += DatePicker_ValueChanged;              Add(datePicker);  

enter image description here

But I want to hide the date picker somehow but still need that to be interactive so that when tapping on the label (actually tapped the date picker), the date picker animates out.

The second problem is I want to close the calendar modal when any date is tapped. But I found only value changed event. Is it possible to close the calendar modal programmatically, would be a great help for me. Here is the calendar modal that pops up after tapping on the date picker:

enter image description here


Read in browser »
share on Twitter

How to write stored procedure in code fast approach using .net core 3.1?

By Mantu on Jul 01, 2021 03:57 am

How to write stored procedure in code fast approach using .net core 3.1? And how to update or modify that? Can anybody explain? Thanks in advance.


Read in browser »
share on Twitter

Problem when migrate from ViewPager to ViewPager2

By Sabrina N on Jul 01, 2021 03:57 am

This viewpager is already running perfectly.

I want to migrate from viewpager to viewpager2. But there is a problem when I scroll viewpager2 left/right, the tables in the fragment sometimes appear sometime not. Is there something wrong with my code?

ViewPager(old) - this is running perfectly

private static class SettingAdapter extends FragmentStatePagerAdapter {      private List<Fragment> fragmentList = new ArrayList<>();      private List<String> titleList = new ArrayList<>();        public SettingAdapter(@NonNull FragmentManager fm, int behavior) {          super(fm, behavior);      }        @NonNull      @Override      public Fragment getItem(int position) {          return fragmentList.get(position);      }        @Override      public int getCount() {          return fragmentList.size();      }        public void addFragment(@NonNull Fragment fragment, @NonNull String title) {          fragmentList.add(fragment);          titleList.add(title);      }        @Override      public int getItemPosition(@NonNull Object object) {          return POSITION_NONE;      }        @Override      public CharSequence getPageTitle(int position) {          return titleList.get(position);      }  }  

SettingAdapter call from onCreateView in Fragment (old)

titles = getSettingTabTitlesRes(context);  adapter = new SettingAdapter(getChildFragmentManager(), BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);    if (titles.length == 15) {      adapter.addFragment(new NetworkFragment(), titles[0]);      adapter.addFragment(new PopulationsFragment(), titles[1]);      adapter.addFragment(new BankFragment(), titles[2]);      adapter.addFragment(new PetrolStationFragment(), titles[3]);      adapter.addFragment(new DispenserFragment(), titles[4]);      adapter.addFragment(new ProductFragment(), titles[5]);      adapter.addFragment(new EmployeeFragment(), titles[6]);      adapter.addFragment(new NozzleFragment(), titles[7]);      adapter.addFragment(new PaymentMethodFragment(), titles[8]);      adapter.addFragment(new WorkScheduleFragment(), titles[9]);      adapter.addFragment(new ReceiptPaperFragment(), titles[10]);      adapter.addFragment(new CustomersFragment(), titles[11]);      adapter.addFragment(new UserAccountFragment(), titles[12]);      adapter.addFragment(new LicenseFragment(), titles[13]);      adapter.addFragment(new HelpFragment(), titles[14]);  }    binding.settingViewpager.setAdapter(adapter);  binding.settingTablayout.setupWithViewPager(viewPager);  

ViewPager2(new) - PROBLEM IN HERE..

private static class SettingAdapter extends FragmentStateAdapter {        public SettingAdapter(@NonNull Fragment fragment) {          super(fragment);      }        @NonNull      @Override      public Fragment createFragment(int position) {          Log.i("xxx", "createFragment: " + position);          switch (position) {              default:              case 0:                  return new NetworkFragment();              case 1:                  return new PopulationsFragment();              case 2:                  return new BankFragment();              case 3:                  return new PetrolStationFragment();              case 4:                  return new DispenserFragment();              case 5:                  return new ProductFragment();              case 6:                  return new EmployeeFragment();              case 7:                  return new NozzleFragment();              case 8:                  return new PaymentMethodFragment();              case 9:                  return new WorkScheduleFragment();              case 10:                  return new ReceiptPaperFragment();              case 11:                  return new CustomersFragment();              case 12:                  return new UserAccountFragment();              case 13:                  return new LicenseFragment();              case 14:                  return new HelpFragment();          }      }        @Override      public int getItemCount() {          return 15;      }  }  

SettingAdapter call from onCreateView in Fragment (new)

String titles = getSettingTabTitlesRes(context);  settingAdapter = new SettingAdapter(this);    binding.settingViewpager.setOffscreenPageLimit(2);  binding.settingViewpager.setAdapter(settingAdapter);    new TabLayoutMediator(binding.settingTablayout, binding.settingViewpager, (tab, position) -> {      tab.setText(titles[position]);  }).attach();  

Read in browser »
share on Twitter

Not able to convert String to Date in VB.Net 2005. Tried Convert.ToDateTime, ParseExact. I couldn't found similar issue anywhere. Hlep needed

By Preetax on Jul 01, 2021 03:56 am

I am using vb 2005 and grid view where I need to do some cell changes on basis of days difference where two dates are taken from two cells and day difference is calculated. But converting string to date is giving me weird errors.

Code part 1: Here we are taking string from two cells: Protected Sub rowDataBoundForColor(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gd1.RowDataBound 'Dim ddl As TextBox = TryCast(, TextBox) 'msgShow2(ddl.SelectedValue) If e.Row.RowType = DataControlRowType.DataRow AndAlso e.Row.RowIndex <> gd1.EditIndex Then Dim ddl As Label = TryCast(e.Row.FindControl("Label25"), Label) If ddl.Text.Trim.Length > 7 Then

            e.Row.BackColor = Drawing.Color.LightGreen              'e.Row.Cells(0).Visible = False              e.Row.Cells(0).Enabled = False              Dim notify As Button = TryCast(e.Row.FindControl("NotifyButton"), Button)              notify.Visible = "True"                  '============ This is the concern code              Dim IndDt As Label = TryCast(e.Row.FindControl("Label14"), Label)              Dim payDt As Label = TryCast(e.Row.FindControl("Label25"), Label)                Dim IndDtS As String = IndDt.Text.Trim              Dim payDtS As String = payDt.Text.Trim                Dim t1 As String = IndDt.Text.Trim              Dim t2 As String = payDt.Text.Trim                  If InStr(IndDtS, "/") > 0 Then                  IndDtS = IndDtS.ToString.Replace("/", "-")              End If                If InStr(IndDtS, ".") > 0 Then                  IndDtS = IndDtS.ToString.Replace(".", "-")              End If                If InStr(payDtS, "/") > 0 Then                  payDtS = payDtS.ToString.Replace("/", "-")              End If                If InStr(payDtS, ".") > 0 Then                  payDtS = payDtS.ToString.Replace(".", "-")              End If                ' function to convert string to date called here              If (IndDtS.Length > 7 And IndDtS.Length < 11) Then                  dateRefiner(IndDtS)                End If                ' function to convert string to date called here              If (payDtS.Length > 7 And payDtS.Length < 11) Then                  dateRefiner(payDtS)              ElseIf payDtS.Length > 10 Then                  Dim st() As String = payDtS.Split(" ")                  dateRefiner(st(st.Length - 1).Trim)              End If                  Dim IndDate As DateTime = IndDtS              Dim payDate As DateTime = payDtS                Dim ID As Label = TryCast(e.Row.FindControl("Label25"), Label)              If DateDiff(DateInterval.Day, payDate, IndDate) > 30 Then                  'ID.Style.Add("color", "Red")              End If                If DateDiff(DateInterval.Day, payDate, IndDate) > 45 Then                  'e.Row.BackColor = Drawing.Color.Red                End If              '============          End If        End If    End Sub  

Part 2: the function definition: Protected Sub dateRefiner(ByRef DateS) Dim fSt2() As String Dim oDate As DateTime

    fSt2 = DateS.ToString.Trim.Split("-")        'dd-mm-yyyy to mm-dd-yyyy converted below      Dim dateR As String = fSt2(1) + "/" + fSt2(0) + "/" + fSt2(2)      Try          oDate = DateTime.ParseExact(dateR, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)      Catch ex As Exception          msgShow2("Refined Date:" + dateR + "Converted Date : " + oDate)      End Try        DateS = oDate    End Sub  

Error: System.FormatException: String was not recognized as a valid DateTime.

At: oDate = DateTime.ParseExact(dateR, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)

On Using a pop up through msgShow2() function, I tried getting the what is the converted date and original data. And I found something weird. Screenshot attached for thisSee original string and converted string in the pic


Read in browser »
share on Twitter

AVL Tree I'm a student and I'm in trouble please help me

By Huỳnh Nhật Quang on Jul 01, 2021 03:56 am

Im curently studying AVL tree And theres a segmentation fault that i've tried to fix it for days but can't Somebody please help me 😭😭 I am given the add, rebalance, rotate left right and remove, i have the classes defined in another folder and sure there no mistakes in using the classes wrong. the deadline is so close i hope stackoverflow can help, this is the first time ive been here =(((

XNode* rotateLeft(XNode* root){      //YOUR CODE HERE      XNode* newRoot = root->pRight;      root->pRight = newRoot->pLeft;      newRoot->pLeft = root;      root->updateHeight();      newRoot->updateHeight();      return newRoot;  }  XNode* rotateRight(XNode* root){      //YOUR CODE HERE      XNode* newRoot = root->pLeft;      root->pLeft = newRoot->pRight;      newRoot->pRight = root;      root->updateHeight();      newRoot->updateHeight();      return newRoot;  }     XNode* rebalance(XNode* root){      //YOUR CODE HERE     if (root == 0) return root;        root->updateHeight();      if(root->isBalanced()) return root;      XNode* newRoot = root;      if(root->isLH()){      XNode* leftTree = root->pLeft;      if(leftTree->isRH()){          root->pLeft = rotateLeft(root->pLeft);          newRoot = rotateRight(root);      }      else newRoot = rotateRight(root);  }  else if(root->isRH()){      XNode* rightTree = root->pRight;      if(rightTree->isLH()){          root->pRight = rotateRight(root->pRight);          newRoot = rotateLeft(root);      }      else newRoot = rotateLeft(root);  }  return newRoot;  }   XNode* add(XNode* root, XNode* newNode){      //YOUR CODE HERE    if(root == NULL) return newNode;        else if(newNode->data.key < root->data.key)      {      root->pLeft = add(root->pLeft, newNode);      root = rebalance(root);      }      else if (newNode->data.key > root->data.key)      {      root->pRight = add(root->pRight, newNode);      root = rebalance(root);      }        return root;  }      XNode* remove(XNode* root, K key, bool& success, V& retValue){      //YOUR CODE HERE      if(root == 0){          success = false;          return 0;      }      XNode* newRoot = root;      if( key < root->data.key)      root->pLeft = remove(root->pLeft, key, success, retValue);      else if(key > root->data.key){          root->pRight = remove(root->pRight, key, success, retValue);      }      else{          if((root->pLeft == 0) || (root->pRight == 0)){              newRoot = ((root->pLeft == 0)? root->pRight: root->pLeft);              success = true;              retValue = root->data.value;              root->data.value = 0;              delete root;          }          else{              V backup = root->data.value;              XNode* maxxLeft = root->pLeft;              while(maxxLeft->pRight != 0) maxxLeft = maxxLeft->pRight;              root->data = maxxLeft->data;              root->pLeft = remove(root->pLeft, maxxLeft->data.key, success, retValue);              success = true;              retValue = backup;          }      }      return rebalance(newRoot);  }  

And this is where the segmentation fault core dump happen i guess

  SUBCASE("Simple tree: LHoLH => rotateRight"){      int keys = {50, 40, 30};      string bfactor_exp = {sEH, sEH, sEH};      for(int idx=0; idx < 3; idx++) tree.add(keys[idx]);      REQUIRE(tree.size() == 3);      REQUIRE(tree.height() == 2);        DLinkedList<string> factor = tree.bfactor();      REQUIRE(factor.size() == 3);      REQUIRE(factor.contains(bfactor_exp, 3) == true);  }                  d                    k                                k  

Read in browser »
share on Twitter

Virtual environment shows pip of the main system

By Tasukete Onegaishimasu on Jul 01, 2021 03:55 am

After I made a new virtual environment in python python3 -m venv venv, I did pip install gtts and by doing pip freeze I can verify that it was successfully installed.

Sometime later, after closing my cmd, I started the virtual environment again via cd venv/Scripts then activate.bat, and when I pip freez-ed it shows the libraries I have installed on the main system. I can say that because Pillow, pynput, pygame, etc. is there and gtts is not.

I tried reactivating it, and the same thing happened. When I pip freeze-ed on the main system, it works perfectly, and still no gtts can be found, meaning I didn't mix the two up. When I clicked the python.exe on the venv, and did import gtts, no error showed up, meaning that gtts did get installed on the venv.


Read in browser »
share on Twitter

LDAP Search for multiple names returns entries in a different order

By Barnabeck on Jul 01, 2021 03:52 am

I work with an LDAP filter that is dynamically built to get the thumnailPhotos of a series of Active Directory users.

string UserIDs = "(|(SamAccountName=SummarS)(SamAccountName=RuatG)(SamAccountName=ArtisaD))" <- is build in a loop operation  string OnlyEnabled = "!(userAccountControl:1.2.840.113556.1.4.803:=2)";  dsSearcher.Filter = "(&(objectCategory=person)(objectClass=user)"+ UserIDs + "(" + OnlyEnabled + "))";  dsSearcher.PropertiesToLoad.Add("SamAccountName");  dsSearcher.PropertiesToLoad.Add("thumbnailPhoto");    using (var results = dsSearcher.FindAll())  {      var t = new DataTable("ActiveDir");      t.Columns.Add(new DataColumn("UserID", typeof(string)));      t.Columns.Add(new DataColumn("data", typeof(byte)));      int i = 0;      foreach (SearchResult searchResult in results)      {          Image SRC = RPT_Podium.Items[i].FindControl("ImgData") as Image;          var bytes = searchResult.Properties["thumbnailPhoto"][0] as byte;          MemoryStream s = new MemoryStream(bytes);          byte imageBytes = s.ToArray();          string base64String = Convert.ToBase64String(imageBytes);          string imageUrl = "data:image/jpg;base64," + base64String;          SRC.ImageUrl = imageUrl;          i = i + 1;      }  }  

To my surprise the returned results are NOT in the order of the AccountNames as appearing in the Search String. This forces me to reorder them somehow and I still can't think of the smartest way to achieve that


Read in browser »
share on Twitter

How to get post_meta from shortcode in post_meta?

By ilir on Jul 01, 2021 03:42 am

My pages' content is saved in blocks which are saved in post_meta instances. There are shortcodes rendered from those blocks (post_metas). It is easy to get the current $post->ID from the global $post, but how to get the post_meta ID within the shortcode callback?

add_shortcode("my_shortcode", "do_my_shortcode"));    function do_my_shortcode($attrs, $content = null)      {          global $post;          // this shortcode is executing from one of the following $post_metas:          $post_metas = get_post_custom($post->ID);            $post_meta_id = ? // How to get current post_meta id where this shortcode comes from?            return '<div class="my-shortcode-content" data-postmetaid="'. $post_meta_id .'">My shortcode content!</div>';      }    

Read in browser »
share on Twitter

Retry and DLT Implementation in Kafka Streams

By Atul Khanduri on Jul 01, 2021 03:40 am

I'm integrating Kafka Streams in a Spring Boot application. I wanted to send the data to DLT if there's an issue in the processor even after the provided number of retries.

Currently, I'm doing this in following way:

Topology topology = builder.build();  stream = new KafkaStreams(topology, streamsConfiguration);    // Setup Error Handling  final MaxFailuresUncaughtExceptionHandler exceptionHandler =          new MaxFailuresUncaughtExceptionHandler(Integer.parseInt(maxFailures), Long.parseLong(maxTimeInterval));  stream.setUncaughtExceptionHandler(exceptionHandler);  
public class MaxFailuresUncaughtExceptionHandler implements StreamsUncaughtExceptionHandler {    private int currentFailureCount;      @Override    public StreamThreadExceptionResponse handle(final Throwable throwable) {        currentFailureCount++;          if (currentFailureCount >= maxFailures) {          // Send record in DLT        }        return REPLACE_THREAD;    }  }  

Few things which I want to achieve but unable to do so:

  • Unable to get the current processor's topic which results in failure
  • Record which results in failure

I wonder if there's any other better way to handle this so that we don't need to manually send the record to DLT. Similar to what we can achieve from normal Kafka Consumer API mentioned below:

@Bean  public ConcurrentKafkaListenerContainerFactory<String, Object>  kafkaListenerContainerFactory() {      ConcurrentKafkaListenerContainerFactory<String, Object> factory =    new ConcurrentKafkaListenerContainerFactory();    factory.setConsumerFactory(consumerFactory());    factory.setConcurrency(consumerConfigVars.getConcurrency());      factory.setErrorHandler(new SeekToCurrentErrorHandler(    new DeadLetterPublishingRecoverer(kafkaTemplate), new FixedBackOff(0L, 3L))); // dead-letter after 3 tries      return factory;  }  

Read in browser »
share on Twitter

Getting invalide identifier error for s.site id

By anjali on Jul 01, 2021 03:40 am

enter image description here

SELECT

        trc.geo_reg1_nm                 AS region,          trc.ropu_nm                     AS ropu,          trc.ctry_nm                     AS country,          trc.trc_alias_cd                AS study_country,          trc.ctry_nm                     AS tr_ctry,          tu.tu_alias_cd   AS study_site,          tu.tu_status,          s.record_id,          s.entered_dt,          s.visit_dt,          s.subject_number          --,        /*s.study_id,         s.site_id*/              FROM          sdv_ar s          INNER JOIN da_cox.dm_ctm_tu tu ON ( s.study_id                                              || '-'                                              || s.site_id ) = tu.tu_alias_cd                                            AND tu.curr_flg = 1        INNER JOIN dm_ctm_tu tu ON s.tu_alias_cd = tu.tu_alias_cd                                            AND tu.curr_flg = 1            INNER JOIN dm_ctm_trc trc ON trc.ctry_cd = tu.ctry_cd                                       AND trc.tr_no = tu.tr_no                                       AND trc.curr_flg = 1    

--TEMPORAL_COMMENT_UNTIL_DATA-- INNER JOIN dm_ctm_tr tr ON tr.tr_no=trc.tr_no AND tr.curr_flg=1 AND tr.tr_stat < 4950 /* Excluding ended studies */ )


Read in browser »
share on Twitter

How to return string value?

By munhyok on Jul 01, 2021 03:36 am

I wrote this code

const link = "CKV0nSlxV8M"      const rendertest = async (link) => {      const format = await ytdl(link, { quality: '22'})      let test = JSON.stringify(format[0].url)          alert(test)  //string type      return test    }    let finalValue = rendertest(link)      console.log(finalValue)  

And I got this value from the test (string)

enter image description here

but exam value is not a String (Object)

enter image description here

I don't know which part I wrote wrong. I want the output of the same test and finalValue


Read in browser »
share on Twitter

Laravel8 - Validate a request with multiple wildcards

By Gaël Duval on Jul 01, 2021 03:30 am

I've tried for the past 2 hours to validate a request with multiple wildcards and dot notation, but it won't work.

Basically, i have 2 levels of inputs in my form:

<input type="text" name="user[0][name]" title="name of the user" />  <!-- Wich works fine with validator -->    ...    <input type="text" name="user[0][book][0][name]" title="name of one of the user's book" />  <!-- Wich does not work with validator -->  

My validator:

return [      'user.*.name' => 'required|min:1',      'user.*.email' => 'required|min:1',      'user.*.status' => 'required|min:1',      'user.*.book.*.name' => 'required|min:1',      'user.*.book.*.rating' => 'required|min:1'  ];  

Everything that validate user's information works fine, but it does not work when i'm trying to validate books data.

Is there a way to do what i'm trying to do ?

Thanks a lot 🙏 !

For the ones who needs it, here is the actual code:

<input type="text"      name="io[{{ $loop->index }}][name]"      title="name of one of the Insertion Order"  />  <!-- Wich works fine with validator -->    ... In a sub-foreach loop ...    <input type="text"      name="io[{{ $loop->parent->index }}][li][{{ $loop->index }}][name]"      title="name of one of the Insertion Order's Line Item's name"  />  <!-- Wich does not work with validator -->  

My validator:

return [      'campaign_name' => 'required|min:1',    // Static, works fine      'campaign_total_budget' => 'required',  // Static, works fine      'campaign_dates' => 'required',         // Static, works fine      'io.*.name' => 'required|min:1',        // One wildcard, works fine      'io.*.dates' => 'required|min:1',       // One wildcard, works fine      'io.*.budget' => 'required|min:1',      // One wildcard, works fine      'io.*.li.*.name' => 'required|min:1',   // Does not work      'io.*.li.*.dates' => 'required|min:1',  // Does not work      'io.*.li.*.budget' => 'required|min:1', // Does not work  ];  

Read in browser »
share on Twitter

How to add a loader for slow network in React

By Cassandra on Jul 01, 2021 03:14 am

I've created a subscription page and on submitting the page doesn't redirect like it is supposed to for people with slow network. Is there a way I can put a loader on the submit button to fix that because it ruins the user experience a little. This is how my submit function looks like.

const handleOnSubmit = (e) => {      e.preventDefault();      var body = {        data: {          name: name,          email: email,          contact_number: phone,          organization: organization,          designation: designation,        },      };        // Send mailchimp data to lambda      body = {        data: {          ...body.data,          mailchimp: {            email_address: email,            status: newsletter ? "subscribed" : "unsubscribed",            merge_fields: {              FNAME: name,              PHONE: phone,              MMERGE6: organization,              JOBTYPE: designation,              SIGNUPSOUR: Book.fields.contentpieceId,            },          },        },      };      setShowModal(false);      if (window) {        window.localStorage.setItem("@landing:sub-emai", email);      }        console.log(body);        if (!isDanger) {        axios          .post(            "{API}/prod/api",            body          )          .then((resp) => {            if (resp.status === 200) {              window.location.href = `/case-study/${eBook.fields.redirectUrl}`;            } else {              setError(true);            }          });      }    };  

Read in browser »
share on Twitter

django form: erorr passing model foreign into a form choice field

By Murcielago on Jul 01, 2021 02:56 am

I am working with a form and model containing two foreign keys from other models. The two fk fields need to be displayed as choices in the template. I was able to do this, the form gets rendered just fine, however, there is an error when trying to save it. A couple posts were informative but none did solve my issue. It seems that the issue is not where I searched for, or at least I am unable to locate and fix it.

here is what I have for models.py

class Partners(models.Model):        PartnerName = models.CharField(max_length=100, primary_key=True)      PartnerCategory = models.CharField(max_length=100)      PartnerPhoneNumber = models.CharField(max_length=100)      PartnerEmail = models.CharField(max_length=100)      PartnerCompany = models.CharField(max_length=100, default='non')      PartnerAdressLine = models.CharField(max_length=100, default="NA")      PartnerZipCode = models.CharField(max_length=100, default="NA")      PartnerCity = models.CharField(max_length=100, default="NA")      PartnerState = models.CharField(max_length=100, default="NA")          def __str__(self):             return str(self.PartnerName)      class Products(models.Model):        ProductName = models.CharField(max_length=100, primary_key=True)      ProductUnit = models.CharField(max_length=100, default="NA")      ProductCategory = models.CharField(max_length=100)      ProductTagNumber = models.IntegerField(max_length=100)      StockOnHand = models.FloatField(max_length=100)        def __str__(self):                 return str(self.ProductName)      class Sales(models.Model):      SaleID = models.AutoField(max_length=100, primary_key=True)      SaleProductName= models.ForeignKey(Products, on_delete=models.CASCADE)      SalePartnersName = models.ForeignKey(Partners,on_delete=models.CASCADE)      SalePartnerBusinessName = models.CharField(max_length=100,default="NA")      SaleQuantity = models.FloatField(max_length=100,default="NA")      SaleUnit = models.CharField(max_length=100,default="NA")      SaleNetAmount = models.FloatField(max_length=100)        SalePartnerCommission = models.FloatField(max_length=100)      SaleDate = models.DateField(default=datetime.date.today)      SaleStatus = models.CharField(max_length=100,default="Ongoing")    

And here is my views.py

def RecordNewDealView(request):            if request.method == 'POST':              form = RecordNewDealForm(request.POST)              if form.is_valid():                    form.save()              return redirect('my_deals.html')          else:              form = RecordNewDealForm()              context = {'form': form,}                return render(request, 'record_new_deal.html', context)  

and finally here is the forms.py file

brokers_df = pd.DataFrame(list(Partners.objects.all().values()))  brokers = brokers_df[brokers_df['PartnerCategory'] == 'Broker']      items_list1 = brokers['PartnerName'].tolist()  items_list2 = brokers['PartnerName'].tolist()    CHOICES_OF_BROKERS = [list(x) for x in zip(items_list1, items_list2)]  CHOICES_OF_BROKERS.insert(0,('Not involved','Not involved'))      class RecordNewDealForm(forms.ModelForm):             SaleStatus = forms.CharField(widget=forms.Select(choices=SALE_STATUS_CHOICES))         SalesBroker = forms.CharField(widget=forms.Select(choices=CHOICES_OF_BROKERS))         SaleProductName = forms.ModelChoiceField(queryset=Products.objects.all().values_list('ProductName', flat=True))         SalePartnerName = forms.ModelChoiceField(queryset=Partners.objects.all().values_list('PartnerName', flat=True))         class Meta:              model = Sales              fields = ("SaleID",                        "SaleProductName","SalePartnerName",                        "SalePartnerBusinessName",                        "SaleQuantity",                        "SaleUnit","SaleNetAmount",                        "SalePartnerCommission", "SaleDate"                         )  

This output the following error when trying to save the form to db

Cannot assign "'Gummies'": "Sales.SaleProductName" must be a "Products" instance.  

I am unfamiliar with this issue and again, I could not find something that solved my issue. It's been now a couple days and I cannot identify what's wrong wit this code, any help would be greatly appreciated!

UPDATE: I came accross this post Cannot assign must be a instance Django so I tried modifying my fk in the model as such:

SaleProductName= models.ForeignKey(Products, related_name='products_catalogue', on_delete=models.CASCADE,  blank=True, null=True)      SalePartnersName = models.ForeignKey(Partners, related_name='partner_name', on_delete=models.CASCADE, blank=True, null=True)  

the same error is getting output when trying to save the form


Read in browser »
share on Twitter

Mongoose In ArrayElemAt Issue In Aggregate

By Muhammad Nabeel on Jul 01, 2021 02:14 am

temporaryshifts is equal to

[{_id:123,  arr:[{_id:123321,name:"Bluh Bluh",date:"bluh bluh"}]  }]  

so i want to access temporaryshifts[0].arr[0] but i dont know how to access

$project:{  shiftArr:{$arrayElemAt:['$temporaryshifts',0]}  }  

Read in browser »
share on Twitter

Too many open files despite a sufficiently high open files limit

By Arash Payan on Jul 01, 2021 01:45 am

I've written a server in Go that routinely stats files, copies files and opens network connections. Sometimes the number of open files (open sockets, files, etc.) can go up to a couple thousand under extremely heavy load. Accordingly, when I start the process I change the soft and hard open file limit from the default of 1024:4096 to 32768:32768, respectively (prlimit --pid <the process id> --nofile=32768:32768). I've verified that the limits do actually get updated.

The problem is that sometimes when there are only a few hundred open files (as verified by running lsof in a continuous loop while the program works), the program starts to receive 'too many open files' errors during its operation. I've seen the error returned as a result of calling os.Open and also from the AWS SDK when it attempts to HeadObject an object on S3 (socket: too many open files).

Is there some other variable/limit that I'm not accounting for that would cause 'too many open files' even though the limit is at 32768 and only a few hundred are actually shown to be open?

Other info

  • Red Hat Enterprise Linux Server 7.6
  • Kernel 3.10.0-957.el7.x86_64 (I know it's ancient. It's not in my control)
  • Go version 1.16.5
  • The network connections are mostly calls to S3 using the AWS SDK v1

Read in browser »
share on Twitter

Question about multiplication order between delta and activation

By Kay on Jul 01, 2021 01:29 am

I have been studying deep learning with Michael Nielsen's online book. For the back-propagation part, he wrote a line of code below: nabla_w[-1] = np.dot(delta, activations[-2].transpose()) This code does not sound clear to me. From his book, ∂𝐶/∂𝑤^𝑙_{𝑗𝑘} = 𝑎^{𝑙−1}𝑘 * 𝛿^𝑙_𝑗, and this equation can be proven with the chain rule. So, I have assumed activations[-2] * delta in order, not vice versa. For example, suppose activations[-2] is 3x1 matrix, and delta 2x1. activations[-2] * delta is incomputable because of their matrix forms, while delta * activations[-2]^T is 2x3 matrix. Can you give me a insight into 1) There is no difference at all between 1) ∂𝐶/∂𝑤^𝑙{𝑗𝑘} = 𝑎^{𝑙−1}𝑘 * 𝛿^𝑙_𝑗, and 2) ∂𝐶/∂𝑤^𝑙{𝑗𝑘} = 𝛿^𝑙_𝑗 * (𝑎^{𝑙−1}_k)^T?


Read in browser »
share on Twitter

IntelliJ 2019.2 expecting to do the soft-wrap every time

By Remo on Jul 01, 2021 01:23 am

When I run the application, logs are printing and it's not wrapped. So I have enabled View -> Active Editor -> Soft-Wrap.

It's wrapping it temporarily. If I try to run application again, it's not wrapping and again I am enabling the soft-wrap.

Is there any permanent solution?


Read in browser »
share on Twitter

I'm having problems with Epic games and unreal engine. specifically with my projects not showing up

By TurnBack Corp on Jul 01, 2021 12:43 am

Hey I am brand new to unreal engine 5 and unreal in general. I would love to start making games so right now I am following a tutorial on yt. it asked us to download a character for our game and when i tried I couldnt find my project. I can open the game project through files but i still cant add the assets from the market place.Here are the screenshots


Read in browser »
share on Twitter

which content-type i need to select to post a form-data which contains(binary and json data) in postman?

By Sravani on Jun 30, 2021 11:21 am

If I select content-type: application/json then I pass my data into a body as a raw(application/json) then my code works that means it's posting my data into the database, but my data is mixed means binary and form-data, if I use content-type: multipart/form-data it's showing following error. How to resolve this error?

Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null (SQL: insert into books (name, image, price, title, quantity, ratings, author, description, user_id, updated_at, created_at) values (?, ?, ?, ?, ?, ?, ?, ?, 1, 2021-06-30 20:40:15, 2021-06-30 20:40:15)) in file C:\Users\VICKY\Desktop\8\laravel-bookstore\vendor\laravel\framework\src\Illuminate\Database\Connection.php on line 692

Header section data i am posting

BooksController.php

<?php    namespace App\Http\Controllers;    use Illuminate\Http\Request;  use App\Models\Books;  use App\Models\User;  use App\Http\Requests;  use Symfony\Component\HttpFoundation\Response;  use App\Http\Resources\Books as BooksResource;  use App\Http\Middleware\Authenticate;    class BooksController extends Controller  {      /**       * Display a listing of the resource.       *       * @return \Illuminate\Http\Response       */      public function DisplayBooks()      {          $books=Books::all();          return User::find($books->user_id=auth()->id())->books;      }        /**       * Show the form for creating a new resource.       *       * @return \Illuminate\Http\Response       */      public function AddBooks(Request $request)      {          $book=new Books();          $book->name=$request->input('name');          $book->image=$request->input('image');          $book->price=$request->input('price');          $book->title=$request->input('title');          $book->quantity=$request->input('quantity');          $book->ratings=$request->input('ratings');          $book->author=$request->input('author');          $book->description=$request->input('description');          $book->user_id = auth()->id();          $book->save();          return new BooksResource($book);      }        /**       * Display the specified resource.       *       * @param  int  $id       * @return \Illuminate\Http\Response       */      public function ShowBook($id)      {          $book=Books::findOrFail($id);          if($book->user_id==auth()->id())              return new BooksResource($book);          else{              return response()->json([                  'error' => 'UnAuthorized/invalid id'], 401);              }      }        /**       * Update the specified resource in storage.       *       * @param  \Illuminate\Http\Request  $request       * @param  int  $id       * @return \Illuminate\Http\Response       */      public function UpdateBook(Request $request, $id)      {          $book=Books::findOrFail($id);          if($book->user_id==auth()->id()){              $book->name=$request->input('name');              $book->image=$request->input('image');              $book->price=$request->input('price');              $book->title=$request->input('title');              $book->quantity=$request->input('quantity');              $book->ratings=$request->input('ratings');              $book->author=$request->input('author');              $book->description=$request->input('description');              $book->save();              return new BooksResource($book);          }          else          {              return response()->json([                  'error' => ' Book is not available ith id'], 404);          }      }        /**       * Remove the specified resource from storage.       *       * @param  int  $id       * @return \Illuminate\Http\Response       */      public function DeleteBook($id)      {          $book=Books::findOrFail($id);          if($book->user_id==auth()->id()){              if($book->delete()){                  return response()->json(['message'=>'Deleted'],201);              }          }          else{              return response()->json([                  'error' => ' Method Not Allowed/invalid Book id'], 405);          }      }  }    

Books migration

<?php    use Illuminate\Database\Migrations\Migration;  use Illuminate\Database\Schema\Blueprint;  use Illuminate\Support\Facades\Schema;    class CreateBooksTable extends Migration  {      /**       * Run the migrations.       *       * @return void       */      public function up()      {          Schema::create('books', function (Blueprint $table) {              $table->increments('id');              $table->string('name')->length(50)->unique();              $table->binary('image');              $table->integer('price')->unsigned();              $table->text('title');              $table->integer('quantity')->length(2)->unsigned();              $table->integer('ratings')->length(2)->unsigned();              $table->string('author');              $table->longText('description');              $table->unsignedBigInteger('user_id');              $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');              $table->timestamps();          });      }        /**       * Reverse the migrations.       *       * @return void       */      public function down()      {          Schema::dropIfExists('books');      }  }    

Books.php (model)

<?php    namespace App\Models;    use Illuminate\Database\Eloquent\Factories\HasFactory;  use Illuminate\Database\Eloquent\Model;    class Books extends Model  {      use HasFactory;      protected $fillable = [          'name',          'image',          'price',          'title',          'quantity',          'ratings',          'author' ,          'description'      ];      protected $hidden = [          'password',          'remember_token',          'updated_at'      ];        /**       * The attributes that should be cast to native types.       *       * @var array       */      protected $casts = [          'email_verified_at' => 'datetime',      ];        /**       * Return a key value array, containing any custom claims to be added to the JWT.       *       * @return array       */      public function getJWTCustomClaims()      {          return ;      }        /**       * Get the identifier that will be stored in the subject claim of the JWT.       *       * @return mixed       */      public function getJWTIdentifier()      {          return $this->getKey();      }        //inverse one to many     public function user(){         return $this->belongsTo(User::class);     }  }    

Read in browser »
share on Twitter

Developing oculus application in Unity using mrtk,no display when streaming debugging

By 陆赛丹 on Jun 30, 2021 05:21 am

I am creating a VR application for Oculus Quest using Unity3D.And I am trying to speed up the process using MRTK,but when streaming debugging in Unity Editor,there is no diaplay.But when I build a package whether a PC package or an apk,it runs normally.What should I set up in my project?


Read in browser »
share on Twitter




Recent Articles:

paste a file with existing file name in vscode cause them to rename instead of replace existing file
How to minimize a war file?
Gitlab CI/CD cannot git push from .gitlab-ci.yml
Images with "display: none" blinking in Firefox before displaying
What is correct example to use Multi-cURL?
Twitter
Facebook
Website
Copyright © 2021 reader, All rights reserved.
You are receiving this email because you opted in via our website.

Our mailing address is:
reader
88 CELICA STREET
Davao 8000
Philippines

Add us to your address book


Want to change how you receive these emails?
You can update your preferences or unsubscribe from this list.

Email Marketing Powered by Mailchimp

No comments:

Post a Comment