问:
Restrict to move/drag the pdf annotation within PDF Page boundary
I am loading one PDF on PDF view using the PDF kit library. I added one custome view (same like PDF Annotation) on pdf view, and I am allowing users to move/drag that custom view on pdf view(within pdf view/container view) using UIPanGestureRecognizer.
Here is a gif,

If you see this gif, there is one problem. That custom view is going outside of the pdf page. I want to restrict it. The custom view should move/drag within the pdf page only.
How I can fix this? Is there a solution for it?

Here is the link  sample project and all code -  https://drive.google.com/file/d/1Ilhd8gp4AAxB_Q9G9swFbe4KQUHbpyGs/view?usp=sharing

Here is some code sample from project,

```<code>override func didMoveToSuperview() {
        addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(pan)))
    }

@objc func pan(_ gesture: UIPanGestureRecognizer) {
    translate(gesture.translation(in: self))
    gesture.setTranslation(.zero, in: self)
    setNeedsDisplay()
    print("Frames after moving : \(frame)")
}
</code>```

and code used as an extension

```<code>extension  CGPoint {
    static func +(lhs: CGPoint, rhs: CGPoint) -> CGPoint {
        .init(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
    }
    static func +=(lhs: inout CGPoint, rhs: CGPoint) {
        lhs.x += rhs.x
        lhs.y += rhs.y
    }
}
extension UIView {
    func translate(_ translation: CGPoint) {
        let destination = center + translation
        let minX = frame.width/2
        let minY = frame.height/2
        let maxX = superview!.frame.width-minX
        let maxY = superview!.frame.height-minY
        center = CGPoint(
            x: min(maxX, max(minX, destination.x)),
            y: min(maxY ,max(minY, destination.y)))
    }
}
</code>```

Code - Get PDF Page Height and Width

```<code> let page = pdfDocument.page(at: 0)
 let pageRect = page?.bounds(for: .mediaBox)

 print("pdf page width =", (pageRect?.size.width)!, "pdf page height =", (pageRect?.size.height)!)
</code>```

答:
I would recommend PDFAnnotation rather that UIView for adding content onto the PDFView.

It is not so easy to compare a UIView's frame within a PDFView due to their coordinate systems being different.

Adding a PDFAnnotation to the PDFView works in sync with the PDF coordinate system whereas working with UIView, you will need to do some conversions between coordinate spaces and this can be tricky and not so accurate.

Here are some small changes I made to kind of get this to work with a view.

First in your SignatoryXibView I added this function to show a red border when we are close to the edge

```<code>func showWarning(_ show: Bool)
{
    if show
    {
        contentView1.layer.borderColor = UIColor.red.cgColor
        return
    }

    contentView1.layer.borderColor = UIColor.green.cgColor
}
</code>```

I believe the SignatoryXibView should not be responsible for detecting and preventing going out of its superviews bounds so I created a protocol which the ViewController needs to conform to so that it can prevent the SignatoryXibView going out of the PDFView bounds.

```<code>protocol SignatoryViewDelegate: class
{
    func signatoryView(_ signatoryView: SignatoryXibView,
                       didReceivePanGesture gesture: UIPanGestureRecognizer)
}

class SignatoryXibView: UIView {

    // Add this
    weak var delegate: SignatoryViewDelegate?

    // .. rest of your code

    @objc
    func pan(_ gesture: UIPanGestureRecognizer)
    {
        // Hand off view translation handling to the delegate
        self.delegate?.signatoryView(self,
                                     didReceivePanGesture: gesture)
    }
}
</code>```

Now in your UIView extension, you created a translate method which works well however, you do not want to translate the view's location. You want to first check if the translation will go out of the desired boundary and prevent the translation from happening.

```<code>extension UIView {

    // Your original code
    func translate(_ translation: CGPoint) {
        let destination = center + translation
        let minX = frame.width/2
        let minY = frame.height/2
        let maxX = superview!.frame.width-minX
        let maxY = superview!.frame.height-minY
        center = CGPoint(
            x: min(maxX, max(minX, destination.x)),
            y: min(maxY ,max(minY, destination.y)))
    }

    // I have added this function to return the new rect
    // that would happen if this view translated
    func translatedRect(_ translation: CGPoint) -> CGRect
    {
        // All of this is your calculation
        let destination = center + translation

        let minX = frame.width/2
        let minY = frame.height/2
        let maxX = superview!.frame.width-minX
        let maxY = superview!.frame.height-minY

        var rect = CGRect(origin: .zero,
                          size: CGSize(width: bounds.width,
                                       height: bounds.height))

        let midX = min(maxX, max(minX, destination.x))
        let midY = min(maxY ,max(minY, destination.y))

        // I am not translating here, just creating a new rect
        // of the view if it would be translated
        rect.origin = CGPoint(x: midX - frame.width/2,
                              y: midY - frame.height/2)

        return rect
    }
}
</code>```

In your ViewController's loadPDF() function, make your view controller the delegate of the SignatoryXibView

```<code>// Add Sign on PdfView
// Your code unchanged
let customView = SignatoryXibView(frame: CGRect(x: 150,
                                                y: 140,
                                                width: 112,
                                                height: 58))
customView.signatoryLabel.text = "John Doe"
self.pdfView.addSubview(customView)

//Add this
customView.delegate = self
</code>```

Then finally you implement the delegate function we added earlier in the protocol to prevent the SignatoryXibView from going out the page's bounds.

```<code>extension ViewController: SignatoryViewDelegate
{
    func signatoryView(_ signatoryView: SignatoryXibView,
                       didReceivePanGesture gesture: UIPanGestureRecognizer)
    {
        // Get the location where the user has tapped
        let gestureTouchLocation = gesture.translation(in: signatoryView)

        // Get the new frame if the signature view would
        // be translated
        let updatedFrame
            = signatoryView.translatedRect(gestureTouchLocation)

        // Convert this rect from the Signature View's coordinate space
        // To the PDFView's coordinate space
        let updatedFrameConverted
        = pdfView.convert(updatedFrame,
                          to: pdfView.currentPage!)

        print("Updated frame: \(updatedFrame)")
        print("Updated frame converted: \(updatedFrameConverted)")
        print("Signature frame: \(signatoryView.frame)")
        print()

        // Retrieve the bounds of the current page
        // Handle the optional properly in your production app
        let pageRect = pdfView.currentPage!.bounds(for: .mediaBox)

        // Check if the new frame of SignatoryXibView is within the bounds of the pdf page
        if updatedFrameConverted.origin.x > CGFloat.zero &&
            updatedFrameConverted.origin.y + updatedFrameConverted.height < pageRect.height &&
            updatedFrameConverted.origin.x + updatedFrameConverted.width < pageRect.width &&
            updatedFrameConverted.origin.y > CGFloat.zero

        {
            // Since the view is within the bounds, you can update the views frame

            signatoryView.translate(gesture.translation(in: signatoryView))

            gesture.setTranslation(.zero, in: signatoryView)
            signatoryView.setNeedsDisplay()

            // Do not show any warning
            signatoryView.showWarning(false)

            return
        }

        // The view has reached the edge of the page so do not perform any view
        // translation and show the warning
        signatoryView.showWarning(true)
    }
}
</code>```

The end result should give you the below result which prevents the view from going outside the page bounds and makes the view red to show it cannot go further:

Final thoughts

I recommend using PDFAnnotation when adding things to the PDF

This will scale and scroll with the pages properly especially in scenarios like zooming a PDF where you might need to update your view again for it to be in the right location

Update

I updated some math in the func signatoryView function in the extension ViewController: SignatoryViewDelegate

This should give you better results in terms of figuring out the right boundary and also it will work when you zoom:

However, since it is not added as an annotation, it will not scroll with the page but the same boundary will be observed on the next page.

Body:
I am loading one PDF on PDF view using the PDF kit library. I added one custome view (same like PDF Annotation) on pdf view, and I am allowing users to move/drag that custom view on pdf view(within pdf view/container view) using UIPanGestureRecognizer.
Here is a gif,

If you see this gif, there is one problem. That custom view is going outside of the pdf page. I want to restrict it. The custom view should move/drag within the pdf page only.
How I can fix this? Is there a solution for it?

Here is the link  sample project and all code -  https://drive.google.com/file/d/1Ilhd8gp4AAxB_Q9G9swFbe4KQUHbpyGs/view?usp=sharing

Here is some code sample from project,

override func didMoveToSuperview() {
        addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(pan)))
    }

@objc func pan(_ gesture: UIPanGestureRecognizer) {
    translate(gesture.translation(in: self))
    gesture.setTranslation(.zero, in: self)
    setNeedsDisplay()
    print("Frames after moving : \(frame)")
}

and code used as an extension

extension  CGPoint {
    static func +(lhs: CGPoint, rhs: CGPoint) -> CGPoint {
        .init(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
    }
    static func +=(lhs: inout CGPoint, rhs: CGPoint) {
        lhs.x += rhs.x
        lhs.y += rhs.y
    }
}
extension UIView {
    func translate(_ translation: CGPoint) {
        let destination = center + translation
        let minX = frame.width/2
        let minY = frame.height/2
        let maxX = superview!.frame.width-minX
        let maxY = superview!.frame.height-minY
        center = CGPoint(
            x: min(maxX, max(minX, destination.x)),
            y: min(maxY ,max(minY, destination.y)))
    }
}

Code - Get PDF Page Height and Width

 let page = pdfDocument.page(at: 0)
 let pageRect = page?.bounds(for: .mediaBox)

 print("pdf page width =", (pageRect?.size.width)!, "pdf page height =", (pageRect?.size.height)!)

Body:
I would recommend PDFAnnotation rather that UIView for adding content onto the PDFView.

It is not so easy to compare a UIView's frame within a PDFView due to their coordinate systems being different.

Adding a PDFAnnotation to the PDFView works in sync with the PDF coordinate system whereas working with UIView, you will need to do some conversions between coordinate spaces and this can be tricky and not so accurate.

Here are some small changes I made to kind of get this to work with a view.

First in your SignatoryXibView I added this function to show a red border when we are close to the edge

func showWarning(_ show: Bool)
{
    if show
    {
        contentView1.layer.borderColor = UIColor.red.cgColor
        return
    }

    contentView1.layer.borderColor = UIColor.green.cgColor
}

I believe the SignatoryXibView should not be responsible for detecting and preventing going out of its superviews bounds so I created a protocol which the ViewController needs to conform to so that it can prevent the SignatoryXibView going out of the PDFView bounds.

protocol SignatoryViewDelegate: class
{
    func signatoryView(_ signatoryView: SignatoryXibView,
                       didReceivePanGesture gesture: UIPanGestureRecognizer)
}

class SignatoryXibView: UIView {

    // Add this
    weak var delegate: SignatoryViewDelegate?

    // .. rest of your code

    @objc
    func pan(_ gesture: UIPanGestureRecognizer)
    {
        // Hand off view translation handling to the delegate
        self.delegate?.signatoryView(self,
                                     didReceivePanGesture: gesture)
    }
}

Now in your UIView extension, you created a translate method which works well however, you do not want to translate the view's location. You want to first check if the translation will go out of the desired boundary and prevent the translation from happening.

extension UIView {

    // Your original code
    func translate(_ translation: CGPoint) {
        let destination = center + translation
        let minX = frame.width/2
        let minY = frame.height/2
        let maxX = superview!.frame.width-minX
        let maxY = superview!.frame.height-minY
        center = CGPoint(
            x: min(maxX, max(minX, destination.x)),
            y: min(maxY ,max(minY, destination.y)))
    }

    // I have added this function to return the new rect
    // that would happen if this view translated
    func translatedRect(_ translation: CGPoint) -> CGRect
    {
        // All of this is your calculation
        let destination = center + translation

        let minX = frame.width/2
        let minY = frame.height/2
        let maxX = superview!.frame.width-minX
        let maxY = superview!.frame.height-minY

        var rect = CGRect(origin: .zero,
                          size: CGSize(width: bounds.width,
                                       height: bounds.height))

        let midX = min(maxX, max(minX, destination.x))
        let midY = min(maxY ,max(minY, destination.y))

        // I am not translating here, just creating a new rect
        // of the view if it would be translated
        rect.origin = CGPoint(x: midX - frame.width/2,
                              y: midY - frame.height/2)

        return rect
    }
}

In your ViewController's loadPDF() function, make your view controller the delegate of the SignatoryXibView

// Add Sign on PdfView
// Your code unchanged
let customView = SignatoryXibView(frame: CGRect(x: 150,
                                                y: 140,
                                                width: 112,
                                                height: 58))
customView.signatoryLabel.text = "John Doe"
self.pdfView.addSubview(customView)

//Add this
customView.delegate = self

Then finally you implement the delegate function we added earlier in the protocol to prevent the SignatoryXibView from going out the page's bounds.

extension ViewController: SignatoryViewDelegate
{
    func signatoryView(_ signatoryView: SignatoryXibView,
                       didReceivePanGesture gesture: UIPanGestureRecognizer)
    {
        // Get the location where the user has tapped
        let gestureTouchLocation = gesture.translation(in: signatoryView)

        // Get the new frame if the signature view would
        // be translated
        let updatedFrame
            = signatoryView.translatedRect(gestureTouchLocation)

        // Convert this rect from the Signature View's coordinate space
        // To the PDFView's coordinate space
        let updatedFrameConverted
        = pdfView.convert(updatedFrame,
                          to: pdfView.currentPage!)

        print("Updated frame: \(updatedFrame)")
        print("Updated frame converted: \(updatedFrameConverted)")
        print("Signature frame: \(signatoryView.frame)")
        print()

        // Retrieve the bounds of the current page
        // Handle the optional properly in your production app
        let pageRect = pdfView.currentPage!.bounds(for: .mediaBox)

        // Check if the new frame of SignatoryXibView is within the bounds of the pdf page
        if updatedFrameConverted.origin.x > CGFloat.zero &&
            updatedFrameConverted.origin.y + updatedFrameConverted.height < pageRect.height &&
            updatedFrameConverted.origin.x + updatedFrameConverted.width < pageRect.width &&
            updatedFrameConverted.origin.y > CGFloat.zero

        {
            // Since the view is within the bounds, you can update the views frame

            signatoryView.translate(gesture.translation(in: signatoryView))

            gesture.setTranslation(.zero, in: signatoryView)
            signatoryView.setNeedsDisplay()

            // Do not show any warning
            signatoryView.showWarning(false)

            return
        }

        // The view has reached the edge of the page so do not perform any view
        // translation and show the warning
        signatoryView.showWarning(true)
    }
}

The end result should give you the below result which prevents the view from going outside the page bounds and makes the view red to show it cannot go further:

Final thoughts

I recommend using PDFAnnotation when adding things to the PDF

This will scale and scroll with the pages properly especially in scenarios like zooming a PDF where you might need to update your view again for it to be in the right location

Update

I updated some math in the func signatoryView function in the extension ViewController: SignatoryViewDelegate

This should give you better results in terms of figuring out the right boundary and also it will work when you zoom:

However, since it is not added as an annotation, it will not scroll with the page but the same boundary will be observed on the next page.


来源: stackexchange

问:
How do you I React to get the button value into the input?
How can I modify it to allow to enter arbitrary values in 'input' and bring the button value into 'input'?
If the user presses the +1 button while entering 3, the value in 'input' increases by 1 from 3. And I hope he can delete the "input" value without the "delete" button.

Also, I want to set the default value to zero and let only positive numbers enter from zero. plz help me.

This is my code.

input-button.jsx

```<code>import React , { useState } from "react";

const PlusButton = () => {
  const [cnt, setCnt] = useState(0);

  const onIncrease = () => {
    setCnt(prevCnt => prevCnt + 1);
  }

  const onIncrease2 = () => {
    setCnt(prevCnt => prevCnt + 10);
  }

const onIncrease2 = () => {
    setCnt(prevCnt => prevCnt + 100);
  }
  return(
    <>
      <div>
        <input type="number" min='0' placeholder='Click button or Enter a random value' value={cnt}/>
      </div>

      <button onClick={onIncrease}>+1</button>
      <button onClick={onIncrease2}>+10</button>
      <button onClick={onIncrease2}>+100</button>
    </>
  );
}

export default PlusButton;
</code>```

(Note. I'm going to import this file to another file. like <PlusButton/>)

答:
Add onChange to the input.</p>
```<code> const onChange = (e) => {

    if (e.target.value === '') {
      setCnt(0)
      return;
    }
    if (e.target.checkValidity()) { //check if min=0
      setCnt(parseInt(e.target.value)) // allow only whole numbers using parseInt.
    }
 }

 const onIncrease = (value) => setCnt(prevCnt => prevCnt + value);

  <input type="number" onChange={onChange} min='0' placeholder='Click button or Enter a random value' value={cnt}/>

  <button onClick={() => onIncrease(1)}>+1</button>
  <button onClick={() => onIncrease(10)}>+10</button>
  <button onClick={() => onIncrease(100)}>+100</button>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I modify it to allow to enter arbitrary values in 'input' and bring the button value into 'input'?
If the user presses the +1 button while entering 3, the value in 'input' increases by 1 from 3. And I hope he can delete the "input" value without the "delete" button.

Also, I want to set the default value to zero and let only positive numbers enter from zero. plz help me.

This is my code.

input-button.jsx

import React , { useState } from "react";

const PlusButton = () => {
  const [cnt, setCnt] = useState(0);

  const onIncrease = () => {
    setCnt(prevCnt => prevCnt + 1);
  }

  const onIncrease2 = () => {
    setCnt(prevCnt => prevCnt + 10);
  }

const onIncrease2 = () => {
    setCnt(prevCnt => prevCnt + 100);
  }
  return(
    <>

        <input type="number" min='0' placeholder='Click button or Enter a random value' value={cnt}/>

      <button onClick={onIncrease}>+1</button>
      <button onClick={onIncrease2}>+10</button>
      <button onClick={onIncrease2}>+100</button>
    </>
  );
}

export default PlusButton;

(Note. I'm going to import this file to another file. like <PlusButton/>)

Body:
Add onChange to the input.

 const onChange = (e) => {

    if (e.target.value === '') {
      setCnt(0)
      return;
    }
    if (e.target.checkValidity()) { //check if min=0
      setCnt(parseInt(e.target.value)) // allow only whole numbers using parseInt.
    }
 }

 const onIncrease = (value) => setCnt(prevCnt => prevCnt + value);

  <input type="number" onChange={onChange} min='0' placeholder='Click button or Enter a random value' value={cnt}/>

  <button onClick={() => onIncrease(1)}>+1</button>
  <button onClick={() => onIncrease(10)}>+10</button>
  <button onClick={() => onIncrease(100)}>+100</button>


问:
fastest way to do keyword search in large text in C/C++
Say I have 100 keywords (that can include spaces) and I need to find out how many times they occur in a big piece of text. What would the fast way be to accomplish this?

My current idea is as follows:

turn the keywords into a suffix tree

walk through the text following the nodes and whenever a char does not occur (i.e. node->next == NULL) in the suffix tree, skip to next word and search again

The suffix tree struct would look something like this:

```<code>struct node {
   int count; //number of occurences (only used at leaf node)
   /* for each lower-case char, have a pointer to either NULL or next node */
   struct node *children[26];
};
</code>```

I am sure there is a faster way to do this, but what is it? Space efficiency is not really a big deal for this case (hence the children array for faster lookup), but time efficiency really is. Any suggestions?

答:
If it is a industrial application, use Boost Regex

It is tested, fast and chances are that it will save you a lot of pain.

ContentLicense: CC BY-SA 3.0

Body:
Say I have 100 keywords (that can include spaces) and I need to find out how many times they occur in a big piece of text. What would the fast way be to accomplish this?

My current idea is as follows:

turn the keywords into a suffix tree

walk through the text following the nodes and whenever a char does not occur (i.e. node->next == NULL) in the suffix tree, skip to next word and search again

The suffix tree struct would look something like this:

struct node {
   int count; //number of occurences (only used at leaf node)
   /* for each lower-case char, have a pointer to either NULL or next node */
   struct node *children[26];
};

I am sure there is a faster way to do this, but what is it? Space efficiency is not really a big deal for this case (hence the children array for faster lookup), but time efficiency really is. Any suggestions?


问:
No result got from HMS Site Kit
I am trying to integrate Huawei Site Kit Search Activity into the Flutter application. However, I got the error as shown in the picture, and no result was getting back.

答:
Error code 6003 means Inconsistent certificate fingerprint configurations. The proposed solution is:

Ensure that the certificate fingerprint packed in the app on your device is consistent with that configured through SHA-256 certificate fingerprint in AppGallery Connect. For details, please refer to Configuring App Information in AppGallery Connect.

HMS Core (APK) will cache the signature file. You need to find HMS Core (APK) on the Apps page of your device and clear its cache, restart your app, and perform the previous operation again.

You can use either way to get your apk fingerprint and compare to make sure it's the same one.

command example: jarsigner -verbose -verify MyAPK_base_v11.0.apk > MyAPK_info.txt

```<code>review MyAPK_info.txt and find ".RSA" path and use below command

unzip -p MyAPK_base_v11.0.apk META-INF/BNDLTOOL.RSA | keytool -printcert
</code>```

Result:

```<code>Certificate fingerprints:
SHA1: D0:88:29:99:94:C3:72:44:EA:CF:B1:6B:09:3E:01:95:FE:E4:45:BE
SHA256: EF:68:A7:0A:3A:47:F8:DD:46:58:52:EA:E2:59:AE:D6:1A:43:38:D8:14:26:05:9E:D3:99:C2:D1:F6:34:D9:DE
Signature algorithm name: SHA1withRSA (weak)
Subject Public Key Algorithm: 1024-bit RSA key (weak)
</code>```

command example: (apksigner.bat normally is in /android/build-tools folder)

apksigner.bat verify --print-certs MyAPK_base_v10.2.6-8569.apk

result:

```<code>Signer #1 certificate DN: CN=Michael Smith, OU=My Org, O=A Team, L=Okemos, ST=Michigan, C=US

Signer #1 certificate SHA-256 digest: ef68a70a3a47f8dd465852eae259aed61a4338d81426059ed399c2d1f634d9de

Signer #1 certificate SHA-1 digest: d088299994c37244eacfb16b093e0195fee445be

Signer #1 certificate MD5 digest: 68710e87d99e7f946958db33d3fcf13c
</code>```

Title: No result got from HMS Site Kit

Body:
Error code 6003 means Inconsistent certificate fingerprint configurations. The proposed solution is:

Ensure that the certificate fingerprint packed in the app on your device is consistent with that configured through SHA-256 certificate fingerprint in AppGallery Connect. For details, please refer to Configuring App Information in AppGallery Connect.

HMS Core (APK) will cache the signature file. You need to find HMS Core (APK) on the Apps page of your device and clear its cache, restart your app, and perform the previous operation again.

You can use either way to get your apk fingerprint and compare to make sure it's the same one.

command example: jarsigner -verbose -verify MyAPK_base_v11.0.apk > MyAPK_info.txt

review MyAPK_info.txt and find ".RSA" path and use below command

unzip -p MyAPK_base_v11.0.apk META-INF/BNDLTOOL.RSA | keytool -printcert

Result:

Certificate fingerprints:
SHA1: D0:88:29:99:94:C3:72:44:EA:CF:B1:6B:09:3E:01:95:FE:E4:45:BE
SHA256: EF:68:A7:0A:3A:47:F8:DD:46:58:52:EA:E2:59:AE:D6:1A:43:38:D8:14:26:05:9E:D3:99:C2:D1:F6:34:D9:DE
Signature algorithm name: SHA1withRSA (weak)
Subject Public Key Algorithm: 1024-bit RSA key (weak)

command example: (apksigner.bat normally is in /android/build-tools folder)

apksigner.bat verify --print-certs MyAPK_base_v10.2.6-8569.apk

result:

Signer #1 certificate DN: CN=Michael Smith, OU=My Org, O=A Team, L=Okemos, ST=Michigan, C=US

Signer #1 certificate SHA-256 digest: ef68a70a3a47f8dd465852eae259aed61a4338d81426059ed399c2d1f634d9de

Signer #1 certificate SHA-1 digest: d088299994c37244eacfb16b093e0195fee445be

Signer #1 certificate MD5 digest: 68710e87d99e7f946958db33d3fcf13c


问:
JavaFX trouble importing
I am new to java and I would like to convert a buffered image to a regular image object and then display to the screen. I am currently following this method (
JavaFX ImageView via FXML does not work
), but I am having trouble importing this library
javafx.embed.swing.SwingFXUtils

into my eclipse project, it claims that there is no such path as javafx.embed which causes an error at the import statement any help or guidance is appreciated thank you

Edit:
all other parts of the javaFX library such as buttons and text fields work fine so javaFX is configured properly, It is just with this 1 import I have a problem with

答: As javaFX is already bundled with JDK 8. I would suggest, try using java 8 instead, if it works, then your previous setup wasn't correct.</p>

Title: JavaFX trouble importing


问:
Cordova writing to a folder within the app structure
Using the Cordova file plugin how can I write files to a folder within the app?  I realise I can't use the www folder but how can I create a folder within the app to write to? Ideally where it cannot be opened by a third party when compiled.

The code I am using is as follows:

```<code>function createFile() {
 var type = window.TEMPORARY;
 var size = 5*1024*1024;
 window.requestFileSystem(type, size, successCallback, errorCallback)

 function successCallback(fs) {
  fs.root.getFile('log.txt', {create: true, exclusive: true}, function(fileEntry) {
     alert('File creation successfull!')
  }, errorCallback);
 }

 function errorCallback(error) {
  alert("ERROR: " + error.code)
 }

}
</code>```

Thanks in advance;

答:
Personally I'd use the cordova.file constants

Creating a directory

window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(directoryEntry) {
    directoryEntry.getDirectory("logDirectory", { create: true }, function(logDirectoryEntry) {
        logDirectoryEntry.getFile("log.txt", {create: true}, function (logFileEntry) {
            // Write file (see example below)
        });
    });
}, onError);
```
<h3>Writing a file</h3>
<pre class="lang-js prettyprint-override"><code>window.resolveLocalFileSystemURL(cordova.file.dataDirectory + "/log.txt", function(fileEntry) {
    fileEntry.createWriter(function(writer) {
        writer.onwriteend = function() {
            console.log("Success!");
        };

        writer.onerror = function(e) {
            console.log("Error :(", e);
        };

        writer.write("Hello");
    });
}, onError);
</code>```

Refer to the File System Layouts for the available cordova.file constants and where they are located physically on the file system, as well as additional  details for both iOS and android platforms.

cordova.file.dataDirectory is stored in the application's data container where no app, other than the app process itself has access to. The data will remain there unless the app deletes it or the app is uninstalled, or the user uses an OS function to clear the app (Android has a Clear Data button for example under App Info).

If you don't want files to be visible by third-party then stay away from any of the external file paths, such as cordova.file.externalDataDirectory

Body:
Using the Cordova file plugin how can I write files to a folder within the app?  I realise I can't use the www folder but how can I create a folder within the app to write to? Ideally where it cannot be opened by a third party when compiled.

The code I am using is as follows:

function createFile() {
 var type = window.TEMPORARY;
 var size = 5*1024*1024;
 window.requestFileSystem(type, size, successCallback, errorCallback)

 function successCallback(fs) {
  fs.root.getFile('log.txt', {create: true, exclusive: true}, function(fileEntry) {
     alert('File creation successfull!')
  }, errorCallback);
 }

 function errorCallback(error) {
  alert("ERROR: " + error.code)
 }

}

Thanks in advance;

Body:
Personally I'd use the cordova.file constants

Creating a directory

window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(directoryEntry) {
    directoryEntry.getDirectory("logDirectory", { create: true }, function(logDirectoryEntry) {
        logDirectoryEntry.getFile("log.txt", {create: true}, function (logFileEntry) {
            // Write file (see example below)
        });
    });
}, onError);

Writing a file

window.resolveLocalFileSystemURL(cordova.file.dataDirectory + "/log.txt", function(fileEntry) {
    fileEntry.createWriter(function(writer) {
        writer.onwriteend = function() {
            console.log("Success!");
        };

        writer.onerror = function(e) {
            console.log("Error :(", e);
        };

        writer.write("Hello");
    });
}, onError);

Refer to the File System Layouts for the available cordova.file constants and where they are located physically on the file system, as well as additional  details for both iOS and android platforms.

cordova.file.dataDirectory is stored in the application's data container where no app, other than the app process itself has access to. The data will remain there unless the app deletes it or the app is uninstalled, or the user uses an OS function to clear the app (Android has a Clear Data button for example under App Info).

If you don't want files to be visible by third-party then stay away from any of the external file paths, such as cordova.file.externalDataDirectory


问:
Splitting a string on an uppercase *or* lowercase letter
I have the following string:

```<code>foo = 'F9B2Z1F8B30Z4'
</code>```

I split this string on upper-case F, as such:

```<code>chunks = ['F' + elem for elem in foo.split('F') if elem != '']
</code>```

This gives me:

```<code>chunks
['F9B2Z1', 'F8B30Z4']
</code>```

But, now assume that one of the F characters is lowercase:

```<code>'F9B2Z1f8B30Z4'
</code>```

Now, we get:

```<code>chunks = ['F' + elem for elem in foo.split('F') if elem != '']
chunks
['F9B2Z1f8B30Z4']
</code>```

I'd like to be able to also split on lower-case f, such as:

```<code>chunks = ['F' + elem for elem in foo.split('F') if elem != '' <some other condition here>]
chunks
['F9B2Z1' 'f8B30Z4']
</code>```

I'm somewhat hesitant to use .replace() because after doing the split I need to perform some tests on the resulting list of chunks (e.g. test whether the first character of each chunk is uppercase or lowercase... and it would be difficult to do that if I replace lowercase Fs with uppercase Fs).

What's the best way to split on uppercase or lowercase without using RegEx?

Thanks!

答:
One way using enumerate:

```<code>foo = 'F9B2Z1f8B30Z4'

indices = [n for n, i in enumerate(foo) if i.lower() == "f"]
[foo[i:j] for i, j in zip(indices, indices[1:] + [None])]
</code>```

Output:

```<code>['F9B2Z1', 'f8B30Z4']
</code>```

Body:
I have the following string:

foo = 'F9B2Z1F8B30Z4'

I split this string on upper-case F, as such:

chunks = ['F' + elem for elem in foo.split('F') if elem != '']

This gives me:

chunks
['F9B2Z1', 'F8B30Z4']

But, now assume that one of the F characters is lowercase:

'F9B2Z1f8B30Z4'

Now, we get:

chunks = ['F' + elem for elem in foo.split('F') if elem != '']
chunks
['F9B2Z1f8B30Z4']

I'd like to be able to also split on lower-case f, such as:

chunks = ['F' + elem for elem in foo.split('F') if elem != '' <some other condition here>]
chunks
['F9B2Z1' 'f8B30Z4']

I'm somewhat hesitant to use .replace() because after doing the split I need to perform some tests on the resulting list of chunks (e.g. test whether the first character of each chunk is uppercase or lowercase... and it would be difficult to do that if I replace lowercase Fs with uppercase Fs).

What's the best way to split on uppercase or lowercase without using RegEx?

Thanks!

Body:
One way using enumerate:

foo = 'F9B2Z1f8B30Z4'

indices = [n for n, i in enumerate(foo) if i.lower() == "f"]
[foo[i:j] for i, j in zip(indices, indices[1:] + [None])]

Output:

['F9B2Z1', 'f8B30Z4']


问:
Django check if many-to-many relationship exists
I have a kind of social network in Django where people can send direct messages. Within all of those messages, I have a conversation field to show who the messages are between so that I can group the messages by person when displaying them to the user.

I'm trying to figure out how I can search for if a conversation exists. In the print statements below in the view, I get back:

```<code><QuerySet [<Conversation: Sarah and Stephen>, <Conversation: Sarah and James>]>

<QuerySet [<User: Sarah>, <User: Stephen>]>

<QuerySet [<User: Sarah>, <User: James>]>
</code>```

In the view below, the sender is 'Sarah' and the receiver is 'James', so I'm trying to figure out how I can search for if a conversation between them already exists (through filter or something) by matching them with the kinds of QuerySet lists above so that if so, I can use that conversation and if not, I can create the conversation. I've tried many things but keep getting stuck. I'm pretty new to many-to-many relationships.

The view

```<code>def writemessage(request, id):
    profile = Profile.objects.get(id=id)
    context = {
        'profile': profile,
    }
    conversations = Conversation.objects.all()
    print(conversations)
    for each in conversations:
        print(each.participants.all())
    if request.method == 'POST':
        sender = request.user
        receiver = profile.user
        content = request.POST['content']
        timestamp = datetime.now()
        record = Message(sender=sender, receiver=receiver, content=content, timestamp=timestamp)
        record.save()
        senderprofile = Profile.objects.get(user=sender)
        receiverprofile = Profile.objects.get(user=receiver)
        # below is where the code breaks
        record.conversation.add(senderprofile)
        record.conversation.add(receiverprofile)
        return redirect('messagespage')
    return render(request, 'thecode/writemessage.html', context)
</code>```

My models

```<code>class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    city = models.CharField(max_length=60)
    country = models.CharField(max_length=60)
    skillstolearn = models.CharField(max_length=200)
    skillstoteach = models.CharField(max_length=200)
    description = models.TextField()

    def __str__(self):
        return self.user.username

class Conversation(models.Model):
    participants = models.ManyToManyField(User)

    def __str__(self):
        return str(self.participants.all()[0]) + ' and ' + str(self.participants.all()[1])
</code>```

答:
For finding Conversation where the M2M only contains those 2 users, you can use chain filters() and use exists() to check if that Conversation exists between those 2 users:</p>
```<code>sarah_user = User.objects.get(username="Sarah")
stephen_user = User.objects.get(username="Stephen")
Conversation.objects.filter(participants=sarah_user).filter(participants=stephen_user).exists()
</code>```

Body:
I have a kind of social network in Django where people can send direct messages. Within all of those messages, I have a conversation field to show who the messages are between so that I can group the messages by person when displaying them to the user.

I'm trying to figure out how I can search for if a conversation exists. In the print statements below in the view, I get back:

<QuerySet [<Conversation: Sarah and Stephen>, <Conversation: Sarah and James>]>

<QuerySet [<User: Sarah>, <User: Stephen>]>

<QuerySet [<User: Sarah>, <User: James>]>

In the view below, the sender is 'Sarah' and the receiver is 'James', so I'm trying to figure out how I can search for if a conversation between them already exists (through filter or something) by matching them with the kinds of QuerySet lists above so that if so, I can use that conversation and if not, I can create the conversation. I've tried many things but keep getting stuck. I'm pretty new to many-to-many relationships.

The view

def writemessage(request, id):
    profile = Profile.objects.get(id=id)
    context = {
        'profile': profile,
    }
    conversations = Conversation.objects.all()
    print(conversations)
    for each in conversations:
        print(each.participants.all())
    if request.method == 'POST':
        sender = request.user
        receiver = profile.user
        content = request.POST['content']
        timestamp = datetime.now()
        record = Message(sender=sender, receiver=receiver, content=content, timestamp=timestamp)
        record.save()
        senderprofile = Profile.objects.get(user=sender)
        receiverprofile = Profile.objects.get(user=receiver)
        # below is where the code breaks
        record.conversation.add(senderprofile)
        record.conversation.add(receiverprofile)
        return redirect('messagespage')
    return render(request, 'thecode/writemessage.html', context)

My models

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    city = models.CharField(max_length=60)
    country = models.CharField(max_length=60)
    skillstolearn = models.CharField(max_length=200)
    skillstoteach = models.CharField(max_length=200)
    description = models.TextField()

    def __str__(self):
        return self.user.username

class Conversation(models.Model):
    participants = models.ManyToManyField(User)

    def __str__(self):
        return str(self.participants.all()[0]) + ' and ' + str(self.participants.all()[1])

Body:
For finding Conversation where the M2M only contains those 2 users, you can use chain filters() and use exists() to check if that Conversation exists between those 2 users:

sarah_user = User.objects.get(username="Sarah")
stephen_user = User.objects.get(username="Stephen")
Conversation.objects.filter(participants=sarah_user).filter(participants=stephen_user).exists()


问:
Silverlight website
I am looking for develop a website in silverlight 4.
I am confused  about which silver light template in VS 2010 is best for creating silver light website[internet application]?
Which is best design pattern[mvc or mvvm] to implement the same silver light website.
please give your valuable suggestion . so i can move further.

Thanks in advance!!

答:
If you want to develop a large Silverlight website I would suggest the following (based on experience of very large Silverlight websites):

Use ASP.NET MVC 3 (aka RAZOR) for your hosting site:

This will allow you to more easily create a parallel HTML site for your Silverlight content (for Search Engines to find your content)

Use RIA Services:

Specifically use the RIA Services as libraries option, for data transport to/from the Silverlight client.

See my answer here for some details: Difference b/w creating a RIA Services Solution and RIA Services class library

Use PRISM:

Use the PRISM pattern to allow for large very loosely coupled modules (this also gives you IOC with Unity and some other cool stuff).

Use MVVM with controllers:

We call this MVCVM, but it is not an official pattern anywhere :)

Controllers are the place to hook event responses, load data into viewmodels, create and show (manually injected) views etc. They are very lightweight and are the only objects that need to exist for the life of the application.

ViewModels do not have any knowledge of how they are displayed or where the data comes from

Views know they can display a certain shape of data, but have no idea where the data/viewmodel comes from.

Use a navigation system

Use the built-in navigation (uses bookmarks to stay on the Silverlight page while providing structured information).

This can be easily translated to an APS.NET MVC 3 equivalent for Search Engine use on your HTML only hosting MVC site.

We wound up using a custom navigation provider so that we could store simple state information for modules in the URL as well.

Title: Silverlight website


问:
Add overlay color to an image using Xamarin.Forms
I'd like to add some icons in my app especially in listviews using custom cell and specify the color to be rendered.
I don't want to edit each image in Photoshop; I want to apply an overlay color at runtime.

Is that possible with a custom renderer?

答:
Now We got another way with Xamarin.CommunityToolkit. We can use its IconTintColorEffect.TintColor for changing Tint Color or Overlay of an Image.

```<code><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:xct="http://xamarin.com/schemas/2020/toolkit"
         x:Class="MyLittleApp.MainPage">
    <StackLayout>
        <Image Source="monkey" xct:IconTintColorEffect.TintColor="Red" />
    </StackLayout>
</ContentPage>
</code>```

Xamarin.CommunityToolkit is handy and provides lot of features such as Shadows on any View, EventToCommandBehavior for MVVMifying lot of Events and Controls, it also has additional Converters, Extensions, Helpers, and Views that are not available in builtin Xamarin Forms yet.

Refer for more Documentation

Body:
Now We got another way with Xamarin.CommunityToolkit. We can use its IconTintColorEffect.TintColor for changing Tint Color or Overlay of an Image.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:xct="http://xamarin.com/schemas/2020/toolkit"
         x:Class="MyLittleApp.MainPage">
    <StackLayout>
        <Image Source="monkey" xct:IconTintColorEffect.TintColor="Red" />
    </StackLayout>
</ContentPage>

Xamarin.CommunityToolkit is handy and provides lot of features such as Shadows on any View, EventToCommandBehavior for MVVMifying lot of Events and Controls, it also has additional Converters, Extensions, Helpers, and Views that are not available in builtin Xamarin Forms yet.

Refer for more Documentation


问:
How to increase a integer every second
I'm making a dodging game in Python where I want the score to increase by 1 every second, but the problem is that I don't know how. It would be nice to find a solution where I don't have to change too much of my code.

Can someone please help?

答:
As you iterate through the game loop, you can check the current time with the time library. You can then check if it has been a second since the last time you awarded a point.
It might look something like this:</p>
```<code>import time
points = 0
currentTime = time.time()
previousPointAwardedTime = currentTime

while gameRunning == True:
    ...
    currentTime = time.time()
    if (currentTime - previousPointAwardedTime) >= 1:
        points += 1
        previousPointAwardedTime = currentTime
</code>```

Title: How to increase a integer every second

Body:
As you iterate through the game loop, you can check the current time with the time library. You can then check if it has been a second since the last time you awarded a point.
It might look something like this:

import time
points = 0
currentTime = time.time()
previousPointAwardedTime = currentTime

while gameRunning == True:
    ...
    currentTime = time.time()
    if (currentTime - previousPointAwardedTime) >= 1:
        points += 1
        previousPointAwardedTime = currentTime


答:
you can try using asyncio</p>
```<code>import asyncio

score = 0  # starting game with a score of zero

async def s():
    global score
    score += 1 #increasing score by 1
    await asyncio.sleep(1)  #waiting for 1 second

while True:  #while game is running
    asyncio.run(s()) #calling function
    print(score)  #printing score
</code>```

Title: How to increase a integer every second

Body:
I'm making a dodging game in Python where I want the score to increase by 1 every second, but the problem is that I don't know how. It would be nice to find a solution where I don't have to change too much of my code.

Can someone please help?

Body:
you can try using asyncio

import asyncio

score = 0  # starting game with a score of zero

async def s():
    global score
    score += 1 #increasing score by 1
    await asyncio.sleep(1)  #waiting for 1 second

while True:  #while game is running
    asyncio.run(s()) #calling function
    print(score)  #printing score


问:
Getting 250 OK status Delivered from SendGrid, but the email never ends up in the mailbox
```<code>function sendEmailVerification(username, email, destination, response, cb){

    // create a random number
    var email_url = security.createEmailToken(username, email);

    // create a new URL for the verify call that will go into the email
    link=PROTOCOL+"://"+destination+"/verify?token="+email_url;

//      to : request.query.to,
   var verifyEmail = new sendgrid.Email();
    verifyEmail.addTo(email);
    verifyEmail.setSubject('Verify your email with example.com.');
    verifyEmail.setFrom('verify@example.com');
    verifyEmail.setText(link);
    verifyEmail.setHtml(link);

    verifyEmail.addFilter('templates', 'enable', 1);
    verifyEmail.addFilter('templates', 'template_id', '3cf3g721-4a31-4fd1-a862-408707e18c96');

    logger.debug("send: mail options for user: " + JSON.stringify(verifyEmail));

    // use the smtp transport to send the email
    sendgrid.send(verifyEmail, function(error, resp) {
        if (error) {
            logger.error(error);
            response.status(500).send("A backend email send error occurred.");
            response.end();
        } else {
            logger.debug("Message sent: " + resp.message);
            response.status(200).send("email sent");
        }
        cb();
    });
}
</code>```

What am I doing wrong? It seems the client service is not accepting my emails. Is it a problem with the headers? I am attempting to send a verification email with a SendGrid template.

Any suggestions are greatly appreciated, and thank you ahead of time!

答: I had this error and turned out GMail was sending my messages to Spam and Trash.</p>

Body:
function sendEmailVerification(username, email, destination, response, cb){

    // create a random number
    var email_url = security.createEmailToken(username, email);

    // create a new URL for the verify call that will go into the email
    link=PROTOCOL+"://"+destination+"/verify?token="+email_url;

//      to : request.query.to,
   var verifyEmail = new sendgrid.Email();
    verifyEmail.addTo(email);
    verifyEmail.setSubject('Verify your email with example.com.');
    verifyEmail.setFrom('verify@example.com');
    verifyEmail.setText(link);
    verifyEmail.setHtml(link);

    verifyEmail.addFilter('templates', 'enable', 1);
    verifyEmail.addFilter('templates', 'template_id', '3cf3g721-4a31-4fd1-a862-408707e18c96');

    logger.debug("send: mail options for user: " + JSON.stringify(verifyEmail));

    // use the smtp transport to send the email
    sendgrid.send(verifyEmail, function(error, resp) {
        if (error) {
            logger.error(error);
            response.status(500).send("A backend email send error occurred.");
            response.end();
        } else {
            logger.debug("Message sent: " + resp.message);
            response.status(200).send("email sent");
        }
        cb();
    });
}

What am I doing wrong? It seems the client service is not accepting my emails. Is it a problem with the headers? I am attempting to send a verification email with a SendGrid template.

Any suggestions are greatly appreciated, and thank you ahead of time!


问:
Is there a better way to get XmlReader NodeType properties?
Based on this, it looks like each time I want to get a node element name, or a text value or whatever, I need to use switch-case.

So do I have to use something like this:

```<code>while (reader.Read())
{
    switch (reader.NodeType)
    {
        case XmlNodeType.Element:
        nodeName = reader.Name;
        break;
    }
}
</code>```

or am I missing something and it could be made shorter and more elegant (I need to use XmlReader, and am not in position to use LINQ to XML)? The idea of having to use all this switch-case mess everywhere just to get these small bits of information is not very appealing to me. Thank you.

答:
The one thing about the Switch case is that it's very clear about your intentions, which I believe is an important thing in modern programming.

However, if you're tired of writing it all the time, and I can't blame you, what about wrapping it in an Extension method ?

Body:
Based on this, it looks like each time I want to get a node element name, or a text value or whatever, I need to use switch-case.

So do I have to use something like this:

while (reader.Read())
{
    switch (reader.NodeType)
    {
        case XmlNodeType.Element:
        nodeName = reader.Name;
        break;
    }
}

or am I missing something and it could be made shorter and more elegant (I need to use XmlReader, and am not in position to use LINQ to XML)? The idea of having to use all this switch-case mess everywhere just to get these small bits of information is not very appealing to me. Thank you.


问:
My css won't load after i declare it on head of html
My folder looks like this:

```<code>root/
-templates/
--css/
---styles.css
--chat.html
-main.go
</code>```

Here was my handler:

```<code>http.Handle("/", &templateHandler{filename: "login.html"})

http.Handle("/css/", http.StripPrefix("/css", http.FileServer(http.Dir("./templates/css/"))))

http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))

http.Handle("/login", &templateHandler{filename: "login.html"})

http.Handle("/room", r)

</code>```

At the head of my chat.html, i link my css with code below

```<code><link href="css/styles.css" rel="styleshseet" >
</code>```

When I am starting to Listen and Serve it, the CSS won't load.
But when I put style code in my HTML head like below, it works.

```<code><style>
 my CSS code
</style>
</code>```

Integrity bootstrap CSS also work properly, and I have tried to put my CSS on raw Github, it also doesn't work,

```<code><link href="https://raw.githubusercontent.com/Triad-0112/Web-ChatProject/master/chat/templates/css/styles.css" rel="stylesheet">
<link href="/chat/templates/css/styles.css" rel="stylesheet">
<link href="./css/styles.css" rel="stylesheet">
</code>```

All those three also don't work.
Any idea what did I miss?

答: I'm sorry. It won't load because it loads old CSS from cookies. When I switched to another browser, it worked by using /css/, which I declared on the CSS Fileserver handler. Thanks mkopriva</p>

Body:
My folder looks like this:

root/
-templates/
--css/
---styles.css
--chat.html
-main.go

Here was my handler:

http.Handle("/", &templateHandler{filename: "login.html"})

http.Handle("/css/", http.StripPrefix("/css", http.FileServer(http.Dir("./templates/css/"))))

http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))

http.Handle("/login", &templateHandler{filename: "login.html"})

http.Handle("/room", r)

At the head of my chat.html, i link my css with code below

<link href="css/styles.css" rel="styleshseet" >

When I am starting to Listen and Serve it, the CSS won't load.
But when I put style code in my HTML head like below, it works.

Integrity bootstrap CSS also work properly, and I have tried to put my CSS on raw Github, it also doesn't work,

<link href="https://raw.githubusercontent.com/Triad-0112/Web-ChatProject/master/chat/templates/css/styles.css" rel="stylesheet">
<link href="/chat/templates/css/styles.css" rel="stylesheet">
<link href="./css/styles.css" rel="stylesheet">

All those three also don't work.
Any idea what did I miss?


问:
Snowflake JSON import into Stage with double quote in column value
I've set stage file format as JSON and trying to import below data from Azure blob, getting error. see 2nd line last SQLTableName value has double quote.

{"SQLDatabaseName":"TV","SQLSchemaName":"sec","SQLTableName":"UserProfile"}
{"SQLDatabaseName":"LW","SQLSchemaName":"sec","SQLTableName":"User"Profile"}

in sql server i am exporting each row in json above format to move data into snowflake.

答:
Your data in JSON format is incorrect, the second line is not JSON validated.
Check your sample data on this page: JSON Formatter & Validator

You should use some escape character when exporting.

It does not validate:

SELECT PARSE_JSON('{"SQLDatabaseName":"LW","SQLSchemaName":"sec","SQLTableName":"User"Profile"}');
```
<p>If you change your data and add an escape character, it will validate:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT PARSE_JSON('{"SQLDatabaseName":"LW","SQLSchemaName":"sec","SQLTableName":"User\'Profile"}');

SELECT PARSE_JSON('{"SQLDatabaseName":"LW","SQLSchemaName":"sec","SQLTableName":"User\\"Profile"}');
</code>```

Body:
Your data in JSON format is incorrect, the second line is not JSON validated.
Check your sample data on this page: JSON Formatter & Validator

You should use some escape character when exporting.

It does not validate:

SELECT PARSE_JSON('{"SQLDatabaseName":"LW","SQLSchemaName":"sec","SQLTableName":"User"Profile"}');

If you change your data and add an escape character, it will validate:

SELECT PARSE_JSON('{"SQLDatabaseName":"LW","SQLSchemaName":"sec","SQLTableName":"User\'Profile"}');

SELECT PARSE_JSON('{"SQLDatabaseName":"LW","SQLSchemaName":"sec","SQLTableName":"User\\"Profile"}');


问:
Why does Option<&str>::cloned() not produce an Option<String>?
I have an Option<&str> and I would like to end up with an Option<String>. For other types, Option::cloned would be an easy way to do that. The docs even say:

pub fn cloned(self) -> Option<T>

Maps an Option<&T> to an Option<T> by cloning the contents of the option.

However, trying this actually results in a compile error:

fn main() {
    let unowned_str_maybe: Option<&str> = Some("abc");
    let owned_str_maybe: Option<String> = unowned_str_maybe.cloned();  // <-- unsatisfied trait bounds
    println!("{:?}", owned_str_maybe);
}

/* Compile error is:

 error[E0599]: the method `cloned` exists for enum `Option<&str>`, but its trait bounds were not satisfied
   --> src/main.rs:5:61
    |
5   |       let owned_str_maybe: Option<String> = unowned_str_maybe.cloned();  // <-- unsatisfied trait bounds
    |                                                               ^^^^^^ method cannot be called on `Option<&str>` due to unsatisfied trait bounds
    |
    = note: the following trait bounds were not satisfied:
            `str: Sized`
            `str: Clone`
            `Option<&str>: Iterator`
            which is required by `&mut Option<&str>: Iterator`
*/
```

Using a more verbose (less idiomatic?) construction of .map(|x| x.to_string()) does compile. Why does Option::cloned not work for converting &str to String?

答:
The reason is that Clone (which is used by Option::cloned) is used only to convert from &T to T, not from &T to U, even if semantically U is an owned version of &T (as String is to &str). In fact, you probably wouldn't expect this function to compile:

```<code>fn cloned(input: &str) -> String {
    input.clone()
}
</code>```

But Option::cloned is, essentially, .map(cloned), so it will work only if cloned works.

In fact, your approach with to_string is probably idiomatic. You probably could use function reference instead of closure, i.e. .map(ToString::to_string), or replace to_string with to_owned, but this is not so important.

Body:
I have an Option<&str> and I would like to end up with an Option<String>. For other types, Option::cloned would be an easy way to do that. The docs even say:

pub fn cloned(self) -> Option<T>

Maps an Option<&T> to an Option<T> by cloning the contents of the option.

However, trying this actually results in a compile error:

fn main() {
    let unowned_str_maybe: Option<&str> = Some("abc");
    let owned_str_maybe: Option<String> = unowned_str_maybe.cloned();  // <-- unsatisfied trait bounds
    println!("{:?}", owned_str_maybe);
}

/* Compile error is:

 error[E0599]: the method `cloned` exists for enum `Option<&str>`, but its trait bounds were not satisfied
   --> src/main.rs:5:61
    |
5   |       let owned_str_maybe: Option<String> = unowned_str_maybe.cloned();  // <-- unsatisfied trait bounds
    |                                                               ^^^^^^ method cannot be called on `Option<&str>` due to unsatisfied trait bounds
    |
    = note: the following trait bounds were not satisfied:
            `str: Sized`
            `str: Clone`
            `Option<&str>: Iterator`
            which is required by `&mut Option<&str>: Iterator`
*/

Using a more verbose (less idiomatic?) construction of .map(|x| x.to_string()) does compile. Why does Option::cloned not work for converting &str to String?

Body:
The reason is that Clone (which is used by Option::cloned) is used only to convert from &T to T, not from &T to U, even if semantically U is an owned version of &T (as String is to &str). In fact, you probably wouldn't expect this function to compile:

fn cloned(input: &str) -> String {
    input.clone()
}

But Option::cloned is, essentially, .map(cloned), so it will work only if cloned works.

In fact, your approach with to_string is probably idiomatic. You probably could use function reference instead of closure, i.e. .map(ToString::to_string), or replace to_string with to_owned, but this is not so important.


问:
label associated to findcontour with opencv
I have a mask from which I get the contours information using

```<code>contours, hierarchy = cv2.findContours(mask.astype('uint8'),cv2.RETR_CCOMP,cv2.CHAIN_APPROX_NONE)
</code>```

How do I get the corresponding label array i.e. an array the same size of mask where values are the indices of contours and located on points of mask which are inside corresponding contours ? I found a way using matplotlib.contains_points function but it is very slow. I'm sure there is another way but strangely I can't find it...here is the version with contains_points :

```<code>points = np.vstack((Xm.flatten(),Ym.flatten())).T
labels = -np.ones((mask.shape[0]*mask.shape[1],1))
for ic,contour in enumerate(contours):
    px = contour[:,0,0];
    py = contour[:,0,1];
    p = Path(list(zip(px,py))) # make a polygon
    Inpoints = p.contains_points(points)
    labels[Inpoints] = ic
</code>```

I'm also trying using cv2.connectedComponents but I can't find a way to get the proper indices as connectedComponents is independent from findcontours...EDIT : here is the piece of code:

```<code># labels of objects
_, labels_obj = cv2.connectedComponents(mask.astype('uint8'))
labels_obj = labels_obj - 1 # remove background
tmp = np.copy(labels_obj)
for ir,iro in enumerate(reg_objects):
    tmp[labels_obj==ir] = iro + 1
tmp[tmp<0]=0
labels_obj = tmp
# labels of holes present in objects
_, labels_hol = cv2.connectedComponents((1-mask).astype('uint8'))
labels_hol = labels_hol - 2 # remove background (objects are 0 and background is 1 so -2)
tmp = np.copy(labels_hol)
for ir,irh in enumerate(reg_holes):
    tmp[labels_hol==ir] = irh + 1
tmp[tmp<0]=0
labels_hol = tmp
# merge
labels = labels_obj + labels_hol - 1
</code>```

labels is then an array the same size of maks for which values point to the different objects and holes of mask. The problem is that labels==0 will not point to the same object/hole than contours[0] ...
EDIT : the label array is to be used in skimage.measure.regionprops

答:
As suggested in the comments, you can create this mask by drawing contours onto a blank image :

```<code>label_map = np.zeros_like(mask, dtype = 'uint8')
contours, hierarchy = cv2.findContours(mask.astype('uint8'),cv2.RETR_CCOMP,cv2.CHAIN_APPROX_NONE)

for i, contour in enumerate(contours):
    label_map = cv2.drawContours(label_map, [contour], -1, (255/(i+1)), -1)#draw and fill the contour with color (255/(1+1)).
</code>```

Note that the argument (255/(i+1)) is only a way of generating a set of len(contours) different grayscales, you may change it with a set of colors.

Body:
I have a mask from which I get the contours information using

contours, hierarchy = cv2.findContours(mask.astype('uint8'),cv2.RETR_CCOMP,cv2.CHAIN_APPROX_NONE)

How do I get the corresponding label array i.e. an array the same size of mask where values are the indices of contours and located on points of mask which are inside corresponding contours ? I found a way using matplotlib.contains_points function but it is very slow. I'm sure there is another way but strangely I can't find it...here is the version with contains_points :

points = np.vstack((Xm.flatten(),Ym.flatten())).T
labels = -np.ones((mask.shape[0]*mask.shape[1],1))
for ic,contour in enumerate(contours):
    px = contour[:,0,0];
    py = contour[:,0,1];
    p = Path(list(zip(px,py))) # make a polygon
    Inpoints = p.contains_points(points)
    labels[Inpoints] = ic

I'm also trying using cv2.connectedComponents but I can't find a way to get the proper indices as connectedComponents is independent from findcontours...EDIT : here is the piece of code:

# labels of objects
_, labels_obj = cv2.connectedComponents(mask.astype('uint8'))
labels_obj = labels_obj - 1 # remove background
tmp = np.copy(labels_obj)
for ir,iro in enumerate(reg_objects):
    tmp[labels_obj==ir] = iro + 1
tmp[tmp<0]=0
labels_obj = tmp
# labels of holes present in objects
_, labels_hol = cv2.connectedComponents((1-mask).astype('uint8'))
labels_hol = labels_hol - 2 # remove background (objects are 0 and background is 1 so -2)
tmp = np.copy(labels_hol)
for ir,irh in enumerate(reg_holes):
    tmp[labels_hol==ir] = irh + 1
tmp[tmp<0]=0
labels_hol = tmp
# merge
labels = labels_obj + labels_hol - 1

labels is then an array the same size of maks for which values point to the different objects and holes of mask. The problem is that labels==0 will not point to the same object/hole than contours[0] ...
EDIT : the label array is to be used in skimage.measure.regionprops

Body:
As suggested in the comments, you can create this mask by drawing contours onto a blank image :

label_map = np.zeros_like(mask, dtype = 'uint8')
contours, hierarchy = cv2.findContours(mask.astype('uint8'),cv2.RETR_CCOMP,cv2.CHAIN_APPROX_NONE)

for i, contour in enumerate(contours):
    label_map = cv2.drawContours(label_map, [contour], -1, (255/(i+1)), -1)#draw and fill the contour with color (255/(1+1)).

Note that the argument (255/(i+1)) is only a way of generating a set of len(contours) different grayscales, you may change it with a set of colors.


问:
React setState in a loop with time delay is not triggering rerenders
I'm trying to mimic a simple sorting algorithm and use React setState to store the sorted array (as "output") in real-time with an interval of 100ms so it can show on the screen as an algorithm visualizer. The sorted array can be displayed in the console but the React state is not updating real-time accordingly. How can I fix this?

```<code>  const [output, setOutput] = useState([]);

  const timer = (ms) => new Promise((res) => setTimeout(res, ms));

  const Simple_Sorting_Algo = (n) => {
    const array = [];
    for (var i = 0; i < n; i++) {
      array.push(Math.floor(Math.random() * 1000));  //generating a random array
    }

    const sortedArr = [...array];
    const send = async () => {
      for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
          if (sortedArr[i] > sortedArr[j]) {
            var tmp = sortedArr[i];
            sortedArr[i] = sortedArr[j];
            sortedArr[j] = tmp;
            console.log(sortedArr);
            setOutput(sortedArr);
            console.log(output);
            await timer(100);     //delay
          }
        }
      }
    };
    send();
  };
</code>```

答:
You have to update the state immutably.

setOutput(sortedArr) should be setOutput([...sortedArr])

The sort function mutates the array in each iteration which is fine, but you can't use the mutated array for updating the state because React doesn't rerender the component when it receives the same array every time.

Body:
I'm trying to mimic a simple sorting algorithm and use React setState to store the sorted array (as "output") in real-time with an interval of 100ms so it can show on the screen as an algorithm visualizer. The sorted array can be displayed in the console but the React state is not updating real-time accordingly. How can I fix this?

  const [output, setOutput] = useState([]);

  const timer = (ms) => new Promise((res) => setTimeout(res, ms));

  const Simple_Sorting_Algo = (n) => {
    const array = [];
    for (var i = 0; i < n; i++) {
      array.push(Math.floor(Math.random() * 1000));  //generating a random array
    }

    const sortedArr = [...array];
    const send = async () => {
      for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
          if (sortedArr[i] > sortedArr[j]) {
            var tmp = sortedArr[i];
            sortedArr[i] = sortedArr[j];
            sortedArr[j] = tmp;
            console.log(sortedArr);
            setOutput(sortedArr);
            console.log(output);
            await timer(100);     //delay
          }
        }
      }
    };
    send();
  };


问:
Doesn't show retrofit + viewmodel data
Good evening. Faced a problem when using retrofit, viewmodel. The problem is that the application starts but no data is displayed. I hope you'll give me a hand! If you need more information, feel free to write!

API I am using - https://swapi.dev/documentation

My model code:

```<code>data class Characters(
    @SerializedName("name") val characters: String,
    @SerializedName("gender") val gender: String,
    @SerializedName("height") val height: String,
    @SerializedName("mass") val mass: String,
)
</code>```
```<code></code>```

Viewmodel

```<code>class HomeViewModel() : ViewModel() {

    var repository = StarWarsRepository()
    val list: MutableLiveData<Response<Characters>> = MutableLiveData()

    fun getCharacterViewModel() {
        viewModelScope.launch {
            list.value = repository.getCharacters()
        }
    }
}
</code>```

Fragment

```<code>class HomeFragment : Fragment() {

    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!
    private lateinit var viewModel: HomeViewModel
    lateinit var recyclerView: RecyclerView
    private lateinit var adapter: HomeListAdapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        viewModel = ViewModelProvider(this).get((HomeViewModel::class.java))
        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        val view = binding.root

        recyclerView = binding.recycler
        adapter = HomeListAdapter()
        recyclerView.adapter = adapter
        viewModel.getCharacterViewModel()
        viewModel.list.observe(this, { list ->
            list.body()?.let {
                adapter.setList(it)
            }
        })
        return view

    }

}
</code>```

Repository

```<code>class StarWarsRepository() {

    suspend fun getCharacters(): Response<Characters> {
        return RetrofitBuilder.api.getCharacters()
    }
}

</code>```

Adapter

```<code>class HomeListAdapter() :
    RecyclerView.Adapter<HomeListAdapter.HomeViewHolder>() {
    var peopleList = ArrayList<Characters>()

    class HomeViewHolder(var binding: ItemCharacterBinding) :
        RecyclerView.ViewHolder(binding.root) {

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HomeViewHolder {
        return HomeViewHolder(
            ItemCharacterBinding.inflate(
                LayoutInflater
                    .from(parent.context), parent, false
            )
        )
    }

    override fun onBindViewHolder(holder: HomeViewHolder, position: Int) {
        val characterList = peopleList[position]
        holder.binding.characterName.text = characterList.characters
    }

    override fun getItemCount(): Int {
        return peopleList.size
    }

    @SuppressLint("NotifyDataSetChanged")
    fun setList(list: Characters) {
        peopleList = arrayListOf(list)
        notifyDataSetChanged()
    }

    }

</code>```

Interface

```<code>interface StarWarsApi {

    @GET("people/")
    suspend fun getCharacters(): Response<Characters>

}
</code>```

答:
It appears that you have not used a LayoutManager in your recycler view.

Before adding adapter, or on onCreateView, call:

```<code>recyclerView.layoutManager=LinearLayoutManager(requireContext())
recyclerView.adapter = adapter
</code>```

Also, try to log the list before setting it:

```<code>Log.i("HomeFragment", "list log: $it")
adapter.setList(it)
</code>```

Title: Doesn't show retrofit + viewmodel data

Body:
Good evening. Faced a problem when using retrofit, viewmodel. The problem is that the application starts but no data is displayed. I hope you'll give me a hand! If you need more information, feel free to write!

API I am using - https://swapi.dev/documentation

My model code:

data class Characters(
    @SerializedName("name") val characters: String,
    @SerializedName("gender") val gender: String,
    @SerializedName("height") val height: String,
    @SerializedName("mass") val mass: String,
)

Viewmodel

class HomeViewModel() : ViewModel() {

    var repository = StarWarsRepository()
    val list: MutableLiveData<Response<Characters>> = MutableLiveData()

    fun getCharacterViewModel() {
        viewModelScope.launch {
            list.value = repository.getCharacters()
        }
    }
}

Fragment

class HomeFragment : Fragment() {

    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!
    private lateinit var viewModel: HomeViewModel
    lateinit var recyclerView: RecyclerView
    private lateinit var adapter: HomeListAdapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        viewModel = ViewModelProvider(this).get((HomeViewModel::class.java))
        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        val view = binding.root

        recyclerView = binding.recycler
        adapter = HomeListAdapter()
        recyclerView.adapter = adapter
        viewModel.getCharacterViewModel()
        viewModel.list.observe(this, { list ->
            list.body()?.let {
                adapter.setList(it)
            }
        })
        return view

    }

}

Repository

class StarWarsRepository() {

    suspend fun getCharacters(): Response<Characters> {
        return RetrofitBuilder.api.getCharacters()
    }
}

Adapter

class HomeListAdapter() :
    RecyclerView.Adapter<HomeListAdapter.HomeViewHolder>() {
    var peopleList = ArrayList<Characters>()

    class HomeViewHolder(var binding: ItemCharacterBinding) :
        RecyclerView.ViewHolder(binding.root) {

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HomeViewHolder {
        return HomeViewHolder(
            ItemCharacterBinding.inflate(
                LayoutInflater
                    .from(parent.context), parent, false
            )
        )
    }

    override fun onBindViewHolder(holder: HomeViewHolder, position: Int) {
        val characterList = peopleList[position]
        holder.binding.characterName.text = characterList.characters
    }

    override fun getItemCount(): Int {
        return peopleList.size
    }

    @SuppressLint("NotifyDataSetChanged")
    fun setList(list: Characters) {
        peopleList = arrayListOf(list)
        notifyDataSetChanged()
    }

    }

Interface

interface StarWarsApi {

    @GET("people/")
    suspend fun getCharacters(): Response<Characters>

}

Body:
It appears that you have not used a LayoutManager in your recycler view.

Before adding adapter, or on onCreateView, call:

recyclerView.layoutManager=LinearLayoutManager(requireContext())
recyclerView.adapter = adapter

Also, try to log the list before setting it:

Log.i("HomeFragment", "list log: $it")
adapter.setList(it)


问:
How to configure signalR's connection string in the Function using the managed identity?
I have a Function App running on .net6 using the isolated worker. I have built the negociate Function which allows to return to an authenticated client the SignalR endpoint.

```<code>[Function("negotiate")]
public Task<HttpResponseData> NegotiateAsync
(
    [HttpTrigger(AuthorizationLevel.Anonymous, Verbs.Post)]
    HttpRequestData httpRequestData,
    [SignalRConnectionInfoInput(HubName = "updates", UserId = "{headers.x-ms-client-principal-id}")]
    ConnectionInfo connectionInfo
)
{
    [...]

    HttpResponseData httpResponseData = httpRequestData.CreateResponse(HttpStatusCode.OK);
    httpResponseData.Headers.Add("Content-Type", "application/json");

    string originalConnectionInfo = JsonSerializer.Serialize(connectionInfo);
    await httpResponseData.WriteStringAsync(originalConnectionInfo);

    return httpResponseData;
}
</code>```

I have activated the System-Assigned identity on the SignalR instance:

I have set the role of SignalR App Server to the Function App (and its staging slot):

Now, I have to specify the endpoint of SignalR to the Function App. Usually, it is set up in the configuration using either the default AzureSignalRConnectionString or a custom one. Following the procedure when accessing storage accounts using Managed Identity, I simply the URL in the AzureSignalRConnectionString setting such as https://<signalr-name>.service.signalr.net.

However I end up with the following error:

Exception while executing function: Functions.negotiate <--- Connection string missing required properties endpoint and accesskey. (Parameter 'connectionString')

Question

How do I configure signalR's connection string in the Function using the managed identity?

答: To clarify, the support for Azure Identity in SignalR extension for isolated workers has not been released yet. For in-process model, SignalR trigger binding supports Azure Identity since 1.7.0-beta.1.</p>

Body:
I have a Function App running on .net6 using the isolated worker. I have built the negociate Function which allows to return to an authenticated client the SignalR endpoint.

[Function("negotiate")]
public Task<HttpResponseData> NegotiateAsync
(
    [HttpTrigger(AuthorizationLevel.Anonymous, Verbs.Post)]
    HttpRequestData httpRequestData,
    [SignalRConnectionInfoInput(HubName = "updates", UserId = "{headers.x-ms-client-principal-id}")]
    ConnectionInfo connectionInfo
)
{
    [...]

    HttpResponseData httpResponseData = httpRequestData.CreateResponse(HttpStatusCode.OK);
    httpResponseData.Headers.Add("Content-Type", "application/json");

    string originalConnectionInfo = JsonSerializer.Serialize(connectionInfo);
    await httpResponseData.WriteStringAsync(originalConnectionInfo);

    return httpResponseData;
}

I have activated the System-Assigned identity on the SignalR instance:

I have set the role of SignalR App Server to the Function App (and its staging slot):

Now, I have to specify the endpoint of SignalR to the Function App. Usually, it is set up in the configuration using either the default AzureSignalRConnectionString or a custom one. Following the procedure when accessing storage accounts using Managed Identity, I simply the URL in the AzureSignalRConnectionString setting such as https://<signalr-name>.service.signalr.net.

However I end up with the following error:

Exception while executing function: Functions.negotiate <--- Connection string missing required properties endpoint and accesskey. (Parameter 'connectionString')

Question

How do I configure signalR's connection string in the Function using the managed identity?


问:
Flutter - change TextFormField background when in active mode (Typing)
I want to achieve this.

While a text form field is inactive, its background, fill color will be grey. But when I am typing or it is in active mode, its background color will be white.

How to achieve this behavior?

答:
After going through some tests, I have finalized the correct answer. The above answer is good. The first one has a problem. Focus Node variable must be inside the state class so that it can preserve its state.

```<code>class _GlobalTextFormFieldState extends State<GlobalTextFormField> {
  late FocusNode focusNode;

  @override
  void initState() {
    focusNode = FocusNode();
    focusNode.addListener(() {
      setState(() {});
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      focusNode: focusNode,
    );
  }
}
</code>```

Body:
After going through some tests, I have finalized the correct answer. The above answer is good. The first one has a problem. Focus Node variable must be inside the state class so that it can preserve its state.

class _GlobalTextFormFieldState extends State<GlobalTextFormField> {
  late FocusNode focusNode;

  @override
  void initState() {
    focusNode = FocusNode();
    focusNode.addListener(() {
      setState(() {});
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      focusNode: focusNode,
    );
  }
}


问:
Store authentication token in iPhone application
I want to store authentication token, that i received from log-in response.

It is right to use for this NSUserDefaults? Or I must use KeyChainWrapper?

What is the best way store authentication token?

答: It is safer to store them in the Keychain (btw. https://github.com/ldandersen/scifihifi-iphone/tree/master/security is awesome).</p>


问:
Set public-read ACL for AWS S3 data upload via iOS Amplify
I've been attempting to upload images to an existing resource in S3, the images need to be publicly viewable and our website expects that the app sets the ACL to public-read on the file.

I have been unable to find a solution using the Amplify SDK that gets this done.

Currently even using the "guest" access level my images are not viewable at their S3 URLS.

Does anyone know how to set the "public-read" ACL during upload using the iOS Amplify SDK?

https://docs.amplify.aws/lib/storage/configureaccess/q/platform/ios/

答: Have you tried using "protected"?</p>

Body: Have you tried using "protected"?


问:
Finding x numbers in list greater than 0 with potential duplicates and assigning index of original list
I have lists of floats which will have some zeros in it. Eg.

```<code>numbers = [1.2, 0.0, 0.0, 1.2, 2.0, 2.5, 17, 1.3, 1.8, 1.3, 1.2]
</code>```

I am trying to assign these values to n numbers (assuming it will be the first 5) for the lowest 5 values that are greater than 0.

I can get the first by using:

```<code>first = min(o for o in numbers if o > 0)
</code>```

But as there are duplicates in the smallest value (1.2), I cannot easily assign second, third, fourth and fifth.

I need to assign these and allow me to keep the index of their values in the original list and assign these too. Eg.

```<code>first_pos = numbers.index(first)
</code>```

I cannot use the above for second as it will assign it the first index value.

Is there any efficient way using a for loop or list comprehension or even a small function to assigning the other numbers so that:

```<code>second = 1.2
second_pos = 4
third = 1.2
third_pos = 10
fourth = 1.3
fourth_pos = 7
fifth = 1.3
fifth_pos = 9
</code>```

I cannot do this with any list comprehension I know of for second as it will not pick up a duplicate. Eg.:

```<code>sec = min(o for o in numbers if o > first)
</code>```

The lists vary in length of values (at least 5, though) and may or may not have duplicates and zeros but many will.

答:
IIUC, one way using sorted with enumerate:

```<code>sorted(((n, i) for n, i in enumerate(numbers) if i > 0), key=lambda x: x[1])[:5]
</code>```

Output of (index, value) pairs of first 5 smallest values:

```<code>[(0, 1.2), (3, 1.2), (10, 1.2), (7, 1.3), (9, 1.3)]
</code>```

Body:
I have lists of floats which will have some zeros in it. Eg.

numbers = [1.2, 0.0, 0.0, 1.2, 2.0, 2.5, 17, 1.3, 1.8, 1.3, 1.2]

I am trying to assign these values to n numbers (assuming it will be the first 5) for the lowest 5 values that are greater than 0.

I can get the first by using:

first = min(o for o in numbers if o > 0)

But as there are duplicates in the smallest value (1.2), I cannot easily assign second, third, fourth and fifth.

I need to assign these and allow me to keep the index of their values in the original list and assign these too. Eg.

first_pos = numbers.index(first)

I cannot use the above for second as it will assign it the first index value.

Is there any efficient way using a for loop or list comprehension or even a small function to assigning the other numbers so that:

second = 1.2
second_pos = 4
third = 1.2
third_pos = 10
fourth = 1.3
fourth_pos = 7
fifth = 1.3
fifth_pos = 9

I cannot do this with any list comprehension I know of for second as it will not pick up a duplicate. Eg.:

sec = min(o for o in numbers if o > first)

The lists vary in length of values (at least 5, though) and may or may not have duplicates and zeros but many will.

Body:
IIUC, one way using sorted with enumerate:

sorted(((n, i) for n, i in enumerate(numbers) if i > 0), key=lambda x: x[1])[:5]

Output of (index, value) pairs of first 5 smallest values:

[(0, 1.2), (3, 1.2), (10, 1.2), (7, 1.3), (9, 1.3)]


问:
Python int too large to convert to C long(TensorFlow importing)
My Code:

```<code>import numpy as np
import tensorflow_datasets as tfds ##The line gives error.
import tensorflow as tf
import matplotlib.pyplot as plt

tfds.disable_progress_bar()
</code>```

Output

```<code>OverflowError: Python int too large to convert to C long
</code>```

Already uninstalled and re-installed.

Any suggestions would be appreciated

答:
This issue is fixed in tensorflow-datasets 4.5.2.

import tensorflow_datasets as tfds

Body:
My Code:

import numpy as np
import tensorflow_datasets as tfds ##The line gives error.
import tensorflow as tf
import matplotlib.pyplot as plt

tfds.disable_progress_bar()

Output

OverflowError: Python int too large to convert to C long

Already uninstalled and re-installed.

Any suggestions would be appreciated


问:
Specify reticulate python path in RETICULATE_PYTHON environment variable
Whenever I use reticulate in RStudio, the default REPL is using python2.7, but I want to use python3 per default.
I have added the python path to python3 to my .bashrc in the environment variable RETICULATE_PYTHON and when I use R and reticulate from the command line, Sys.getenv('RETICUALTE_PYTHON') returns /usr/bin/python3. If open a REPL in the command line using, I get the correct path. If I do the same in RStudio, I get an empty string.

R
```

```Sys.getenv('RETICULATE_PYTHON')
```

<p>Return in R (from command line): </p>

<p><code>[1] "/usr/bin/python3"</code></p>

<p>in RStudio:</p>

<p><code>[1] ""</code></p>

<p>In the RStudio Terminal the output is correct:</p>

<pre class="lang-sh prettyprint-override"><code>echo $RETICULATE_PYTHON
/usr/bin/python3
</code>```

Also, when I start R from the command line, py_config() is this:

```<code>> library(reticulate)
> py_config()
python:         /usr/bin/python3
libpython:      /usr/lib/python3.6/config-3.6m-x86_64-linux-gnu/libpython3.6.so
pythonhome:     /usr:/usr
version:        3.6.7 (default, Oct 22 2018, 11:32:17)  [GCC 8.2.0]
numpy:          /usr/lib/python3/dist-packages/numpy
numpy_version:  1.14.5

NOTE: Python version was forced by RETICULATE_PYTHON
</code>```

But in RStudio it is this:

```<code>> library(reticulate)
> py_config()
python:         /usr/bin/python
libpython:      /usr/lib/python2.7/config-x86_64-linux-gnu/libpython2.7.so
pythonhome:     /usr:/usr
version:        2.7.15+ (default, Oct  2 2018, 22:12:08)  [GCC 8.2.0]
numpy:          /usr/lib/python2.7/dist-packages/numpy
numpy_version:  1.14.5

python versions found:
 /usr/bin/python
 /usr/bin/python3
</code>```

Restarting RStudio did not help. Any suggestions on how to make RStudio use the correct python binary as well?

答:
The solution I used was simply to set the default Python interpreter for RStudio  (2021.09.1 for Windows) using Tools > Global Options to the path of the interpreter I wanted RStudio to use.

In my case, I set it too use "C:/tools/Anaconda3/envs/dev/python.exe".

I assume the same solution would work for Linux too.

Body:
Whenever I use reticulate in RStudio, the default REPL is using python2.7, but I want to use python3 per default.
I have added the python path to python3 to my .bashrc in the environment variable RETICULATE_PYTHON and when I use R and reticulate from the command line, Sys.getenv('RETICUALTE_PYTHON') returns /usr/bin/python3. If open a REPL in the command line using, I get the correct path. If I do the same in RStudio, I get an empty string.

R

Sys.getenv('RETICULATE_PYTHON')

Return in R (from command line):

[1] "/usr/bin/python3"

in RStudio:

[1] ""

In the RStudio Terminal the output is correct:

echo $RETICULATE_PYTHON
/usr/bin/python3

Also, when I start R from the command line, py_config() is this:

> library(reticulate)
> py_config()
python:         /usr/bin/python3
libpython:      /usr/lib/python3.6/config-3.6m-x86_64-linux-gnu/libpython3.6.so
pythonhome:     /usr:/usr
version:        3.6.7 (default, Oct 22 2018, 11:32:17)  [GCC 8.2.0]
numpy:          /usr/lib/python3/dist-packages/numpy
numpy_version:  1.14.5

NOTE: Python version was forced by RETICULATE_PYTHON

But in RStudio it is this:

> library(reticulate)
> py_config()
python:         /usr/bin/python
libpython:      /usr/lib/python2.7/config-x86_64-linux-gnu/libpython2.7.so
pythonhome:     /usr:/usr
version:        2.7.15+ (default, Oct  2 2018, 22:12:08)  [GCC 8.2.0]
numpy:          /usr/lib/python2.7/dist-packages/numpy
numpy_version:  1.14.5

python versions found:
 /usr/bin/python
 /usr/bin/python3

Restarting RStudio did not help. Any suggestions on how to make RStudio use the correct python binary as well?


问:
Ajax request giving id NULL
Good Morning...I am trying to update the data in table using ajax, while passing the data to controller using id, ID preview is showing NULL and so not able to update the data in Table.
I am trying to add new data in one table and at same time update data in another table using same ajax...
Ajax -

```<code>$.ajaxSetup({

    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }

});

$(document).on('click', '#footer_addnewinspectiondata_button', function() {

    $.ajax({

        type: 'put',
        url: '/addbuffaloinspectiondata',
        dataType: 'json',
        data: {
            'buffaloID': $('#buffaloID').val(),
            'inspectiondate': $('#inspectiondate').val(),
            'pregnantstatus': $('#pregnantstatus').val(),
            'healthstatus': $('#healthstatus').val(),
            'weight': $('#weight').val(),
            'height': $('#height').val(),
            'weeklytika': $('#weeklytika').val(),
            'monthlytika': $('#monthlytika').val(),
            'inspection': $('#inspection').val(),
            'inspectionby': $('#inspectionby').val(),
            'inspectionnote': $('#inspectionnote').val(),

        },
        success: function(data) {

            console.log(data);

        },
        error: function(e) {
            console.log(e);
        }
    });
});
</code>```

Web.php File

```<code>Route:: put('/addbuffaloinspectiondata',
       [viewbuffaloController::class,'addbuffaloinspectiondata'])->name('addbuffaloinspectiondata');
</code>```

Controller File -

```<code>public function addbuffaloinspectiondata(Request $req)
{
    // add new data in buffaloinspection table for Buffalo ID

    $newdata = new buffaloinspectiondata;

    $newdata->buffaloID            = $req->buffaloID;
    $newdata->inspectiondate       = $req->inspectiondate;

    $newdata->weight               = $req->weight;
    $newdata->height               = $req->height;
    $newdata->pregnant             = $req->pregnantstatus;

    $newdata->health               = $req->healthstatus;
    $newdata->weeklytika           = $req->weeklytika;
    $newdata->monthlytika          = $req->monthlytika;

    $newdata->inspection           = $req->inspection;
    $newdata->inspectionby         = $req->inspectionby;
    $newdata->inspectionnote       = $req->inspectionnote;

    // update data in BuffaloDATA Table

    $updatedata = buffalodata::find($req->buffaloID);

        $updatedata->weight             = $req->get('weight');
        $updatedata->height             = $req->get('height');

        $newdata->save ();
        $updatedata->save ();

        return response()->json([$newdata,$updatedata],200);
}
</code>```

Did i miss something or doing wrong in code... Thanks in Advance.

答:
The Reason that you are getting Id NULL is dd($updatedata); it will stop execution after that
remove it

and change your return like this

return response()->json([$newdata,$updatedata],200);

your controller

```<code>public function addbuffaloinspectiondata(Request $req)
{
    // add new data in buffaloinspection table for Buffalo ID

    $newdata = new buffaloinspectiondata();

    $newdata->buffaloID            = $req->buffaloID;
    $newdata->inspectiondate       = $req->inspectiondate;

    $newdata->weight               = $req->weight;
    $newdata->height               = $req->height;
    $newdata->pregnant             = $req->pregnantstatus;

    $newdata->health               = $req->healthstatus;
    $newdata->weeklytika           = $req->weeklytika;
    $newdata->monthlytika          = $req->monthlytika;

    $newdata->inspection           = $req->inspection;
    $newdata->inspectionby         = $req->inspectionby;
    $newdata->inspectionnote       = $req->inspectionnote;
    $newdata->save();

    // update data in BuffaloDATA Table

    $updatedata = buffalodata::find($req->buffaloID);
    $updatedata->weight  = $req->weight;
    $updatedata->height  = $req->height;
    $updatedata->update();

        return response()->json([$newdata,$updatedata],200);
}
</code>```

Title: Ajax request giving id NULL

Body:
Good Morning...I am trying to update the data in table using ajax, while passing the data to controller using id, ID preview is showing NULL and so not able to update the data in Table.
I am trying to add new data in one table and at same time update data in another table using same ajax...
Ajax -

$.ajaxSetup({

    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }

});

$(document).on('click', '#footer_addnewinspectiondata_button', function() {

    $.ajax({

        type: 'put',
        url: '/addbuffaloinspectiondata',
        dataType: 'json',
        data: {
            'buffaloID': $('#buffaloID').val(),
            'inspectiondate': $('#inspectiondate').val(),
            'pregnantstatus': $('#pregnantstatus').val(),
            'healthstatus': $('#healthstatus').val(),
            'weight': $('#weight').val(),
            'height': $('#height').val(),
            'weeklytika': $('#weeklytika').val(),
            'monthlytika': $('#monthlytika').val(),
            'inspection': $('#inspection').val(),
            'inspectionby': $('#inspectionby').val(),
            'inspectionnote': $('#inspectionnote').val(),

        },
        success: function(data) {

            console.log(data);

        },
        error: function(e) {
            console.log(e);
        }
    });
});

Web.php File

Route:: put('/addbuffaloinspectiondata',
       [viewbuffaloController::class,'addbuffaloinspectiondata'])->name('addbuffaloinspectiondata');

Controller File -

public function addbuffaloinspectiondata(Request $req)
{
    // add new data in buffaloinspection table for Buffalo ID

    $newdata = new buffaloinspectiondata;

    $newdata->buffaloID            = $req->buffaloID;
    $newdata->inspectiondate       = $req->inspectiondate;

    $newdata->weight               = $req->weight;
    $newdata->height               = $req->height;
    $newdata->pregnant             = $req->pregnantstatus;

    $newdata->health               = $req->healthstatus;
    $newdata->weeklytika           = $req->weeklytika;
    $newdata->monthlytika          = $req->monthlytika;

    $newdata->inspection           = $req->inspection;
    $newdata->inspectionby         = $req->inspectionby;
    $newdata->inspectionnote       = $req->inspectionnote;

    // update data in BuffaloDATA Table

    $updatedata = buffalodata::find($req->buffaloID);

        $updatedata->weight             = $req->get('weight');
        $updatedata->height             = $req->get('height');

        $newdata->save ();
        $updatedata->save ();

        return response()->json([$newdata,$updatedata],200);
}

Did i miss something or doing wrong in code... Thanks in Advance.

Body:
The Reason that you are getting Id NULL is dd($updatedata); it will stop execution after that
remove it

and change your return like this

return response()->json([$newdata,$updatedata],200);

your controller

public function addbuffaloinspectiondata(Request $req)
{
    // add new data in buffaloinspection table for Buffalo ID

    $newdata = new buffaloinspectiondata();

    $newdata->buffaloID            = $req->buffaloID;
    $newdata->inspectiondate       = $req->inspectiondate;

    $newdata->weight               = $req->weight;
    $newdata->height               = $req->height;
    $newdata->pregnant             = $req->pregnantstatus;

    $newdata->health               = $req->healthstatus;
    $newdata->weeklytika           = $req->weeklytika;
    $newdata->monthlytika          = $req->monthlytika;

    $newdata->inspection           = $req->inspection;
    $newdata->inspectionby         = $req->inspectionby;
    $newdata->inspectionnote       = $req->inspectionnote;
    $newdata->save();

    // update data in BuffaloDATA Table

    $updatedata = buffalodata::find($req->buffaloID);
    $updatedata->weight  = $req->weight;
    $updatedata->height  = $req->height;
    $updatedata->update();

        return response()->json([$newdata,$updatedata],200);
}


问:
Could not resolve dependency: google-maps-react
It is my first time to clone react project from github

i did:

```<code>$ git clone <link>
</code>```

after that:

```<code>npm install
</code>```

but i faced an error with google-maps-react

```<code>$ npm install --save google-maps-react
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: @iso/here@4.0.0
npm ERR! Found: react@17.0.2
npm ERR! node_modules/react
npm ERR!   react@"^17.0.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"~0.14.8 || ^15.0.0 || ^16.0.0" from google-maps-react@2.0.6
npm ERR! node_modules/google-maps-react
npm ERR!   google-maps-react@"^2.0.6" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\user\AppData\Local\npm-cache\eresolve-report.txt for a full report.
</code>```

i tried:

```<code>$ npm cache clean --force
$ npm install -g npm
</code>```

,:

```<code>$npm config set legacy-peer-deps true
</code>```

,:

```<code>npm install  --force
</code>```

,:

```<code>npm install --save --legacy-peer-deps
</code>```

,:

```<code>rm -rf node_modules
</code>```

and more ..

node js version:

```<code>16.13.2
</code>```

react version:

```<code>17.0.2
</code>```

npm version:

```<code>8.4.1
</code>```

nothing seem to work

am i missing something?

答:
Solution:

The app is using "yarn"
I'm able now to run the app after installing "yarn add node-sass"

Body:
It is my first time to clone react project from github

i did:

$ git clone <link>

after that:

npm install

but i faced an error with google-maps-react

$ npm install --save google-maps-react
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: @iso/here@4.0.0
npm ERR! Found: react@17.0.2
npm ERR! node_modules/react
npm ERR!   react@"^17.0.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"~0.14.8 || ^15.0.0 || ^16.0.0" from google-maps-react@2.0.6
npm ERR! node_modules/google-maps-react
npm ERR!   google-maps-react@"^2.0.6" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\user\AppData\Local\npm-cache\eresolve-report.txt for a full report.

i tried:

$ npm cache clean --force
$ npm install -g npm

,:

$npm config set legacy-peer-deps true

,:

npm install  --force

,:

npm install --save --legacy-peer-deps

,:

rm -rf node_modules

and more ..

node js version:

16.13.2

react version:

17.0.2

npm version:

8.4.1

nothing seem to work

am i missing something?