问:
Hydration failed because the initial UI does not match nextjs
How to solve this error? it says thats its in my html/xml file

the error is : Hydration failed because the initial UI does not match what was rendered on the server

I tried to change the structure of the file but i dont have much idea of what can i do, because this is just a test for a future project, so i didnt care about the layout, anyways this error got me mad, heres the code:

```<code>import React, { useState, useEffect } from "react";
import axios from "axios";
import * as PhosphorIcons from 'phosphor-react'

function HomePage(): JSX.Element {

  const [providers, setProviders] = useState([] as any[])

  useEffect(() => {
    axios.get('http://localhost:5140/providers/list')
    .then(res => {
      console.log(res)
      setProviders(res.data)
    }).catch(err => {
      console.log(err)
    })
  }, [])

  const renderedProviders = Object.values(providers).map(provider => {
    return (
      <div
        className="card"
        style={{ width: "18rem"}}
        key={provider.id}
      >
        <img className="card-img-top" style={{height: '100%'}} src={provider.photo!=null ? provider.photo: 'https://h-o-m-e.org/wp-content/uploads/2022/04/Blank-Profile-Picture-1.jpg' } alt="Foto do Prestador"/>
        <div className="card-body">
          <h3>{provider.name}</h3>
          <p>{provider.location.city}</p>
          <h5>{provider.service.type}</h5>

          {(() => {
        if (provider.starAverage === 5) {
          return (
            <p><PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" /></p>
          )
        }
        if (provider.starAverage === 4) {
          return (
            <p><PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" /></p>
          )
        }
        if (provider.starAverage === 3) {
          return (
            <p><PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" /></p>
          )
        }
        if (provider.starAverage === 2) {
          return (
            <p><PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" /></p>
          )
        }
        if (provider.starAverage === 1) {
          return (
            <p><PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
              <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" /></p>
          )
        }
        if (provider.starAverage === 0 || provider.starAverage === null) {
          return (
            <p> <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />
              <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" /></p>
          )
        }
      })()}

          <p>Telefone: {provider.phone}</p>
        </div>
      </div>
    );
  });
  return (
    <>

    <div>

      <br></br>
      <h3 style={{fontSize: "40px", textAlign: "center"}}>Lista de Prestadores:</h3>
      <br></br>
    <div className="d-flex flex-row flex-wrap justify-content-between">
      {renderedProviders}
      </div>

    </div>

      </>

  )
}

export default HomePage;

</code>```

Body:
How to solve this error? it says thats its in my html/xml file

the error is : Hydration failed because the initial UI does not match what was rendered on the server

I tried to change the structure of the file but i dont have much idea of what can i do, because this is just a test for a future project, so i didnt care about the layout, anyways this error got me mad, heres the code:

import React, { useState, useEffect } from "react";
import axios from "axios";
import * as PhosphorIcons from 'phosphor-react'

function HomePage(): JSX.Element {

  const [providers, setProviders] = useState([] as any[])

  useEffect(() => {
    axios.get('http://localhost:5140/providers/list')
    .then(res => {
      console.log(res)
      setProviders(res.data)
    }).catch(err => {
      console.log(err)
    })
  }, [])

  const renderedProviders = Object.values(providers).map(provider => {
    return (

{provider.name}

{provider.location.city}

{provider.service.type}

          {(() => {
        if (provider.starAverage === 5) {
          return (

<PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />

          )
        }
        if (provider.starAverage === 4) {
          return (

<PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />

          )
        }
        if (provider.starAverage === 3) {
          return (

<PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />

          )
        }
        if (provider.starAverage === 2) {
          return (

<PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />

          )
        }
        if (provider.starAverage === 1) {
          return (

<PhosphorIcons.Star size={26} color="#2dc88c" weight="fill" />
              <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />

          )
        }
        if (provider.starAverage === 0 || provider.starAverage === null) {
          return (

 <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />
              <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />
            <PhosphorIcons.Star size={26} color="#ADADAD" weight="fill" />

          )
        }
      })()}

Telefone: {provider.phone}

    );
  });
  return (
    <>

Lista de Prestadores:

      {renderedProviders}

      </>

  )
}

export default HomePage;


来源: stackexchange

问:
Convert image to utf8 base64 encoded string
I currently have an image uri from the expo impage picker library:

```<code>    return ImagePicker.launchImageLibraryAsync({
        allowsEditing: false,
        base64: true,
        quality: 1,
    })
</code>```

I need to then convert that selected image to a base 64 string. I tried using RNFS library to do this conversion:

```<code>const imageBase64 = await RNFS.readFile(image, 'base64').then(res => {
   return res
});
</code>```

but the resulting string does not match image encoding I see here: https://www.base64-image.de/

I think I need to encode the image using utf-8 - is there some way I can do this?

ContentLicense: CC BY-SA 4.0

Body:
I currently have an image uri from the expo impage picker library:

    return ImagePicker.launchImageLibraryAsync({
        allowsEditing: false,
        base64: true,
        quality: 1,
    })

I need to then convert that selected image to a base 64 string. I tried using RNFS library to do this conversion:

const imageBase64 = await RNFS.readFile(image, 'base64').then(res => {
   return res
});

but the resulting string does not match image encoding I see here: https://www.base64-image.de/

I think I need to encode the image using utf-8 - is there some way I can do this?


问:
Flutter applying shadow inside of the image (Bottom Gradient Shadow)
I am trying to apply shadow fade under an image in Flutter.
I believe it has a different naming in the Flutter world and I am unable to find it.
I think it can be resolved using a ShaderMask or Stacking a container with Linear gradient BoxDecoration.
I have achieved the following result using Stack, Linear Gradient in a container with box decoration. Is there any other way to achieve similar result?
As you can see with my result I am applying the shadow effect to the whole block , how can I apply this only for the image?
Thanks in advance.Image with shadow under it

Similar problem is posted in stackoverflow but it solves the problem for both top and bottom gradient. top and bottom gradient

I have already tried using Stacking image and Container with Linear gradient decoration I am almost sure that it is not the solution.

Image as an example


问:
How can I run the Gradle Daemon within an Eclipse Application?
When executing a Gradle build, I would like to use and from Gradle. But the Ant tasks I intend to use are Eclipse Platform Contributions. This means that the tasks will call out into OSGi. In order to make this happen, I would need to run the Gradle Daemon within OSGi, specifically as an Eclipse Application. I am wondering if anyone has done this and if it is possible

I have read the Gradle Tooling API, but it only describes how the Gradle Connector calls the Daemon for a default JVM.


问:
how to change the css of a child of an iframe using the youtube iframe api
I need to hide the youtube annotations, but what they say in the youtube iframe api, what would it be, rel=0, does not work</p>
```<code>.ytp-show-cards-title {display: none !important}
</code>```

Body:
I need to hide the youtube annotations, but what they say in the youtube iframe api, what would it be, rel=0, does not work

.ytp-show-cards-title {display: none !important}


问:
Stripe Apple Pay Integration

How do I retrieve the client Secret?

a problem that doesn't let me sleep:

```<code>extension CheckoutViewController {
  func applePayContext(_ context: STPApplePayContext, didCreatePaymentMethod paymentMethod: StripeAPI.PaymentMethod, paymentInformation: PKPayment, completion: @escaping     STPIntentClientSecretCompletionBlock) {

 let clientSecret = ... // Retrieve the PaymentIntent client secret from your backend (see Server-side step above)
    // Call the completion block with the client secret or an error
    completion(clientSecret, error);
}

func applePayContext(_ context: STPApplePayContext, didCompleteWith status: STPApplePayContext.PaymentStatus, error: Error?) {
      switch status {
    case .success:
        // Payment succeeded, show a receipt view
        break
    case .error:
        // Payment failed, show the error
        break
    case .userCancellation:
        // User canceled the payment
        break
    @unknown default:
        fatalError()
    }
}
</code>```

}

**I get this error: StripeApplePay/PaymentIntent+API.swift:30: Assertion failed: secret format does not match expected client secret formatting. So I guess that'S why it doesn't work

I wanted to incorporate Stripe in my Apple Pay. However the Stripe documentation only tells me to retrieve the client data but not how and through which objects. Would be amazing if you could help :*(**

Title: Stripe Apple Pay Integration

Body:
How do I retrieve the client Secret?

a problem that doesn't let me sleep:

extension CheckoutViewController {
  func applePayContext(_ context: STPApplePayContext, didCreatePaymentMethod paymentMethod: StripeAPI.PaymentMethod, paymentInformation: PKPayment, completion: @escaping     STPIntentClientSecretCompletionBlock) {

 let clientSecret = ... // Retrieve the PaymentIntent client secret from your backend (see Server-side step above)
    // Call the completion block with the client secret or an error
    completion(clientSecret, error);
}

func applePayContext(_ context: STPApplePayContext, didCompleteWith status: STPApplePayContext.PaymentStatus, error: Error?) {
      switch status {
    case .success:
        // Payment succeeded, show a receipt view
        break
    case .error:
        // Payment failed, show the error
        break
    case .userCancellation:
        // User canceled the payment
        break
    @unknown default:
        fatalError()
    }
}

}

**I get this error: StripeApplePay/PaymentIntent+API.swift:30: Assertion failed: secret format does not match expected client secret formatting. So I guess that'S why it doesn't work

I wanted to incorporate Stripe in my Apple Pay. However the Stripe documentation only tells me to retrieve the client data but not how and through which objects. Would be amazing if you could help :*(**


问:
Does Python lazily evaluate 'AND' conditionals?
I'm currently solving a combinatorics problem which I have boiled down to a smaller, more manageable task of studying the asymptotic behavior of the problem. The code has more depth to it than what I've shared but the following blocks target my question.

I'm currently testing my code with ~1E7 iterations but the final product will need to loop through ~1E11 iterations. In the following code examples, <condition_1> is used to reduce the search space down to a sufficient set of size << ~1E7. A partial computation of one of the results I need is used to see if it satisfies an inequality; since I only need to store key-value pairs which satisfy the inequality, I use <condition_2> to decrease the load on memory.

I had implemented two versions of my code. I am currently using Way 2 in hopes of being more performant. For my general knowledge: Will python 'lazily' evaluate the conditional, ie. if the first condition is false -- not compute the second condition?

# Way 1
for i in range(N):
    <computation related to condition_2, used in code block>
    if <condition_1> & <condition_2>

        <storing results in dictionary>
```
<pre class="lang-py prettyprint-override"><code># Way 2
for i in range(N):
    if <condition_1>:
        <computation related to condition_2, used in code block>
        if <condition_2>:
            <code block>
            <storing results in dictionary>
</code>```

Body:
I'm currently solving a combinatorics problem which I have boiled down to a smaller, more manageable task of studying the asymptotic behavior of the problem. The code has more depth to it than what I've shared but the following blocks target my question.

I'm currently testing my code with ~1E7 iterations but the final product will need to loop through ~1E11 iterations. In the following code examples, <condition_1> is used to reduce the search space down to a sufficient set of size << ~1E7. A partial computation of one of the results I need is used to see if it satisfies an inequality; since I only need to store key-value pairs which satisfy the inequality, I use <condition_2> to decrease the load on memory.

I had implemented two versions of my code. I am currently using Way 2 in hopes of being more performant. For my general knowledge: Will python 'lazily' evaluate the conditional, ie. if the first condition is false -- not compute the second condition?

# Way 1
for i in range(N):
    <computation related to condition_2, used in code block>
    if <condition_1> & <condition_2>

        <storing results in dictionary>

# Way 2
for i in range(N):
    if <condition_1>:
        <computation related to condition_2, used in code block>
        if <condition_2>:

            <storing results in dictionary>


问:
How can I select x characters and replace them with another string in a docx file using PHPWord?
Here is what I had used to retrieve the text from a .docx file.

```<code><?php

use PhpOffice\PhpWord\Element\AbstractContainer;
use PhpOffice\PhpWord\Element\Text;
use PhpOffice\PhpWord\IOFactory as WordIOFactory;

require_once 'vendor/autoload.php';

$source = 'test/example.doc';
$objReader = WordIOFactory::createReader('MsDoc');
$phpWord = $objReader->load($source); // instance of \PhpOffice\PhpWord\PhpWord
$text = '';

function getWordText($element) {
    $result = '';
    if ($element instanceof AbstractContainer) {
        foreach ($element->getElements() as $element) {
            $result .= getWordText($element);
        }
    } elseif ($element instanceof Text) {
        $result .= $element->getText();
    }
    // and so on for other element types (see src/PhpWord/Element)

    return $result;
}

foreach ($phpWord->getSections() as $section) {
    foreach ($section->getElements() as $element) {
        $text .= getWordText($element);
    }
}

echo $text;
</code>```

Now, I would like to take all the content of this file and replace it with another content without losing the format of the doc or .docx file (i.e. style, design etc...). How can I do this?

Body:
Here is what I had used to retrieve the text from a .docx file.

<?php

use PhpOffice\PhpWord\Element\AbstractContainer;
use PhpOffice\PhpWord\Element\Text;
use PhpOffice\PhpWord\IOFactory as WordIOFactory;

require_once 'vendor/autoload.php';

$source = 'test/example.doc';
$objReader = WordIOFactory::createReader('MsDoc');
$phpWord = $objReader->load($source); // instance of \PhpOffice\PhpWord\PhpWord
$text = '';

function getWordText($element) {
    $result = '';
    if ($element instanceof AbstractContainer) {
        foreach ($element->getElements() as $element) {
            $result .= getWordText($element);
        }
    } elseif ($element instanceof Text) {
        $result .= $element->getText();
    }
    // and so on for other element types (see src/PhpWord/Element)

    return $result;
}

foreach ($phpWord->getSections() as $section) {
    foreach ($section->getElements() as $element) {
        $text .= getWordText($element);
    }
}

echo $text;

Now, I would like to take all the content of this file and replace it with another content without losing the format of the doc or .docx file (i.e. style, design etc...). How can I do this?


问:
Getting same values when duplicating a reactive form
I am new to angular and I have followed a tutorial to create a reactive form in which I have an input and if I click a button, this input is duplicated.

The front looks like this:

```<code>    <div class="col-md-6">
      <form [formGroup]="becDonorsForm">
        <div formArrayName="bec_donors">
          <div class="row" *ngFor="let item of becDonors.controls; let becDonorsIndex=index" [formGroupName]="becDonorsIndex">

          <div class="col-md-2">
            <fieldset>
              <legend style="font-size:12px;">ph:donor id</legend>
              <input type="text" pInputText  style="width:100%"  formControlName="becDonorId" />
            </fieldset>
          </div>
          <div  class="col-md-1">
            <button pButton type="button" (click)="addbecDonorID()"  icon="pi pi-plus" iconPos="center" style="margin-bottom:1px;"></button>
          </div>
          <div *ngIf="becDonorsIndex>0" class="col-md-1">
            <button pButton type="button" icon="pi pi-minus" iconPos="center" style="margin-bottom:1px;" (click)="deletebecDonorID(becDonorsIndex)"></button>
          </div>
          </div>
        </div>
      </form>
    </div>
</code>```

Basically I have an input with a button to add another one (duplicate it) and another button to delete it in case it's not the only one.

This is the backend:

```<code>becDonorsForm: FormGroup;
  ngOnInit(): void
  {
    this.becDonorsForm = this.fb.group({
      bec_donors: this.fb.array([this.fb.group({becDonorId:''})]),
    })
  }
  addbecDonorID() {
    this.becDonors.push(this.fb.group({becDonorId:''}));
  }
  deletebecDonorID(index) {
    this.becDonors.removeAt(index);
  }
  get becDonors() {
    return this.becDonorsForm.get('bec_donors') as FormArray;
  }
</code>```

And up to here everything is great, it works as expected, the problem is that I tried to extend it by adding a select, as follows:

```<code>      <form [formGroup]="becDonorsForm">
        <div formArrayName="bec_donors">
          <div class="row" *ngFor="let item of becDonors.controls; let becDonorsIndex=index" [formGroupName]="becDonorsIndex">
          <div class="col-md-4">
            <fieldset>

<--This-->
              <legend style="font-size:12px;">ph:BECS</legend>
              <ng-container style="min-width: 100%;" *ngIf="localSystemBECS">
                <p-dropdown styleClass="w-100"   [ngModelOptions]="{standalone: true}" [options]="localSystemBECS.localSystem" [(ngModel)]="selectedBEC" optionLabel="name"></p-dropdown>
              </ng-container>
            </fieldset>
          </div>

          <div class="col-md-2">
            <fieldset>
              <legend style="font-size:12px;">ph:donor id</legend>
              <input type="text" pInputText  style="width:100%"  formControlName="becDonorId" />
            </fieldset>
          </div>
          <div  class="col-md-1">
            <button pButton type="button" (click)="addbecDonorID()"  icon="pi pi-plus" iconPos="center" style="margin-bottom:1px;"></button>
          </div>
          <div *ngIf="becDonorsIndex>0" class="col-md-1">
            <button pButton type="button" icon="pi pi-minus" iconPos="center" style="margin-bottom:1px;" (click)="deletebecDonorID(becDonorsIndex)"></button>
          </div>
          </div>
        </div>
      </form>
</code>```

On the back, I did not add anything other than

```<code>localSystemBECS : LocalSystemsBECSResponse;
selectedBEC: LocalSystemElement;
</code>```

And a method that fills the first data array.

I guess I have to do something similar to what I already have from

```<code>   bec_donors: this.fb.array([this.fb.group({becDonorId:''})])
</code>```

but I don't know how to expand it, I would appreciate your help

Body:
I am new to angular and I have followed a tutorial to create a reactive form in which I have an input and if I click a button, this input is duplicated.

The front looks like this:

      <form [formGroup]="becDonorsForm">

            <fieldset>
              <legend style="font-size:12px;">ph:donor id</legend>
              <input type="text" pInputText  style="width:100%"  formControlName="becDonorId" />
            </fieldset>

            <button pButton type="button" (click)="addbecDonorID()"  icon="pi pi-plus" iconPos="center" style="margin-bottom:1px;"></button>

0" class="col-md-1">
            <button pButton type="button" icon="pi pi-minus" iconPos="center" style="margin-bottom:1px;" (click)="deletebecDonorID(becDonorsIndex)"></button>

      </form>

Basically I have an input with a button to add another one (duplicate it) and another button to delete it in case it's not the only one.

This is the backend:

becDonorsForm: FormGroup;
  ngOnInit(): void
  {
    this.becDonorsForm = this.fb.group({
      bec_donors: this.fb.array([this.fb.group({becDonorId:''})]),
    })
  }
  addbecDonorID() {
    this.becDonors.push(this.fb.group({becDonorId:''}));
  }
  deletebecDonorID(index) {
    this.becDonors.removeAt(index);
  }
  get becDonors() {
    return this.becDonorsForm.get('bec_donors') as FormArray;
  }

And up to here everything is great, it works as expected, the problem is that I tried to extend it by adding a select, as follows:

      <form [formGroup]="becDonorsForm">

            <fieldset>

<--This-->
              <legend style="font-size:12px;">ph:BECS</legend>
              <ng-container style="min-width: 100%;" *ngIf="localSystemBECS">

              </ng-container>
            </fieldset>

            <fieldset>
              <legend style="font-size:12px;">ph:donor id</legend>
              <input type="text" pInputText  style="width:100%"  formControlName="becDonorId" />
            </fieldset>

            <button pButton type="button" (click)="addbecDonorID()"  icon="pi pi-plus" iconPos="center" style="margin-bottom:1px;"></button>

0" class="col-md-1">
            <button pButton type="button" icon="pi pi-minus" iconPos="center" style="margin-bottom:1px;" (click)="deletebecDonorID(becDonorsIndex)"></button>

      </form>

On the back, I did not add anything other than

localSystemBECS : LocalSystemsBECSResponse;
selectedBEC: LocalSystemElement;

And a method that fills the first data array.

I guess I have to do something similar to what I already have from

   bec_donors: this.fb.array([this.fb.group({becDonorId:''})])

but I don't know how to expand it, I would appreciate your help


问:
PHP API Error 35 Send failure: Operation not supported
Recently, I started getting the error with code 35 that says "Send failure: Operation not supported" on my website while trying to access an API.

What is causing this error and how do I fix it? I have a feeling it is something to do with the server and not my PHP code since I made no changes to my PHP code before this error started happening.

```<code><?php
     $url = "https://example.com/api.php";
     $curl = curl_init();
     curl_setopt_array($curl, array(
     CURLOPT_URL => $url,
     CURLOPT_RETURNTRANSFER => true,  // Capture response.
     CURLOPT_ENCODING => "",  // Accept gzip/deflate/whatever.
     CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4, // Speed up curl - WAS POTENTIALLY CAUSING "COULD NOT RESOLVE HOST" ERRORS
     CURLOPT_TCP_FASTOPEN => 1, // Speeeeed up curl
     CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible;)',
     CURLOPT_MAXREDIRS => 10,
     CURLOPT_CONNECTTIMEOUT, 0, //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
     CURLOPT_TIMEOUT => 0, // The maximum number of seconds to allow cURL functions to execute. Use 0 to wait indefinitely.
     CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
     CURLOPT_HEADER => true,
     CURLOPT_CUSTOMREQUEST => "GET",
     CURLOPT_HTTPHEADER => $headers,
     ));
     if (FALSE === $curl){
            throw new Exception('Failed to initialize');
     }
     $result = curl_exec($curl);

     $headerSize = curl_getinfo( $curl, CURLINFO_HEADER_SIZE);
     $headerStr = substr($result, 0, $headerSize);
     $bodyStr = substr($result, $headerSize);

     curl_close($curl);
     $json = json_decode($bodyStr, true);

     print_r($json);

    ?>
</code>```

Body:
Recently, I started getting the error with code 35 that says "Send failure: Operation not supported" on my website while trying to access an API.

What is causing this error and how do I fix it? I have a feeling it is something to do with the server and not my PHP code since I made no changes to my PHP code before this error started happening.

<?php
     $url = "https://example.com/api.php";
     $curl = curl_init();
     curl_setopt_array($curl, array(
     CURLOPT_URL => $url,
     CURLOPT_RETURNTRANSFER => true,  // Capture response.
     CURLOPT_ENCODING => "",  // Accept gzip/deflate/whatever.
     CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4, // Speed up curl - WAS POTENTIALLY CAUSING "COULD NOT RESOLVE HOST" ERRORS
     CURLOPT_TCP_FASTOPEN => 1, // Speeeeed up curl
     CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible;)',
     CURLOPT_MAXREDIRS => 10,
     CURLOPT_CONNECTTIMEOUT, 0, //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
     CURLOPT_TIMEOUT => 0, // The maximum number of seconds to allow cURL functions to execute. Use 0 to wait indefinitely.
     CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
     CURLOPT_HEADER => true,
     CURLOPT_CUSTOMREQUEST => "GET",
     CURLOPT_HTTPHEADER => $headers,
     ));
     if (FALSE === $curl){
            throw new Exception('Failed to initialize');
     }
     $result = curl_exec($curl);

     $headerSize = curl_getinfo( $curl, CURLINFO_HEADER_SIZE);
     $headerStr = substr($result, 0, $headerSize);
     $bodyStr = substr($result, $headerSize);

     curl_close($curl);
     $json = json_decode($bodyStr, true);

     print_r($json);

    ?>


问:
SmarterCSV end of file reached, but ruby's CSV library can process the file
I have two CSV files which are basically the same, but for some reason, SmarterCSV can not read the one named bad_file Here is a Gist of both files. Ruby's native CSV library can read bad_file no problem.

Before processing each file. I strip everything above the header row using the below code:

  def self.clean(file)
    if (csv = File.read(file).gsub!(/\A.+?(?=^Date,)/m, ''))
      tempfile = Tempfile.new('file_name')
      tempfile.write(csv)
      tempfile
    else
      file
    end
  end
```
<p>I then pass that file into smarter CSV like this:</p>
<pre class="lang-rb prettyprint-override"><code>    File.open(file, encoding: 'bom|utf-8') do |f|
      chunk = SmarterCSV.process(f, {
                                   verbose: true,
                                   remove_empty_hashes: true,
                                   col_sep: :auto,
                                   force_utf8: true,
                                   force_simple_split: true,
                                   strip_chars_from_headers: /[\-"\xEF\xBB\xBF]/,
                                   duplicate_header_suffix: ''
                                 })
    end
</code>```

I can not figure out what is even differnt about the CSV files, let alone why SmarterCSV can't process the bad one. Also, if anyone has a better method for stripping the unneeded info from the top of the spreadsheet, that could solve this problem right there.

Body:
I have two CSV files which are basically the same, but for some reason, SmarterCSV can not read the one named bad_file Here is a Gist of both files. Ruby's native CSV library can read bad_file no problem.

Before processing each file. I strip everything above the header row using the below code:

  def self.clean(file)
    if (csv = File.read(file).gsub!(/\A.+?(?=^Date,)/m, ''))
      tempfile = Tempfile.new('file_name')
      tempfile.write(csv)
      tempfile
    else
      file
    end
  end

I then pass that file into smarter CSV like this:

    File.open(file, encoding: 'bom|utf-8') do |f|
      chunk = SmarterCSV.process(f, {
                                   verbose: true,
                                   remove_empty_hashes: true,
                                   col_sep: :auto,
                                   force_utf8: true,
                                   force_simple_split: true,
                                   strip_chars_from_headers: /[\-"\xEF\xBB\xBF]/,
                                   duplicate_header_suffix: ''
                                 })
    end

I can not figure out what is even differnt about the CSV files, let alone why SmarterCSV can't process the bad one. Also, if anyone has a better method for stripping the unneeded info from the top of the spreadsheet, that could solve this problem right there.


问:
Laravel get model relations with select raw query
So I have copied a function from the internet to get all companies in your area. Now the function receives all the columns in the table I need, but my table has relations with other tables, and I want it to get the data of the other tables instead of only the ids.

This is the code to get all the companies in your area:

$companies = DB::table('companies')
    ->selectRaw(
        "id, owner, company_info, address, latitude, longitude,
        (6371 * acos( cos( radians(?))
        * cos( radians(latitude) )
        * cos( radians( longitude ) - radians(?))
        + sin( radians(?) )
        * sin( radians(latitude)))) AS distance",
        [$requestedCords['latitude'], $requestedCords['longitude'], $requestedCords['latitude']]
    )
    ->having("distance", "<=", $requestedCords['radius'])
    ->orderBy("distance",'asc')
    ->offset(0)
    ->limit(20)
    ->get();
```

The owner, company_info and the address columns are references to other tables.

Body:
So I have copied a function from the internet to get all companies in your area. Now the function receives all the columns in the table I need, but my table has relations with other tables, and I want it to get the data of the other tables instead of only the ids.

This is the code to get all the companies in your area:

$companies = DB::table('companies')
    ->selectRaw(
        "id, owner, company_info, address, latitude, longitude,
        (6371 * acos( cos( radians(?))
        * cos( radians(latitude) )
        * cos( radians( longitude ) - radians(?))
        + sin( radians(?) )
        * sin( radians(latitude)))) AS distance",
        [$requestedCords['latitude'], $requestedCords['longitude'], $requestedCords['latitude']]
    )
    ->having("distance", "<=", $requestedCords['radius'])
    ->orderBy("distance",'asc')
    ->offset(0)
    ->limit(20)
    ->get();

The owner, company_info and the address columns are references to other tables.


问:
how can you use two libraries on the same computer at the same time, which are imported under the same name?
I have two bots, one uses discord.py, the second one uses discord.py-self, both libraries are imported as "import discord", but if both libraries are on my computer, one of the scripts will not work. how can i import a specific library or how can i solve this problem?</p>


问:
How to use ngx-pagination to apply pagination on list of items using angular 13?
I work on a web application with ASP.NET Core 6 and Angular 13.

This application displays a list of items successfully without any issue.

My issue How to Apply pagination on Angular 13 using ngx-pagination ?

What I tried is:

(1) Create Web API action to display all items

```<code>public async Task<IActionResult> GetAll(int pageNumber)
{
    var allitems = _iitem.GetAllItems();

    var result = _pageHelper.GetPage(allitems.AsQueryable(), pageNumber);

    var itemsdata = new ItemsPageViewModel
            {
                items = result.Items,
                Pager = result.Pager
            };

    return Ok(itemsdata);
    }
</code>```

When I call this action method, it returns json data as shown here:

```<code>{
    "items": [
        {
            "id": 3,
            "itemNameEN": "pen"
        },
        {
            "id": 4,
            "itemNameEN": "pencil"
        },
        {
            "id": 5,
            "itemNameEN": "pen2"
        }
    ],
    "pager": {
        "numberOfPages": 1,
        "currentPage": 1,
        "totalRecords": 3
    }
}
</code>```

(2) I created a component items logic in component.ts:

```<code>ngOnInit(): void {
    this.retrieveAllItems();
  }

 retrieveAllItems(): void {
  this.erpservice.getAll()
    .subscribe(
      data => {

        this.items = data.items;
        console.log(data);
      },
      error => {
        console.log(error);
      });
}
</code>```

(3) I created a component view component.html:

```<code><table id="customers">
  <tr>
      <th>Id</th>
      <th>ItemNameEN</th>
  </tr>
  <tr *ngFor="let item of items">
      <td>{{item.id}}</td>
      <td>{{item.itemNameEN}}</td>
  </tr>
</table>
</code>```

How to apply pagination on angular 13 using ngxPagination ?

I install ngxPagination module

my issue how to apply pagination on angular 13 ?

Body:
I work on a web application with ASP.NET Core 6 and Angular 13.

This application displays a list of items successfully without any issue.

My issue How to Apply pagination on Angular 13 using ngx-pagination ?

What I tried is:

(1) Create Web API action to display all items

public async Task<IActionResult> GetAll(int pageNumber)
{
    var allitems = _iitem.GetAllItems();

    var result = _pageHelper.GetPage(allitems.AsQueryable(), pageNumber);

    var itemsdata = new ItemsPageViewModel
            {
                items = result.Items,
                Pager = result.Pager
            };

    return Ok(itemsdata);
    }

When I call this action method, it returns json data as shown here:

{
    "items": [
        {
            "id": 3,
            "itemNameEN": "pen"
        },
        {
            "id": 4,
            "itemNameEN": "pencil"
        },
        {
            "id": 5,
            "itemNameEN": "pen2"
        }
    ],
    "pager": {
        "numberOfPages": 1,
        "currentPage": 1,
        "totalRecords": 3
    }
}

(2) I created a component items logic in component.ts:

ngOnInit(): void {
    this.retrieveAllItems();
  }

 retrieveAllItems(): void {
  this.erpservice.getAll()
    .subscribe(
      data => {

        this.items = data.items;
        console.log(data);
      },
      error => {
        console.log(error);
      });
}

(3) I created a component view component.html:

      Id
      ItemNameEN

      {{item.id}}
      {{item.itemNameEN}}

How to apply pagination on angular 13 using ngxPagination ?

I install ngxPagination module

my issue how to apply pagination on angular 13 ?


问:
How to iterate a div searching for a child containing specific words?
Given a parent div:

parent = document.querySelector("...");
```
<p>How could I find a <code>child</code> of it, that contains 'notifications' and 'window' in her name?</p>
<p>As example:</p>
<pre class="lang-js prettyprint-override"><code>form class="notifications window-wj653j-Root-Root e1j27xnw0"
</code>```

The form name changes each time, only notifications window don't.

This works:

$x(".//*[contains(@class,'notifications')]//*[contains(@class,'field')][contains(@class,'window-')]")
```

But i don't know how to do the search only inside the parent div.

Body:
Given a parent div:

parent = document.querySelector("...");

How could I find a child of it, that contains 'notifications' and 'window' in her name?

As example:

form class="notifications window-wj653j-Root-Root e1j27xnw0"

The form name changes each time, only notifications window don't.

This works:

$x(".//*[contains(@class,'notifications')]//*[contains(@class,'field')][contains(@class,'window-')]")

But i don't know how to do the search only inside the parent div.


问:
Display one featured post(that is most recent), followed by Recent posts(Hubspot)
I'm currently working on a Blog Listings page. I'd like to display one Featured post at a time, and up top before other posts. And in order to test this out, I created a couple of Test blogs. One is with another Featured tag.

So my blog listings page is showing the most recent posts, which is nice...

But I'd like to show the most recent Featured post up top.
I also would like to add a Recent Posts heading on ONLY the first recent posts card but can't seem to figure out how, considering the cards are in a for-loop and it would show Recent Posts on every card if I do add the heading in the code.

Wondering if someone with another set of eyes can troubleshoot my code and see what's up!

Thank you :)

I got my source code from: https://www.stephanieogaygarcia.com/hubspot-website-development/set-featured-posts-on-the-hubspot-blog-listings-page

Here is how the page looks so far:

Blog Listing Page

And here is the code:

```<code>{% set featured_posts = blog_recent_topic_posts('default', 'featured', 1) %}
{% for post in featured_posts %}
  {% for topic in post.topic_list %}
    {% if topic.name == 'featured' %}
      <section class="blog-index-list">
        <article class="blog-index__post-wrapper-list-">
          <div class="blog-index__post-list">
            {% if post.featured_image and group.use_featured_image_in_summary %}
              <a class="blog-index__post-image-list"
                 style="background-image: url('{{ post.featured_image }}');"
                 href="{{ post.absolute_url }}">
              </a>
            {% endif %}
            <div class="blog-index__post-content-list">
              <div>
                {% set featured_tag = post.topic_list | first %}
                {% if featured_tag %}
                  <span class="blog-index__post-preheader-list">{{ featured_tag }}</span>
                {% endif %}
                                 <div class="blog-index__post-meta-list">
                  <span class="blog-index__post-author-list">
                    {{ post.blog_post_author }} |
                  </span>
                  <span class="blog-index__post-date-list">
                    {{ post.publish_date | datetimeformat('%b %e, %Y') }}
                  </span>

                </div>
                <h3><div class="blog-title"><a href="{{ post.absolute_url }}">{{ post.name }}</a></div></h3>
                {% if content_group.show_summary_in_listing %}
                  <div class="meta-description">{{ post.meta_description | default(post.post_summary, true) | truncatehtml(250, '...', false) }}</div>
                {% endif %}
              </div>
              <a href="{{ post.absolute_url }}"> <button class="blog-button-cta"> Read More </button> </a>
            </div>
          </div>
        </article>
      </section>
    {% endif %}
  {% endfor %}
{% endfor %}

{# Blog listing #}
{% set remaining_posts = contents | sort(attribute='publish_date', reverse=True) %}
{% for content in remaining_posts %}
  {# On the blog listing page, the first post will be featured above older posts #}
  <article class="blog-index__post-wrapper-list">
    <div class="blog-index__post-list">
      {% if content.featured_image and group.use_featured_image_in_summary %}
        <a class="blog-index__post-image-list"
               style="background-image: url('{{ content.featured_image }}');"
               href="{{ content.absolute_url }}">
            </a>
            {% endif %}
            <div class="blog-index__post-content-list">
              <div>
                {% set featured_tag = content.topic_list | first %}
                {% if featured_tag %}
                <span class="blog-index__post-preheader-list">{{ featured_tag }}</span>
                {% endif %}

                <h3><div class="blog-title"><a href="{{ content.absolute_url }}">{{ content.name }}</a></div></h3>
              <div class="blog-index__post-meta-list">
                <span class="blog-index__post-author-list">
                  {{ content.blog_post_author }} |
                </span>
                <span class="blog-index__post-date-list">
                  {{ content.publish_date | datetimeformat('%b %e, %Y') }}
                </span>

              </div>
                {% if content_group.show_summary_in_listing %}
                <div class="meta-description">{{ content.meta_description | default(content.post_summary, true) | truncatehtml(250, '...', false) }}</div>
                {% endif %}
              </div>

                {#<a href="{{ content.absolute_url }}"> <button class="blog-button-cta"> Read More </button> </a> #}

            </div>
            <a href="{{ content.absolute_url }}"> <button class="blog-button-cta"> Read More </button> </a>
          </div>
        </article>
        {% endfor %}
```
```

Body:
I'm currently working on a Blog Listings page. I'd like to display one Featured post at a time, and up top before other posts. And in order to test this out, I created a couple of Test blogs. One is with another Featured tag.

So my blog listings page is showing the most recent posts, which is nice...

But I'd like to show the most recent Featured post up top.
I also would like to add a Recent Posts heading on ONLY the first recent posts card but can't seem to figure out how, considering the cards are in a for-loop and it would show Recent Posts on every card if I do add the heading in the code.

Wondering if someone with another set of eyes can troubleshoot my code and see what's up!

Thank you :)

I got my source code from: https://www.stephanieogaygarcia.com/hubspot-website-development/set-featured-posts-on-the-hubspot-blog-listings-page

Here is how the page looks so far:

Blog Listing Page

And here is the code:

{% set featured_posts = blog_recent_topic_posts('default', 'featured', 1) %}
{% for post in featured_posts %}
  {% for topic in post.topic_list %}
    {% if topic.name == 'featured' %}

            {% if post.featured_image and group.use_featured_image_in_summary %}

            {% endif %}

                {% set featured_tag = post.topic_list | first %}
                {% if featured_tag %}
                  {{ featured_tag }}
                {% endif %}

                    {{ post.blog_post_author }} |

                    {{ post.publish_date | datetimeformat('%b %e, %Y') }}

{{ post.name }}

                {% if content_group.show_summary_in_listing %}

{{ post.meta_description | default(post.post_summary, true) | truncatehtml(250, '...', false) }}

                {% endif %}

               <button class="blog-button-cta"> Read More </button>

    {% endif %}
  {% endfor %}
{% endfor %}

{# Blog listing #}
{% set remaining_posts = contents | sort(attribute='publish_date', reverse=True) %}
{% for content in remaining_posts %}
  {# On the blog listing page, the first post will be featured above older posts #}

      {% if content.featured_image and group.use_featured_image_in_summary %}

            {% endif %}

                {% set featured_tag = content.topic_list | first %}
                {% if featured_tag %}
                {{ featured_tag }}
                {% endif %}

{{ content.name }}

                  {{ content.blog_post_author }} |

                  {{ content.publish_date | datetimeformat('%b %e, %Y') }}

                {% if content_group.show_summary_in_listing %}

{{ content.meta_description | default(content.post_summary, true) | truncatehtml(250, '...', false) }}

                {% endif %}

                {# <button class="blog-button-cta"> Read More </button>  #}

             <button class="blog-button-cta"> Read More </button>

        {% endfor %}
```


问:
Keras model.build with multiple inputs
```<code>class MyModel(tf.keras.Model):
   def __init__(self, ...):
       ...

   def call(self, input_1, input_2, input_3):
       ....
</code>```

I want to build above model, so I call build method as follows

```<code>model = MyModel(...)
model.build(input_shape = ( (None, 3), (None, 2), (None, 5) ))
</code>```

However, the following error came out

TypeError: Error converting shape to a TensorShape: Dimension value
must be integer or None or have an index method, got value '(None,
3)' with type '<class 'tuple'>'.

How can I build keras model with multiple inputs?

Title: Keras model.build with multiple inputs

Body:
class MyModel(tf.keras.Model):
   def __init__(self, ...):
       ...

   def call(self, input_1, input_2, input_3):
       ....

I want to build above model, so I call build method as follows

model = MyModel(...)
model.build(input_shape = ( (None, 3), (None, 2), (None, 5) ))

However, the following error came out

TypeError: Error converting shape to a TensorShape: Dimension value
must be integer or None or have an index method, got value '(None,
3)' with type '<class 'tuple'>'.

How can I build keras model with multiple inputs?


问:
How do I save color to las file using laspy
I have been trying to add color to my point cloud. I want to add red green and blue but for now, I am only adding red to simplify the problem. I want to be using chunks to read the file. Right now when I read the file back I get an array of zeros.</p>
```<code>import numpy as np
import laspy

def calculate_normals(file: str, chunk_size: int):
    # read file point cloud file
    header = laspy.LasHeader(point_format=2, version="1.2")
    with laspy.open(file, mode='r') as read_f:

        n_points = int(read_f.header.point_count)
        n_chunks = int(n_points / chunk_size) + 1
        chunk_size = n_points // n_chunks + 1

        # Write to new file
        header.scales = read_f.header.scales
        out_file = file[:-4] + '_normals' + file[-4:]
        print('Opening', out_file)
        with laspy.open(out_file, mode='w', header=header) as write_f:
            for count, chunk in enumerate(read_f.chunk_iterator(chunk_size)):
                rec_s = len(chunk)
                header = laspy.LasHeader(point_format=2, version="1.2")
                point_record = laspy.ScaleAwarePointRecord.zeros(rec_s, header=header)
                points = np.array((chunk.x, chunk.y, chunk.z)).T
                point_record.x, point_record.y, point_record.z = points.T
                point_record.red = np.full(len(chunk), 155)

def read_test(file):
    with laspy.open(file, mode='r') as read_f:
        points = read_f.read_points(500)
        print(points.red)
</code>```

Body:
I have been trying to add color to my point cloud. I want to add red green and blue but for now, I am only adding red to simplify the problem. I want to be using chunks to read the file. Right now when I read the file back I get an array of zeros.

import numpy as np
import laspy

def calculate_normals(file: str, chunk_size: int):
    # read file point cloud file
    header = laspy.LasHeader(point_format=2, version="1.2")
    with laspy.open(file, mode='r') as read_f:

        n_points = int(read_f.header.point_count)
        n_chunks = int(n_points / chunk_size) + 1
        chunk_size = n_points // n_chunks + 1

        # Write to new file
        header.scales = read_f.header.scales
        out_file = file[:-4] + '_normals' + file[-4:]
        print('Opening', out_file)
        with laspy.open(out_file, mode='w', header=header) as write_f:
            for count, chunk in enumerate(read_f.chunk_iterator(chunk_size)):
                rec_s = len(chunk)
                header = laspy.LasHeader(point_format=2, version="1.2")
                point_record = laspy.ScaleAwarePointRecord.zeros(rec_s, header=header)
                points = np.array((chunk.x, chunk.y, chunk.z)).T
                point_record.x, point_record.y, point_record.z = points.T
                point_record.red = np.full(len(chunk), 155)

def read_test(file):
    with laspy.open(file, mode='r') as read_f:
        points = read_f.read_points(500)
        print(points.red)


问:
Neural Network - ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list)
I am working on a tensorflow project, which includes a neural network that should be able to learn how to get inspirational quotes from input quotes. But when I go to run my code, I get this error:

```<code>ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list).
</code>```

I have tried many things but am just looking for the reason it is happening. I assume it is because I am using a nested-list in my array, as seen here:

```<code>[list([7, 8]) list([33, 34, 34]) list([24, 4, 0, 18, 18])]
</code>```

But I am not sure why that is causing an error as I use lists and lists of lists very frequently in my other neural networks.

Here is my full code:

```<code>alpha = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " ", ".", ",", "!"]
packing = []
listing = []
try:
  while True:
    temp = input(":")
    for elements in temp:
      count = 0
      for i in range(56):
        if elements == alpha[count]:
          listing.append(count)
          break
        count = count + 1

    packing.append(listing)
    listing = []

except KeyboardInterrupt:
  print("Dataset Created.")
  print("This is your Data: " + str(packing))

import tensorflow as tf
import numpy as np
from tensorflow import keras
from tensorflow.keras.activations import relu
from tensorflow.keras import regularizers

packing = np.array(packing)
shapepack = packing.shape[0]
inputs = np.zeros((shapepack,))
print(packing)
print("--------------")
print(inputs)

model = keras.Sequential([
    keras.layers.Dense(6, input_shape=(shapepack,), activation='relu',
                       kernel_regularizer=regularizers.l1(0.01)),
    #                                                     0.01 is the reg rate
    keras.layers.Dense(8, input_shape=(shapepack,), activation='relu',
                       kernel_regularizer=regularizers.l1(0.01)),
    #                                                     0.01 is the reg rate
    keras.layers.Dense(1, input_shape=(shapepack,), activation='relu',
                       kernel_regularizer=regularizers.l1(0.01))
    #                                                     0.01 is the reg rate
])

model.compile(optimizer='sgd', loss='mse')

network = model.fit(inputs, packing, epochs=35000)

predictions = model.predict(packing)

del tf
del np
del keras
del relu
del regularizers
</code>```

I tried to fix the error by converting the list to a float64 but I could not change the inner lists so they stayed as list type, I expected the code to work and start running the network but just ended with the same error.

```<code>ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list).
</code>```

All help is appreciated!

Body:
I am working on a tensorflow project, which includes a neural network that should be able to learn how to get inspirational quotes from input quotes. But when I go to run my code, I get this error:

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list).

I have tried many things but am just looking for the reason it is happening. I assume it is because I am using a nested-list in my array, as seen here:

[list([7, 8]) list([33, 34, 34]) list([24, 4, 0, 18, 18])]

But I am not sure why that is causing an error as I use lists and lists of lists very frequently in my other neural networks.

Here is my full code:

alpha = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " ", ".", ",", "!"]
packing = []
listing = []
try:
  while True:
    temp = input(":")
    for elements in temp:
      count = 0
      for i in range(56):
        if elements == alpha[count]:
          listing.append(count)
          break
        count = count + 1

    packing.append(listing)
    listing = []

except KeyboardInterrupt:
  print("Dataset Created.")
  print("This is your Data: " + str(packing))

import tensorflow as tf
import numpy as np
from tensorflow import keras
from tensorflow.keras.activations import relu
from tensorflow.keras import regularizers

packing = np.array(packing)
shapepack = packing.shape[0]
inputs = np.zeros((shapepack,))
print(packing)
print("--------------")
print(inputs)

model = keras.Sequential([
    keras.layers.Dense(6, input_shape=(shapepack,), activation='relu',
                       kernel_regularizer=regularizers.l1(0.01)),
    #                                                     0.01 is the reg rate
    keras.layers.Dense(8, input_shape=(shapepack,), activation='relu',
                       kernel_regularizer=regularizers.l1(0.01)),
    #                                                     0.01 is the reg rate
    keras.layers.Dense(1, input_shape=(shapepack,), activation='relu',
                       kernel_regularizer=regularizers.l1(0.01))
    #                                                     0.01 is the reg rate
])

model.compile(optimizer='sgd', loss='mse')

network = model.fit(inputs, packing, epochs=35000)

predictions = model.predict(packing)

del tf
del np
del keras
del relu
del regularizers

I tried to fix the error by converting the list to a float64 but I could not change the inner lists so they stayed as list type, I expected the code to work and start running the network but just ended with the same error.

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list).

All help is appreciated!


问:
java.security.cert.CertificateExpiredException:Certificate expired at Thu Oct 20 19:59:59EDT 2022 (compared to Wed Jan04 17:53:35EST 2023) for Android
So a bit of back story. This error code is only coming up on an app that was created around 2018 or so and was working all the way up until a couple months back. This error pops up when I am making a HTTPS POST call (So a login into the API). There is also an iOS version of the app and it is working normally. Both iOS and Android are pointing to the same endpoint too.

Back to Android. In the logs, it shows that the login was successful, but I won't get passed the login screen because of that said error. I was recreating the app and set up the login component of the app and it showed in the logs that I logged into the API successfully there as well. So the issue is only coming up from this particular version of the app.

Here's the error code:

```<code>W/System.err: javax.net.ssl.SSLHandshakeException: Chain validation failed
W/System.err:     at com.android.org.conscrypt.SSLUtils.toSSLHandshakeException(SSLUtils.java:362)
W/System.err:     at com.android.org.conscrypt.ConscryptEngine.convertException(ConscryptEngine.java:1134)
W/System.err:     at com.android.org.conscrypt.ConscryptEngine.readPlaintextData(ConscryptEngine.java:1089)
W/System.err:     at com.android.org.conscrypt.ConscryptEngine.unwrap(ConscryptEngine.java:876)
W/System.err:     at com.android.org.conscrypt.ConscryptEngine.unwrap(ConscryptEngine.java:747)
W/System.err:     at com.android.org.conscrypt.ConscryptEngine.unwrap(ConscryptEngine.java:712)
W/System.err:     at com.android.org.conscrypt.ConscryptEngineSocket$SSLInputStream.processDataFromSocket(ConscryptEngineSocket.java:849)
W/System.err:     at com.android.org.conscrypt.ConscryptEngineSocket$SSLInputStream.access$100(ConscryptEngineSocket.java:722)
W/System.err:     at com.android.org.conscrypt.ConscryptEngineSocket.doHandshake(ConscryptEngineSocket.java:238)
W/System.err:     at com.android.org.conscrypt.ConscryptEngineSocket.startHandshake(ConscryptEngineSocket.java:217)
W/System.err:     at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.kt:379)
W/System.err:     at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.kt:337)
W/System.err:     at okhttp3.internal.connection.RealConnection.connect(RealConnection.kt:209)
W/System.err:     at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.kt:226)
W/System.err:     at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.kt:106)
W/System.err:     at okhttp3.internal.connection.ExchangeFinder.find(ExchangeFinder.kt:74)
W/System.err:     at okhttp3.internal.connection.RealCall.initExchange$okhttp(RealCall.kt:255)
W/System.err:     at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:32)
W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
W/System.err:     at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:95)
W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
W/System.err:     at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:83)
W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
W/System.err:     at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:76)
W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
W/System.err:     at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:201)
W/System.err:     at okhttp3.internal.connection.RealCall.execute(RealCall.kt:154)
W/System.err:     at retrofit2.OkHttpCall.execute(OkHttpCall.java:188)
W/System.err:     at retrofit2.adapter.rxjava2.CallExecuteObservable.subscribeActual(CallExecuteObservable.java:45)
W/System.err:     at io.reactivex.Observable.subscribe(Observable.java:12267)
W/System.err:     at retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
W/System.err:     at io.reactivex.Observable.subscribe(Observable.java:12267)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableFromObservable.subscribeActual(FlowableFromObservable.java:29)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14918)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableOnBackpressureLatest.subscribeActual(FlowableOnBackpressureLatest.java:32)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14918)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableFlatMap.subscribeActual(FlowableFlatMap.java:53)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14918)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableMap.subscribeActual(FlowableMap.java:37)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14918)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14865)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableOnErrorNext$OnErrorNextSubscriber.onError(FlowableOnErrorNext.java:115)
W/System.err:     at io.reactivex.internal.operators.single.SingleToFlowable$SingleToFlowableObserver.onError(SingleToFlowable.java:67)
W/System.err:     at io.reactivex.internal.operators.single.SingleCreate$Emitter.tryOnError(SingleCreate.java:94)
W/System.err:     at io.reactivex.internal.operators.single.SingleCreate$Emitter.onError(SingleCreate.java:80)
W/System.err:     at com.parabit.parabeacon.app.demo.data_section.LocalStorage.lambda$getDeviceIdInfo$15(LocalStorage.java:236)
W/System.err:     at com.parabit.parabeacon.app.demo.data_section.LocalStorage$$ExternalSyntheticLambda9.subscribe(Unknown Source:2)
W/System.err:     at io.reactivex.internal.operators.single.SingleCreate.subscribeActual(SingleCreate.java:39)
W/System.err:     at io.reactivex.Single.subscribe(Single.java:3603)
W/System.err:     at io.reactivex.internal.operators.single.SingleToFlowable.subscribeActual(SingleToFlowable.java:37)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14918)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableOnErrorNext.subscribeActual(FlowableOnErrorNext.java:40)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14918)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableFlatMap.subscribeActual(FlowableFlatMap.java:53)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14918)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14865)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableFlatMap$MergeSubscriber.onNext(FlowableFlatMap.java:163)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableFromArray$ArraySubscription.slowPath(FlowableFromArray.java:162)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableFromArray$BaseArraySubscription.request(FlowableFromArray.java:90)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableFlatMap$MergeSubscriber.onSubscribe(FlowableFlatMap.java:117)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableFromArray.subscribeActual(FlowableFromArray.java:38)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14918)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableFlatMap.subscribeActual(FlowableFlatMap.java:53)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14918)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14865)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableSubscribeOn$SubscribeOnSubscriber.run(FlowableSubscribeOn.java:82)
W/System.err:     at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:66)
W/System.err:     at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:57)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/System.err:     at java.lang.Thread.run(Thread.java:923)
W/System.err: Caused by: java.security.cert.CertificateException: Chain validation failed
W/System.err:     at com.android.org.conscrypt.TrustManagerImpl.verifyChain(TrustManagerImpl.java:724)
W/System.err:     at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:554)
W/System.err:     at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:575)
W/System.err:     at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:620)
I/chatty: uid=10207(com.parabit.parabeacon.app.demo) identical 1 line
W/System.err:     at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:620)
W/System.err:     at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:510)
W/System.err:     at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:428)
W/System.err:     at com.android.org.conscrypt.TrustManagerImpl.getTrustedChainForServer(TrustManagerImpl.java:356)
W/System.err:     at android.security.net.config.NetworkSecurityTrustManager.checkServerTrusted(NetworkSecurityTrustManager.java:94)
W/System.err:     at android.security.net.config.RootTrustManager.checkServerTrusted(RootTrustManager.java:90)
W/System.err:     at com.android.org.conscrypt.ConscryptEngineSocket$2.checkServerTrusted(ConscryptEngineSocket.java:161)
W/System.err:     at com.android.org.conscrypt.Platform.checkServerTrusted(Platform.java:250)
W/System.err:     at com.android.org.conscrypt.ConscryptEngine.verifyCertificateChain(ConscryptEngine.java:1644)
W/System.err:     at com.android.org.conscrypt.NativeCrypto.ENGINE_SSL_read_direct(Native Method)
W/System.err:     at com.android.org.conscrypt.NativeSsl.readDirectByteBuffer(NativeSsl.java:568)
W/System.err:     at com.android.org.conscrypt.ConscryptEngine.readPlaintextDataDirect(ConscryptEngine.java:1095)
W/System.err:     at com.android.org.conscrypt.ConscryptEngine.readPlaintextData(ConscryptEngine.java:1079)
W/System.err:   ... 70 more
W/System.err: Caused by: java.security.cert.CertPathValidatorException: timestamp check failed
W/System.err:     at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:135)
W/System.err:     at sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:222)
W/System.err:     at sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:140)
W/System.err:     at sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:79)
W/System.err:     at java.security.cert.CertPathValidator.validate(CertPathValidator.java:301)
W/System.err:     at com.android.org.conscrypt.TrustManagerImpl.verifyChain(TrustManagerImpl.java:720)
W/System.err:   ... 87 more
W/System.err: Caused by: java.security.cert.CertificateExpiredException: Certificate expired at Thu Oct 20 19:59:59 EDT 2022 (compared to Wed Jan 04 17:53:35 EST 2023) //<- Here's the real issue
W/System.err:     at com.android.org.conscrypt.OpenSSLX509Certificate.checkValidity(OpenSSLX509Certificate.java:269)
W/System.err:     at sun.security.provider.certpath.BasicChecker.verifyTimestamp(BasicChecker.java:194)
W/System.err:     at sun.security.provider.certpath.BasicChecker.check(BasicChecker.java:144)
W/System.err:     at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:125)
W/System.err:   ... 92 more
</code>```

I've been searching all day for a solution but couldn't find anything on this error that was tangible. Any ideas or solutions is appreciated. Thank you. If you need anymore info, please let me know.

P.S. The Android apps were built on Android Studio.

Body:
So a bit of back story. This error code is only coming up on an app that was created around 2018 or so and was working all the way up until a couple months back. This error pops up when I am making a HTTPS POST call (So a login into the API). There is also an iOS version of the app and it is working normally. Both iOS and Android are pointing to the same endpoint too.

Back to Android. In the logs, it shows that the login was successful, but I won't get passed the login screen because of that said error. I was recreating the app and set up the login component of the app and it showed in the logs that I logged into the API successfully there as well. So the issue is only coming up from this particular version of the app.

Here's the error code:

W/System.err: javax.net.ssl.SSLHandshakeException: Chain validation failed
W/System.err:     at com.android.org.conscrypt.SSLUtils.toSSLHandshakeException(SSLUtils.java:362)
W/System.err:     at com.android.org.conscrypt.ConscryptEngine.convertException(ConscryptEngine.java:1134)
W/System.err:     at com.android.org.conscrypt.ConscryptEngine.readPlaintextData(ConscryptEngine.java:1089)
W/System.err:     at com.android.org.conscrypt.ConscryptEngine.unwrap(ConscryptEngine.java:876)
W/System.err:     at com.android.org.conscrypt.ConscryptEngine.unwrap(ConscryptEngine.java:747)
W/System.err:     at com.android.org.conscrypt.ConscryptEngine.unwrap(ConscryptEngine.java:712)
W/System.err:     at com.android.org.conscrypt.ConscryptEngineSocket$SSLInputStream.processDataFromSocket(ConscryptEngineSocket.java:849)
W/System.err:     at com.android.org.conscrypt.ConscryptEngineSocket$SSLInputStream.access$100(ConscryptEngineSocket.java:722)
W/System.err:     at com.android.org.conscrypt.ConscryptEngineSocket.doHandshake(ConscryptEngineSocket.java:238)
W/System.err:     at com.android.org.conscrypt.ConscryptEngineSocket.startHandshake(ConscryptEngineSocket.java:217)
W/System.err:     at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.kt:379)
W/System.err:     at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.kt:337)
W/System.err:     at okhttp3.internal.connection.RealConnection.connect(RealConnection.kt:209)
W/System.err:     at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.kt:226)
W/System.err:     at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.kt:106)
W/System.err:     at okhttp3.internal.connection.ExchangeFinder.find(ExchangeFinder.kt:74)
W/System.err:     at okhttp3.internal.connection.RealCall.initExchange$okhttp(RealCall.kt:255)
W/System.err:     at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:32)
W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
W/System.err:     at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:95)
W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
W/System.err:     at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:83)
W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
W/System.err:     at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:76)
W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
W/System.err:     at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:201)
W/System.err:     at okhttp3.internal.connection.RealCall.execute(RealCall.kt:154)
W/System.err:     at retrofit2.OkHttpCall.execute(OkHttpCall.java:188)
W/System.err:     at retrofit2.adapter.rxjava2.CallExecuteObservable.subscribeActual(CallExecuteObservable.java:45)
W/System.err:     at io.reactivex.Observable.subscribe(Observable.java:12267)
W/System.err:     at retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
W/System.err:     at io.reactivex.Observable.subscribe(Observable.java:12267)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableFromObservable.subscribeActual(FlowableFromObservable.java:29)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14918)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableOnBackpressureLatest.subscribeActual(FlowableOnBackpressureLatest.java:32)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14918)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableFlatMap.subscribeActual(FlowableFlatMap.java:53)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14918)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableMap.subscribeActual(FlowableMap.java:37)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14918)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14865)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableOnErrorNext$OnErrorNextSubscriber.onError(FlowableOnErrorNext.java:115)
W/System.err:     at io.reactivex.internal.operators.single.SingleToFlowable$SingleToFlowableObserver.onError(SingleToFlowable.java:67)
W/System.err:     at io.reactivex.internal.operators.single.SingleCreate$Emitter.tryOnError(SingleCreate.java:94)
W/System.err:     at io.reactivex.internal.operators.single.SingleCreate$Emitter.onError(SingleCreate.java:80)
W/System.err:     at com.parabit.parabeacon.app.demo.data_section.LocalStorage.lambda$getDeviceIdInfo$15(LocalStorage.java:236)
W/System.err:     at com.parabit.parabeacon.app.demo.data_section.LocalStorage$$ExternalSyntheticLambda9.subscribe(Unknown Source:2)
W/System.err:     at io.reactivex.internal.operators.single.SingleCreate.subscribeActual(SingleCreate.java:39)
W/System.err:     at io.reactivex.Single.subscribe(Single.java:3603)
W/System.err:     at io.reactivex.internal.operators.single.SingleToFlowable.subscribeActual(SingleToFlowable.java:37)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14918)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableOnErrorNext.subscribeActual(FlowableOnErrorNext.java:40)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14918)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableFlatMap.subscribeActual(FlowableFlatMap.java:53)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14918)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14865)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableFlatMap$MergeSubscriber.onNext(FlowableFlatMap.java:163)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableFromArray$ArraySubscription.slowPath(FlowableFromArray.java:162)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableFromArray$BaseArraySubscription.request(FlowableFromArray.java:90)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableFlatMap$MergeSubscriber.onSubscribe(FlowableFlatMap.java:117)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableFromArray.subscribeActual(FlowableFromArray.java:38)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14918)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableFlatMap.subscribeActual(FlowableFlatMap.java:53)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14918)
W/System.err:     at io.reactivex.Flowable.subscribe(Flowable.java:14865)
W/System.err:     at io.reactivex.internal.operators.flowable.FlowableSubscribeOn$SubscribeOnSubscriber.run(FlowableSubscribeOn.java:82)
W/System.err:     at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:66)
W/System.err:     at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:57)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/System.err:     at java.lang.Thread.run(Thread.java:923)
W/System.err: Caused by: java.security.cert.CertificateException: Chain validation failed
W/System.err:     at com.android.org.conscrypt.TrustManagerImpl.verifyChain(TrustManagerImpl.java:724)
W/System.err:     at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:554)
W/System.err:     at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:575)
W/System.err:     at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:620)
I/chatty: uid=10207(com.parabit.parabeacon.app.demo) identical 1 line
W/System.err:     at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:620)
W/System.err:     at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:510)
W/System.err:     at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:428)
W/System.err:     at com.android.org.conscrypt.TrustManagerImpl.getTrustedChainForServer(TrustManagerImpl.java:356)
W/System.err:     at android.security.net.config.NetworkSecurityTrustManager.checkServerTrusted(NetworkSecurityTrustManager.java:94)
W/System.err:     at android.security.net.config.RootTrustManager.checkServerTrusted(RootTrustManager.java:90)
W/System.err:     at com.android.org.conscrypt.ConscryptEngineSocket$2.checkServerTrusted(ConscryptEngineSocket.java:161)
W/System.err:     at com.android.org.conscrypt.Platform.checkServerTrusted(Platform.java:250)
W/System.err:     at com.android.org.conscrypt.ConscryptEngine.verifyCertificateChain(ConscryptEngine.java:1644)
W/System.err:     at com.android.org.conscrypt.NativeCrypto.ENGINE_SSL_read_direct(Native Method)
W/System.err:     at com.android.org.conscrypt.NativeSsl.readDirectByteBuffer(NativeSsl.java:568)
W/System.err:     at com.android.org.conscrypt.ConscryptEngine.readPlaintextDataDirect(ConscryptEngine.java:1095)
W/System.err:     at com.android.org.conscrypt.ConscryptEngine.readPlaintextData(ConscryptEngine.java:1079)
W/System.err:   ... 70 more
W/System.err: Caused by: java.security.cert.CertPathValidatorException: timestamp check failed
W/System.err:     at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:135)
W/System.err:     at sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:222)
W/System.err:     at sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:140)
W/System.err:     at sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:79)
W/System.err:     at java.security.cert.CertPathValidator.validate(CertPathValidator.java:301)
W/System.err:     at com.android.org.conscrypt.TrustManagerImpl.verifyChain(TrustManagerImpl.java:720)
W/System.err:   ... 87 more
W/System.err: Caused by: java.security.cert.CertificateExpiredException: Certificate expired at Thu Oct 20 19:59:59 EDT 2022 (compared to Wed Jan 04 17:53:35 EST 2023) //<- Here's the real issue
W/System.err:     at com.android.org.conscrypt.OpenSSLX509Certificate.checkValidity(OpenSSLX509Certificate.java:269)
W/System.err:     at sun.security.provider.certpath.BasicChecker.verifyTimestamp(BasicChecker.java:194)
W/System.err:     at sun.security.provider.certpath.BasicChecker.check(BasicChecker.java:144)
W/System.err:     at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:125)
W/System.err:   ... 92 more

I've been searching all day for a solution but couldn't find anything on this error that was tangible. Any ideas or solutions is appreciated. Thank you. If you need anymore info, please let me know.

P.S. The Android apps were built on Android Studio.


问:
How can I change the location where the custom field is displayed in the Quick Edit tab in WordPress
That's my situation right now:

I want to display my "Artist" custom field under the "Slug" field, with the same HTML structure. How can I do this?

The following code may help:

```<code>// Display the custom field
function my_custom_field_add_quick_edit($column_name, $post_type)
{
    if ($column_name != 'Artista')
        return;
    global $post;
    $custom_field_value = get_post_meta($post->ID, 'Artista', true);
    ?>
    <fieldset class="inline-edit-col-right">
        <div class="inline-edit-group">
            <label>
                <span class="title">Artista</span>
                <input type="text" name="Artista" value="<?php echo esc_attr($custom_field_value); ?>" />
            </label>
        </div>
    </fieldset>
<?php
}
add_action('quick_edit_custom_box', 'my_custom_field_add_quick_edit', 10, 2);
</code>```
```<code>// Display the original fields
<fieldset class="inline-edit-col-left">
                <legend class="inline-edit-legend" id="<?php echo $bulk ? 'bulk' : 'quick'; ?>-edit-legend"><?php echo $bulk ? __( 'Bulk Edit' ) : __( 'Quick Edit' ); ?></legend>
                <div class="inline-edit-col">

                <?php if ( post_type_supports( $screen->post_type, 'title' ) ) : ?>

                    <?php if ( $bulk ) : ?>

                        <div id="bulk-title-div">
                            <div id="bulk-titles"></div>
                        </div>

                    <?php else : // $bulk ?>

                        <label>
                            <span class="title"><?php _e( 'Title' ); ?></span>
                            <span class="input-text-wrap"><input type="text" name="post_title" class="ptitle" value="" /></span>
                        </label>

                        <?php if ( is_post_type_viewable( $screen->post_type ) ) : ?>

                            <label>
                                <span class="title"><?php _e( 'Slug' ); ?></span>
                                <span class="input-text-wrap"><input type="text" name="post_name" value="" autocomplete="off" spellcheck="false" /></span>
                            </label>

                        <?php endif; // is_post_type_viewable() ?>

                    <?php endif; // $bulk ?>

                <?php endif; // post_type_supports( ... 'title' ) ?>

                </div>
            </fieldset>
</code>```

Thanks in advance. And don't be rude. I'm new to PHP.

Body:
That's my situation right now:

I want to display my "Artist" custom field under the "Slug" field, with the same HTML structure. How can I do this?

The following code may help:

// Display the custom field
function my_custom_field_add_quick_edit($column_name, $post_type)
{
    if ($column_name != 'Artista')
        return;
    global $post;
    $custom_field_value = get_post_meta($post->ID, 'Artista', true);
    ?>
    <fieldset class="inline-edit-col-right">

                Artista
                <input type="text" name="Artista" value="<?php echo esc_attr($custom_field_value); ?>" />

    </fieldset>
<?php
}
add_action('quick_edit_custom_box', 'my_custom_field_add_quick_edit', 10, 2);

// Display the original fields
<fieldset class="inline-edit-col-left">
                <legend class="inline-edit-legend" id="<?php echo $bulk ? 'bulk' : 'quick'; ?>-edit-legend"><?php echo $bulk ? __( 'Bulk Edit' ) : __( 'Quick Edit' ); ?></legend>

                <?php if ( post_type_supports( $screen->post_type, 'title' ) ) : ?>

                    <?php if ( $bulk ) : ?>

                    <?php else : // $bulk ?>

                            <?php _e( 'Title' ); ?>
                            <input type="text" name="post_title" class="ptitle" value="" />

                        <?php if ( is_post_type_viewable( $screen->post_type ) ) : ?>

                                <?php _e( 'Slug' ); ?>
                                <input type="text" name="post_name" value="" autocomplete="off" spellcheck="false" />

                        <?php endif; // is_post_type_viewable() ?>

                    <?php endif; // $bulk ?>

                <?php endif; // post_type_supports( ... 'title' ) ?>

            </fieldset>

Thanks in advance. And don't be rude. I'm new to PHP.


问:
How to make live updated plotly graph in python from SQL database?
I am trying to make live update graph with plotly by using python. My code is connected to MySQL server database that gets updated for every 30 seconds. What am I supposed to add in this code? Thank you.

```<code>import pymysql
import pandas as pd
import matplotlib.pyplot as plt
from IPython import display
import plotly.express as px
import plotly.graph_objects as go

myMyConn = pymysql.connect(user='ID', password='PW', host='IP', port=#####,charset='utf8', database='###')
myMyCursor = myMyConn.cursor()

sql = """
        SELECT X_Axis_CrestFactor, Y_Axis_CrestFactor, Z_Axis_CrestFactor, created_at
        FROM sensor_data
        WHERE info_devaddr = 'FF6CC451';
        """

df = pd.read_sql(sql, myMyConn)

x_CrestFactor = df['X_Axis_CrestFactor']
y_CrestFactor = df['Y_Axis_CrestFactor']
z_CrestFactor = df['Z_Axis_CrestFactor']
created_time = df['created_at']

fig = go.Figure()
fig.add_trace(go.Scatter(x=created_time, y=x_CrestFactor, mode='lines'))
fig.add_trace(go.Scatter(x=created_time, y=y_CrestFactor, mode='lines'))
fig.add_trace(go.Scatter(x=created_time, y=z_CrestFactor, mode='lines'))

fig.show()
</code>```

From my original code, all I get is a graph that does not automatically update. How can I update my graph automatically?

Body:
I am trying to make live update graph with plotly by using python. My code is connected to MySQL server database that gets updated for every 30 seconds. What am I supposed to add in this code? Thank you.

import pymysql
import pandas as pd
import matplotlib.pyplot as plt
from IPython import display
import plotly.express as px
import plotly.graph_objects as go

myMyConn = pymysql.connect(user='ID', password='PW', host='IP', port=#####,charset='utf8', database='###')
myMyCursor = myMyConn.cursor()

sql = """
        SELECT X_Axis_CrestFactor, Y_Axis_CrestFactor, Z_Axis_CrestFactor, created_at
        FROM sensor_data
        WHERE info_devaddr = 'FF6CC451';
        """

df = pd.read_sql(sql, myMyConn)

x_CrestFactor = df['X_Axis_CrestFactor']
y_CrestFactor = df['Y_Axis_CrestFactor']
z_CrestFactor = df['Z_Axis_CrestFactor']
created_time = df['created_at']

fig = go.Figure()
fig.add_trace(go.Scatter(x=created_time, y=x_CrestFactor, mode='lines'))
fig.add_trace(go.Scatter(x=created_time, y=y_CrestFactor, mode='lines'))
fig.add_trace(go.Scatter(x=created_time, y=z_CrestFactor, mode='lines'))

fig.show()

From my original code, all I get is a graph that does not automatically update. How can I update my graph automatically?


问:
Python logger is not creating log file despite a FileHandler being specified
I've been using a logger to log messages to a file and also output them to the console. I don't believe I did anything wrong, but the log file hasn't been being created for a few of the runs that I did.

The code I have is:

```<code>log_msg_format = '[%(asctime)s - %(levelname)s - %(filename)s: %(lineno)d] %(message)s'
handlers = [logging.FileHandler(filename=args.log_filename), logging.StreamHandler()]
logging.basicConfig(format=log_msg_format,
                    level=logging.INFO,
                    handlers=handlers)
</code>```

When I check the logging level for each of the handlers, they are both NOTSET. I thought that this might be the problem, but the script is still outputting log messages to the console which means that this shouldn't be a problem.

What might be going wrong?

Body:
I've been using a logger to log messages to a file and also output them to the console. I don't believe I did anything wrong, but the log file hasn't been being created for a few of the runs that I did.

The code I have is:

log_msg_format = '[%(asctime)s - %(levelname)s - %(filename)s: %(lineno)d] %(message)s'
handlers = [logging.FileHandler(filename=args.log_filename), logging.StreamHandler()]
logging.basicConfig(format=log_msg_format,
                    level=logging.INFO,
                    handlers=handlers)

When I check the logging level for each of the handlers, they are both NOTSET. I thought that this might be the problem, but the script is still outputting log messages to the console which means that this shouldn't be a problem.

What might be going wrong?


问:
Should tagged types work for value classes?
I am trying to create a tagged type (in Scala 2.x) in the same way that Shapeless (2.x) does but it fails with a ClassCastException:

object Main {

  sealed trait TaggedProps[Props] extends Any

  final class KeyAddingStage(private val args: Array[Any]) extends AnyVal

  type RenderedProps[Props] = KeyAddingStage with TaggedProps[Props]

  object Name {
    case class Props(name: String)

    def component(props: Props): KeyAddingStage = new KeyAddingStage(
      Array(
        props
      )
    )

    def apply(name: String): RenderedProps[Props] = component(Props(name)).asInstanceOf[RenderedProps[Props]]
  }

  def main(args: Array[String]): Unit = {
    val first: RenderedProps[Name.Props] = Name("Jason")
    val firstStage: KeyAddingStage = first
    println(first == firstStage)
    val props: Seq[RenderedProps[Name.Props]] = Seq(first)
    val propsHead: RenderedProps[Name.Props] = props.head
    println(firstStage == propsHead)
  }
}
```
<p>Fails with:</p>
```[error] java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to Main$KeyAddingStage
[error]     at Main$.main(test.scala:26)
[error]     at Main.main(test.scala)
[error]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[error]     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[error]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[error]     at java.lang.reflect.Method.invoke(Method.java:498)
```
<p>I initially found this in a Scala.js project and I thought that it was a Scala.js bug but it does in fact fail on the JVM too.</p>
<p>I found a workaround which is to do it in a similar way to scala-newtype:</p>
<pre class="lang-scala prettyprint-override"><code>import scala.language.implicitConversions

object Main {

  final class KeyAddingStage(private val args: Array[Any]) extends AnyVal

  object KeyAddingStage {
    implicit def build(stage: KeyAddingStage): String = stage.toString
  }

  type RenderedProps[Props] = RenderedProps.Type[Props]

  object RenderedProps {
    // This must be a structural type like it is in @newtype
    type Base = {
      type __RenderedProps__newtype
    }

    trait Tag[Props] extends Any

    // But we can put the type we are extending here after Base so that it works in the same way as @newsubtype
    type Type[Props] <: Base with KeyAddingStage with Tag[Props]

    def apply[Props](stage: KeyAddingStage): RenderedProps[Props] = stage.asInstanceOf[RenderedProps[Props]]
  }

  object Name {
    case class Props(name: String)

    def component(props: Props): KeyAddingStage = new KeyAddingStage(
      Array(
        props.asInstanceOf[Any]
      )
    )

    def apply(name: String): RenderedProps[Props] = RenderedProps(component(Props(name)))
  }

  def main(args: Array[String]): Unit = {
    val first: RenderedProps[Name.Props] = Name("Jason")
    val firstStage: KeyAddingStage = first
    val str: String = first
    println(first == firstStage)
    val props: Seq[RenderedProps[Name.Props]] = Seq(first)
    val propsHead: RenderedProps[Name.Props] = props.head
    println(firstStage == propsHead)
  }
}
</code>```

My question is whether this should be considered a Scala compiler bug/improvement or not?

I haven't looked at the Java bytecode but from the JS side it seems relatively easy to solve.

Body:
I am trying to create a tagged type (in Scala 2.x) in the same way that Shapeless (2.x) does but it fails with a ClassCastException:

object Main {

  sealed trait TaggedProps[Props] extends Any

  final class KeyAddingStage(private val args: Array[Any]) extends AnyVal

  type RenderedProps[Props] = KeyAddingStage with TaggedProps[Props]

  object Name {
    case class Props(name: String)

    def component(props: Props): KeyAddingStage = new KeyAddingStage(
      Array(
        props
      )
    )

    def apply(name: String): RenderedProps[Props] = component(Props(name)).asInstanceOf[RenderedProps[Props]]
  }

  def main(args: Array[String]): Unit = {
    val first: RenderedProps[Name.Props] = Name("Jason")
    val firstStage: KeyAddingStage = first
    println(first == firstStage)
    val props: Seq[RenderedProps[Name.Props]] = Seq(first)
    val propsHead: RenderedProps[Name.Props] = props.head
    println(firstStage == propsHead)
  }
}

Fails with:

[error] java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to Main$KeyAddingStage
[error]     at Main$.main(test.scala:26)
[error]     at Main.main(test.scala)
[error]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[error]     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[error]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[error]     at java.lang.reflect.Method.invoke(Method.java:498)

I initially found this in a Scala.js project and I thought that it was a Scala.js bug but it does in fact fail on the JVM too.

I found a workaround which is to do it in a similar way to scala-newtype:

import scala.language.implicitConversions

object Main {

  final class KeyAddingStage(private val args: Array[Any]) extends AnyVal

  object KeyAddingStage {
    implicit def build(stage: KeyAddingStage): String = stage.toString
  }

  type RenderedProps[Props] = RenderedProps.Type[Props]

  object RenderedProps {
    // This must be a structural type like it is in @newtype
    type Base = {
      type __RenderedProps__newtype
    }

    trait Tag[Props] extends Any

    // But we can put the type we are extending here after Base so that it works in the same way as @newsubtype
    type Type[Props] <: Base with KeyAddingStage with Tag[Props]

    def apply[Props](stage: KeyAddingStage): RenderedProps[Props] = stage.asInstanceOf[RenderedProps[Props]]
  }

  object Name {
    case class Props(name: String)

    def component(props: Props): KeyAddingStage = new KeyAddingStage(
      Array(
        props.asInstanceOf[Any]
      )
    )

    def apply(name: String): RenderedProps[Props] = RenderedProps(component(Props(name)))
  }

  def main(args: Array[String]): Unit = {
    val first: RenderedProps[Name.Props] = Name("Jason")
    val firstStage: KeyAddingStage = first
    val str: String = first
    println(first == firstStage)
    val props: Seq[RenderedProps[Name.Props]] = Seq(first)
    val propsHead: RenderedProps[Name.Props] = props.head
    println(firstStage == propsHead)
  }
}

My question is whether this should be considered a Scala compiler bug/improvement or not?

I haven't looked at the Java bytecode but from the JS side it seems relatively easy to solve.