问:
Convert pandas dataframe to NumPy array
How do I convert a pandas dataframe into a NumPy array?

DataFrame:

```<code>import numpy as np
import pandas as pd

index = [1, 2, 3, 4, 5, 6, 7]
a = [np.nan, np.nan, np.nan, 0.1, 0.1, 0.1, 0.1]
b = [0.2, np.nan, 0.2, 0.2, 0.2, np.nan, np.nan]
c = [np.nan, 0.5, 0.5, np.nan, 0.5, 0.5, np.nan]
df = pd.DataFrame({'A': a, 'B': b, 'C': c}, index=index)
df = df.rename_axis('ID')
</code>```

gives

```<code>label   A    B    C
ID
1   NaN  0.2  NaN
2   NaN  NaN  0.5
3   NaN  0.2  0.5
4   0.1  0.2  NaN
5   0.1  0.2  0.5
6   0.1  NaN  0.5
7   0.1  NaN  NaN
</code>```

I would like to convert this to a NumPy array, like so:

```<code>array([[ nan,  0.2,  nan],
       [ nan,  nan,  0.5],
       [ nan,  0.2,  0.5],
       [ 0.1,  0.2,  nan],
       [ 0.1,  0.2,  0.5],
       [ 0.1,  nan,  0.5],
       [ 0.1,  nan,  nan]])
</code>```

Also, is it possible to preserve the dtypes, like this?

```<code>array([[ 1, nan,  0.2,  nan],
       [ 2, nan,  nan,  0.5],
       [ 3, nan,  0.2,  0.5],
       [ 4, 0.1,  0.2,  nan],
       [ 5, 0.1,  0.2,  0.5],
       [ 6, 0.1,  nan,  0.5],
       [ 7, 0.1,  nan,  nan]],
     dtype=[('ID', '<i4'), ('A', '<f8'), ('B', '<f8'), ('B', '<f8')])
</code>```

答:
Try this:</p>

```<code>a = numpy.asarray(df)
</code>```

Title: Convert pandas dataframe to NumPy array

Body:
How do I convert a pandas dataframe into a NumPy array?

DataFrame:

import numpy as np
import pandas as pd

index = [1, 2, 3, 4, 5, 6, 7]
a = [np.nan, np.nan, np.nan, 0.1, 0.1, 0.1, 0.1]
b = [0.2, np.nan, 0.2, 0.2, 0.2, np.nan, np.nan]
c = [np.nan, 0.5, 0.5, np.nan, 0.5, 0.5, np.nan]
df = pd.DataFrame({'A': a, 'B': b, 'C': c}, index=index)
df = df.rename_axis('ID')

gives

label   A    B    C
ID
1   NaN  0.2  NaN
2   NaN  NaN  0.5
3   NaN  0.2  0.5
4   0.1  0.2  NaN
5   0.1  0.2  0.5
6   0.1  NaN  0.5
7   0.1  NaN  NaN

I would like to convert this to a NumPy array, like so:

array([[ nan,  0.2,  nan],
       [ nan,  nan,  0.5],
       [ nan,  0.2,  0.5],
       [ 0.1,  0.2,  nan],
       [ 0.1,  0.2,  0.5],
       [ 0.1,  nan,  0.5],
       [ 0.1,  nan,  nan]])

Also, is it possible to preserve the dtypes, like this?

array([[ 1, nan,  0.2,  nan],
       [ 2, nan,  nan,  0.5],
       [ 3, nan,  0.2,  0.5],
       [ 4, 0.1,  0.2,  nan],
       [ 5, 0.1,  0.2,  0.5],
       [ 6, 0.1,  nan,  0.5],
       [ 7, 0.1,  nan,  nan]],
     dtype=[('ID', '<i4'), ('A', '<f8'), ('B', '<f8'), ('B', '<f8')])

Body:
Try this:

a = numpy.asarray(df)


来源: stackexchange

问:
Integrating weather information in iphone
Can anyone tell me the steps to integrate weather information into my iPhone App. I found some API's are there, but didn't found steps for this. Thanks in advance.</p>

答:
use google weather in php

see the link http://komunitasweb.com/2009/09/showing-the-weather-with-php-and-google-weather-api/

to iphone see old question in so :

https://stackoverflow.com/questions/1305127/free-weather-api

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
is there a function to create new variable based on one condition if any of my 27 columns have "Yes", then create 1, otherwise 0
Hi I got dataframe about 28 columns and each columns contains Yes, No or NA. I would like to create new variable, if any of the columns contains "Yes", then create 1, otherwise 0.

Your help much appreciated.

答:
We can create a new column by getting the rowSums of logical matrix (df1 == "Yes") and check if it is greater than 0

```<code>df1$newVar <- as.integer(rowSums(df1 == "Yes", na.rm = TRUE) > 0)
</code>```

Body:
We can create a new column by getting the rowSums of logical matrix (df1 == "Yes") and check if it is greater than 0

df1$newVar <- as.integer(rowSums(df1 == "Yes", na.rm = TRUE) > 0)


问:
What makes PdfStamper to remove images from pdf after cleanup() though it shouldn't?
Fist of all, I'm relatively new to java, as well to iText.

Shortly, I have a program which copies every 2 pages from big source pdf document and creates a new doc for each pair of pages. Additionally, the program removes some text information from the first page and protects new documents with owner password.

Here is my code. I use iText 5.5.13.

```<code>    //...
    final Rectangle RECT_TOP= new Rectangle(25f, 788f, 288f, 812.5f);
    final Rectangle RECT_BOT= new Rectangle(103.5f, 36.5f, 331f, 40f);
    //...

    PdfDocument document = new Document(reader.getPageSizeWithRotation(1));
    File tempFile = File.createTempFile("temp", ".pdf");
    PdfCopy writer = new PdfCopy(
            document, //PdfDocument
            new FileOutputStream(tempFile.getAbsolutePath()));

   document.open();

    writer.addPage( writer.getImportedPage(reader, i) );
    writer.addPage( writer.getImportedPage(reader, i + 1) );

    writer.freeReader(reader);
    writer.close();
    document.close();

    PdfReader tmpReader = new PdfReader(tempFile.getAbsolutePath());
    PdfStamper st = new PdfStamper(tmpReader, new FileOutputStream(outFile));
    List<PdfCleanUpLocation> locations = new ArrayList<PdfCleanUpLocation>();
    locations.add(new PdfCleanUpLocation(1, RECT_TOP, BaseColor.WHITE));
    locations.add(new PdfCleanUpLocation(1, RECT_BOT, BaseColor.WHITE));

    new PdfCleanUpProcessor(locations, st).cleanUp();
    st.setEncryption(
        "".getBytes(),
        OWNER_PASSWORD.getBytes(),
        PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING,
        PdfWriter.ENCRYPTION_AES_256 | PdfWriter.DO_NOT_ENCRYPT_METADATA);

    st.getWriter().freeReader(tmpReader);
    st.close();
    tmpReader.close();
    tempFile.delete();
</code>```

Source PDFs have a QR code as image on every page that I have to cleanUp(). Regions RECT_TOP and RECT_BOT don't include the image in any way.

I tested my code on two pdf with the same data inside. One of them was created with BullZip PDF printer (v PDF-1.5) and the other one with Foxit PDF printer (v PDF-1.7). The thing is the cleanUp method removes the QR code and data from rectangle  locations passed to PdfCleanUpProcessor in BullZip-created docs, but for foxit PDFs it works as it should and I really need it working with Bullzip docs.

I tried to manipulate the version of the temp pdf file and cleanUp() through redacted annotations, but with no use.

I want to understand where to look at and what to change (maybe somewhere in PdfCleanUpProcessor class?) to make it work properly.
Does anybody know why this happens?

UPD. I managed to create some PDFs similar to ones I need to process and I found out another interesting thing: Bullzip is able to create both "bad" and "good" files itself. I checked different printer settings, including permissions, but it is still hard to say what it depends on. Among the noticable differences there is only a slightly smaller file size and a little different page margins.

Anyway, here my test files

答:
You have indeed found a bug in the iText 5 PdfCleanUpProcessor: It drops all inline images which are not partially subject to redaction.

The bug in detail

The bug is located in the PdfCleanUpRenderListener method renderImage:

```<code>public void renderImage(ImageRenderInfo renderInfo) {
    List<Rectangle> areasToBeCleaned = getImageAreasToBeCleaned(renderInfo);

    if (areasToBeCleaned == null) {
        chunks.add(new PdfCleanUpContentChunk.Image(false, null));
    } else if ( areasToBeCleaned.size() > 0) {
        try {
            PdfImageObject pdfImage = renderInfo.getImage();
            byte[] imageBytes = processImage(pdfImage.getImageAsBytes(), areasToBeCleaned);

            if (renderInfo.getRef() == null && pdfImage != null) { // true => inline image
                PdfDictionary dict = pdfImage.getDictionary();
                PdfObject imageMask = dict.get(PdfName.IMAGEMASK);
                Image image = Image.getInstance(imageBytes);

                if (imageMask == null) {
                    imageMask = dict.get(PdfName.IM);
                }

                if (imageMask != null && imageMask.equals(PdfBoolean.PDFTRUE)) {
                    image.makeMask();
                }

                PdfContentByte canvas = getContext().getCanvas();
                canvas.addImage(image, 1, 0, 0, 1, 0, 0, true);
            } else if (pdfImage != null && imageBytes != pdfImage.getImageAsBytes()) {
                chunks.add(new PdfCleanUpContentChunk.Image(true, imageBytes));
            }
        } catch (UnsupportedPdfException pdfException) {
            chunks.add(new PdfCleanUpContentChunk.Image(false, null));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
</code>```

Inline images require special treatment here: For non-inlined images the actual instruction for drawing the image XObject is handled elsewhere and renderImage only needs to check whether the image has to be redacted and provide a redacted image version. For inline images, though, this method also has to add the image to the result content stream (unless it is completely redacted away).

As you can see there is a special treatment of inline images in the block for images partially covered by redaction areas (areasToBeCleaned.size() > 0) but none for images not covered by redaction areas (areasToBeCleaned != null and areasToBeCleaned.size() == 0).

How to fix it

You can fix this by adding a similar special treatment in a new else clause:

```<code>public void renderImage(ImageRenderInfo renderInfo) {
    List<Rectangle> areasToBeCleaned = getImageAreasToBeCleaned(renderInfo);

    if (areasToBeCleaned == null) {
        chunks.add(new PdfCleanUpContentChunk.Image(false, null));
    } else if ( areasToBeCleaned.size() > 0) {
        try {
            PdfImageObject pdfImage = renderInfo.getImage();
            byte[] imageBytes = processImage(pdfImage.getImageAsBytes(), areasToBeCleaned);

            if (renderInfo.getRef() == null && pdfImage != null) { // true => inline image
                PdfDictionary dict = pdfImage.getDictionary();
                PdfObject imageMask = dict.get(PdfName.IMAGEMASK);
                Image image = Image.getInstance(imageBytes);

                if (imageMask == null) {
                    imageMask = dict.get(PdfName.IM);
                }

                if (imageMask != null && imageMask.equals(PdfBoolean.PDFTRUE)) {
                    image.makeMask();
                }

                PdfContentByte canvas = getContext().getCanvas();
                canvas.addImage(image, 1, 0, 0, 1, 0, 0, true);
            } else if (pdfImage != null && imageBytes != pdfImage.getImageAsBytes()) {
                chunks.add(new PdfCleanUpContentChunk.Image(true, imageBytes));
            }
        } catch (UnsupportedPdfException pdfException) {
            chunks.add(new PdfCleanUpContentChunk.Image(false, null));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else { // add inline images not subject to redaction to the content
        try {
            PdfImageObject pdfImage = renderInfo.getImage();
            if (renderInfo.getRef() == null && pdfImage != null) { // true => inline image
                PdfDictionary dict = pdfImage.getDictionary();
                PdfObject imageMask = dict.get(PdfName.IMAGEMASK);
                Image image = Image.getInstance(pdfImage.getImageAsBytes());

                if (imageMask == null) {
                    imageMask = dict.get(PdfName.IM);
                }

                if (imageMask != null && imageMask.equals(PdfBoolean.PDFTRUE)) {
                    image.makeMask();
                }

                PdfContentByte canvas = getContext().getCanvas();
                canvas.addImage(image, 1, 0, 0, 1, 0, 0, true);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
</code>```

Example

To illustrate the issue and the effect of the fix, I created a simple PDF with five inline images:

```<code>Document document = new Document(new Rectangle(500, 500));
PdfWriter writer = PdfWriter.getInstance(document, baos);
document.open();
PdfContentByte canvas = writer.getDirectContent();
for (int i = 0; i < 5; i++) {
    canvas.addImage(image, 50, 0, 0, 50, i * 100 + 25, i * 100 + 25, true);
}
document.close();
</code>```

(RedactWithImageIssue helper method createPdfWithInlineImages)

looking like this:

Applying redaction like this

```<code>PdfReader reader = new PdfReader(pdf);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
List<com.itextpdf.text.pdf.pdfcleanup.PdfCleanUpLocation> locations = new ArrayList<>();
locations.add(new com.itextpdf.text.pdf.pdfcleanup.PdfCleanUpLocation(1, new Rectangle(150, 150, 350, 350), BaseColor.RED));
new PdfCleanUpProcessor(locations, stamper).cleanUp();
stamper.close();
</code>```

(RedactWithImageIssue test testRedactPdfWithInlineImages)

without and with the patch respectively results in

As you can see, originally only the partially redacted inline images remained but with the patch inline images completely outside the redaction area remain, too.

Body:
Fist of all, I'm relatively new to java, as well to iText.

Shortly, I have a program which copies every 2 pages from big source pdf document and creates a new doc for each pair of pages. Additionally, the program removes some text information from the first page and protects new documents with owner password.

Here is my code. I use iText 5.5.13.

    //...
    final Rectangle RECT_TOP= new Rectangle(25f, 788f, 288f, 812.5f);
    final Rectangle RECT_BOT= new Rectangle(103.5f, 36.5f, 331f, 40f);
    //...

    PdfDocument document = new Document(reader.getPageSizeWithRotation(1));
    File tempFile = File.createTempFile("temp", ".pdf");
    PdfCopy writer = new PdfCopy(
            document, //PdfDocument
            new FileOutputStream(tempFile.getAbsolutePath()));

   document.open();

    writer.addPage( writer.getImportedPage(reader, i) );
    writer.addPage( writer.getImportedPage(reader, i + 1) );

    writer.freeReader(reader);
    writer.close();
    document.close();

    PdfReader tmpReader = new PdfReader(tempFile.getAbsolutePath());
    PdfStamper st = new PdfStamper(tmpReader, new FileOutputStream(outFile));
    List<PdfCleanUpLocation> locations = new ArrayList<PdfCleanUpLocation>();
    locations.add(new PdfCleanUpLocation(1, RECT_TOP, BaseColor.WHITE));
    locations.add(new PdfCleanUpLocation(1, RECT_BOT, BaseColor.WHITE));

    new PdfCleanUpProcessor(locations, st).cleanUp();
    st.setEncryption(
        "".getBytes(),
        OWNER_PASSWORD.getBytes(),
        PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING,
        PdfWriter.ENCRYPTION_AES_256 | PdfWriter.DO_NOT_ENCRYPT_METADATA);

    st.getWriter().freeReader(tmpReader);
    st.close();
    tmpReader.close();
    tempFile.delete();

Source PDFs have a QR code as image on every page that I have to cleanUp(). Regions RECT_TOP and RECT_BOT don't include the image in any way.

I tested my code on two pdf with the same data inside. One of them was created with BullZip PDF printer (v PDF-1.5) and the other one with Foxit PDF printer (v PDF-1.7). The thing is the cleanUp method removes the QR code and data from rectangle  locations passed to PdfCleanUpProcessor in BullZip-created docs, but for foxit PDFs it works as it should and I really need it working with Bullzip docs.

I tried to manipulate the version of the temp pdf file and cleanUp() through redacted annotations, but with no use.

I want to understand where to look at and what to change (maybe somewhere in PdfCleanUpProcessor class?) to make it work properly.
Does anybody know why this happens?

UPD. I managed to create some PDFs similar to ones I need to process and I found out another interesting thing: Bullzip is able to create both "bad" and "good" files itself. I checked different printer settings, including permissions, but it is still hard to say what it depends on. Among the noticable differences there is only a slightly smaller file size and a little different page margins.

Anyway, here my test files

Body:
You have indeed found a bug in the iText 5 PdfCleanUpProcessor: It drops all inline images which are not partially subject to redaction.

The bug in detail

The bug is located in the PdfCleanUpRenderListener method renderImage:

public void renderImage(ImageRenderInfo renderInfo) {
    List<Rectangle> areasToBeCleaned = getImageAreasToBeCleaned(renderInfo);

    if (areasToBeCleaned == null) {
        chunks.add(new PdfCleanUpContentChunk.Image(false, null));
    } else if ( areasToBeCleaned.size() > 0) {
        try {
            PdfImageObject pdfImage = renderInfo.getImage();
            byte[] imageBytes = processImage(pdfImage.getImageAsBytes(), areasToBeCleaned);

            if (renderInfo.getRef() == null && pdfImage != null) { // true => inline image
                PdfDictionary dict = pdfImage.getDictionary();
                PdfObject imageMask = dict.get(PdfName.IMAGEMASK);
                Image image = Image.getInstance(imageBytes);

                if (imageMask == null) {
                    imageMask = dict.get(PdfName.IM);
                }

                if (imageMask != null && imageMask.equals(PdfBoolean.PDFTRUE)) {
                    image.makeMask();
                }

                PdfContentByte canvas = getContext().getCanvas();
                canvas.addImage(image, 1, 0, 0, 1, 0, 0, true);
            } else if (pdfImage != null && imageBytes != pdfImage.getImageAsBytes()) {
                chunks.add(new PdfCleanUpContentChunk.Image(true, imageBytes));
            }
        } catch (UnsupportedPdfException pdfException) {
            chunks.add(new PdfCleanUpContentChunk.Image(false, null));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

Inline images require special treatment here: For non-inlined images the actual instruction for drawing the image XObject is handled elsewhere and renderImage only needs to check whether the image has to be redacted and provide a redacted image version. For inline images, though, this method also has to add the image to the result content stream (unless it is completely redacted away).

As you can see there is a special treatment of inline images in the block for images partially covered by redaction areas (areasToBeCleaned.size() > 0) but none for images not covered by redaction areas (areasToBeCleaned != null and areasToBeCleaned.size() == 0).

How to fix it

You can fix this by adding a similar special treatment in a new else clause:

public void renderImage(ImageRenderInfo renderInfo) {
    List<Rectangle> areasToBeCleaned = getImageAreasToBeCleaned(renderInfo);

    if (areasToBeCleaned == null) {
        chunks.add(new PdfCleanUpContentChunk.Image(false, null));
    } else if ( areasToBeCleaned.size() > 0) {
        try {
            PdfImageObject pdfImage = renderInfo.getImage();
            byte[] imageBytes = processImage(pdfImage.getImageAsBytes(), areasToBeCleaned);

            if (renderInfo.getRef() == null && pdfImage != null) { // true => inline image
                PdfDictionary dict = pdfImage.getDictionary();
                PdfObject imageMask = dict.get(PdfName.IMAGEMASK);
                Image image = Image.getInstance(imageBytes);

                if (imageMask == null) {
                    imageMask = dict.get(PdfName.IM);
                }

                if (imageMask != null && imageMask.equals(PdfBoolean.PDFTRUE)) {
                    image.makeMask();
                }

                PdfContentByte canvas = getContext().getCanvas();
                canvas.addImage(image, 1, 0, 0, 1, 0, 0, true);
            } else if (pdfImage != null && imageBytes != pdfImage.getImageAsBytes()) {
                chunks.add(new PdfCleanUpContentChunk.Image(true, imageBytes));
            }
        } catch (UnsupportedPdfException pdfException) {
            chunks.add(new PdfCleanUpContentChunk.Image(false, null));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else { // add inline images not subject to redaction to the content
        try {
            PdfImageObject pdfImage = renderInfo.getImage();
            if (renderInfo.getRef() == null && pdfImage != null) { // true => inline image
                PdfDictionary dict = pdfImage.getDictionary();
                PdfObject imageMask = dict.get(PdfName.IMAGEMASK);
                Image image = Image.getInstance(pdfImage.getImageAsBytes());

                if (imageMask == null) {
                    imageMask = dict.get(PdfName.IM);
                }

                if (imageMask != null && imageMask.equals(PdfBoolean.PDFTRUE)) {
                    image.makeMask();
                }

                PdfContentByte canvas = getContext().getCanvas();
                canvas.addImage(image, 1, 0, 0, 1, 0, 0, true);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

Example

To illustrate the issue and the effect of the fix, I created a simple PDF with five inline images:

Document document = new Document(new Rectangle(500, 500));
PdfWriter writer = PdfWriter.getInstance(document, baos);
document.open();
PdfContentByte canvas = writer.getDirectContent();
for (int i = 0; i < 5; i++) {
    canvas.addImage(image, 50, 0, 0, 50, i * 100 + 25, i * 100 + 25, true);
}
document.close();

(RedactWithImageIssue helper method createPdfWithInlineImages)

looking like this:

Applying redaction like this

PdfReader reader = new PdfReader(pdf);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
List<com.itextpdf.text.pdf.pdfcleanup.PdfCleanUpLocation> locations = new ArrayList<>();
locations.add(new com.itextpdf.text.pdf.pdfcleanup.PdfCleanUpLocation(1, new Rectangle(150, 150, 350, 350), BaseColor.RED));
new PdfCleanUpProcessor(locations, stamper).cleanUp();
stamper.close();

(RedactWithImageIssue test testRedactPdfWithInlineImages)

without and with the patch respectively results in

As you can see, originally only the partially redacted inline images remained but with the patch inline images completely outside the redaction area remain, too.


问:
Azure - trigger notification from service bus queue
I am trying to create the following process:

An IoT device sends a message to the IoT Hub which in turn, if the message contains some value, triggers a notification to all of the registered android devices through the Notification Hub.

At first, I do not care what is the content of the message itself, and I just want to trigger a notification on every incoming message.

I have managed to set up the IoT device and connect it to the IoT hub.
I have also managed to set up the Notification Hub, and connect it with the android app, in a way that when I use the "test send" in the Notification Hub, a notification is received on the android device.

In order to connect both ends (IoT Hub and Notification Hub), I tried to follow the following tutorial: https://www.developer.com/ws/android/sending-notifications-to-mobile-apps-from-azure-function-apps.html

In addition, I have added routing from the IoT Hub to the appropriate queue in the service bus.

Now, whenever the IoT device sends a message to the hub, I can see that the queue receives a message. However, I can't seem to use the queue to trigger the notification.

The ServiceHubQueueTrigger function I have added has the following error in the portal:

```<code>Error:

Function (ServiceBusQueueTrigger1) Error: The binding type(s) 'notificationHub' are not registered. Please ensure the type is correct and the binding extension is installed.
</code>```

Its function.json looks like this:

```<code>{
  "bindings": [
    {
      "name": "myQueueItem",
      "type": "serviceBusTrigger",
      "direction": "in",
      "queueName": "notificationqueue",
      "connection": "ServiceBusConnection",
      "accessRights": "manage"
    },
    {
      "name": "notification",
      "type": "notificationHub",
      "hubName": "<hub-name>",
      "connection": "NotificationConnString",
      "platform": "gcm",
      "tagExpression": "",
      "direction": "out"
    }
  ]
}
</code>```

where hub-name is the name of the Notification Hub.

How can I trigger the notifications to the android devices through the queue?
Is there a way to trigger them directly from an IoT Hub Event Trigger function?

Thanks!

答:
Yes, you can trigger an Azure Function directly from incoming IoT Hub events. See one of my samples here: https://github.com/sebader/iotedge-end2end/blob/master/CloudFunctions/IotHubMessageProcessor.cs

```<code>public static void Run([IoTHubTrigger("messages/events", Connection = "iothubevents_cs", ConsumerGroup = "receiverfunction")]EventData message, ILogger log)
{
  log.LogInformation($"IotHubMessageProcessor received a message: {Encoding.UTF8.GetString(message.Body.Array)}");
}
</code>```

IoT Hub Function Binding: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-event-iot

Body:
I am trying to create the following process:

An IoT device sends a message to the IoT Hub which in turn, if the message contains some value, triggers a notification to all of the registered android devices through the Notification Hub.

At first, I do not care what is the content of the message itself, and I just want to trigger a notification on every incoming message.

I have managed to set up the IoT device and connect it to the IoT hub.
I have also managed to set up the Notification Hub, and connect it with the android app, in a way that when I use the "test send" in the Notification Hub, a notification is received on the android device.

In order to connect both ends (IoT Hub and Notification Hub), I tried to follow the following tutorial: https://www.developer.com/ws/android/sending-notifications-to-mobile-apps-from-azure-function-apps.html

In addition, I have added routing from the IoT Hub to the appropriate queue in the service bus.

Now, whenever the IoT device sends a message to the hub, I can see that the queue receives a message. However, I can't seem to use the queue to trigger the notification.

The ServiceHubQueueTrigger function I have added has the following error in the portal:

Error:

Function (ServiceBusQueueTrigger1) Error: The binding type(s) 'notificationHub' are not registered. Please ensure the type is correct and the binding extension is installed.

Its function.json looks like this:

{
  "bindings": [
    {
      "name": "myQueueItem",
      "type": "serviceBusTrigger",
      "direction": "in",
      "queueName": "notificationqueue",
      "connection": "ServiceBusConnection",
      "accessRights": "manage"
    },
    {
      "name": "notification",
      "type": "notificationHub",
      "hubName": "<hub-name>",
      "connection": "NotificationConnString",
      "platform": "gcm",
      "tagExpression": "",
      "direction": "out"
    }
  ]
}

where hub-name is the name of the Notification Hub.

How can I trigger the notifications to the android devices through the queue?
Is there a way to trigger them directly from an IoT Hub Event Trigger function?

Thanks!

Body:
Yes, you can trigger an Azure Function directly from incoming IoT Hub events. See one of my samples here: https://github.com/sebader/iotedge-end2end/blob/master/CloudFunctions/IotHubMessageProcessor.cs

public static void Run([IoTHubTrigger("messages/events", Connection = "iothubevents_cs", ConsumerGroup = "receiverfunction")]EventData message, ILogger log)
{
  log.LogInformation($"IotHubMessageProcessor received a message: {Encoding.UTF8.GetString(message.Body.Array)}");
}

IoT Hub Function Binding: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-event-iot


问:
Why is the assignment in a function ignored?
Consider following code:

```<code>zzz=2

function f()
{
    zzz=4
}

$(f)
echo $zzz
</code>```

Why is the assignment (zzz=4) ignored? I thought I knew what $( ) does - it takes everything written to stdout and pastes it verbatim in the place where it's used. But why would that affect assignments to a global variable?

答:
Why are you calling it in a subshell at all?

```<code>zzz=2
f() { zzz=4; }
$(f)            # assigns COPY of zzz, then goes POOF
echo $zzz
f               # assigns to zzz
echo $zzz
</code>```

By running it in a subshell you are creating a child environment which gets the variable assigned, then evaporates.

Body:
Consider following code:

zzz=2

function f()
{
    zzz=4
}

$(f)
echo $zzz

Why is the assignment (zzz=4) ignored? I thought I knew what $( ) does - it takes everything written to stdout and pastes it verbatim in the place where it's used. But why would that affect assignments to a global variable?

Body:
Why are you calling it in a subshell at all?

zzz=2
f() { zzz=4; }
$(f)            # assigns COPY of zzz, then goes POOF
echo $zzz
f               # assigns to zzz
echo $zzz

By running it in a subshell you are creating a child environment which gets the variable assigned, then evaporates.


问:
xamarin.forms Handle Clicked event on WebView
I want to handle the click/tap event on a WebView control

I've tried the GestureRecognizers but nothing happens, i think maybe the WebView has some sort of making the event handled "true".

```<code><WebView>
   <WebView.GestureRecognizers>
      <TapGestureRecognizer
              Tapped="OnWebViewClick"
              NumberOfTapsRequired="1" />
   </WebView.GestureRecognizers>
</WebView>
</code>```

And I've tried it using c# code behind too but no luck :/

答:
An easier workaround is to use the 'Focused' event on your webview. You can implement it as below:</p>

```<code>var wb = new WebView
{
  HorizontalOptions = LayoutOptions.FillAndExpand,
  VerticalOptions = LayoutOptions.FillAndExpand,
  Source = "https://stackoverflow.com/questions/56320611/webview-gesturerecognition-not-working-in-xamarin-forms",
};

wb.Focused += (s, e) =>
{
   //Handle your logic here!
   wb.Unfocus();
};
</code>```

Body:
I want to handle the click/tap event on a WebView control

I've tried the GestureRecognizers but nothing happens, i think maybe the WebView has some sort of making the event handled "true".

<WebView>
   <WebView.GestureRecognizers>
      <TapGestureRecognizer
              Tapped="OnWebViewClick"
              NumberOfTapsRequired="1" />
   </WebView.GestureRecognizers>
</WebView>

And I've tried it using c# code behind too but no luck :/

Body:
An easier workaround is to use the 'Focused' event on your webview. You can implement it as below:

var wb = new WebView
{
  HorizontalOptions = LayoutOptions.FillAndExpand,
  VerticalOptions = LayoutOptions.FillAndExpand,
  Source = "https://stackoverflow.com/questions/56320611/webview-gesturerecognition-not-working-in-xamarin-forms",
};

wb.Focused += (s, e) =>
{
   //Handle your logic here!
   wb.Unfocus();
};


问:
My VPC is greyed out when trying to create a EC2 Instance?
I am trying to create an instance into my already created VPC network. For some reason when I am in the middle of the launch, I cannot select my VPC and it only lets me select a default VPC which is not what I want.

答:
The reason for grey-out is because the VPC is created with "dedicated" tenancy. Changing the VPC to"default" tenancy will solve the issue. Apparently, there is no option to make that change in the AWS GUI. Either you have to delete and re-create the VPC with default tenancy or modify the tenancy value using the AWS CLI.

To modify the instance tenancy attribute of a VPC using the AWS CLI

Use the modify-vpc-tenancy command to specify the ID of the VPC and instance tenancy value. The only supported value is default.

aws ec2 modify-vpc-tenancy --vpc-id vpc-1a2b3c4d --instance-tenancy default


问:
How can I check the value in a key-value nested list?
I have created a REST web service.

I have in the response, a nested list with 5 key-value associations in each list.
I only want to check if each value has the right format (boolean, string or integer).

So this is the nested list.

```<code>{"marches": [
      {
      "id": 13,
      "libelle": "CAS",
      "libelleSite": "USA",
      "siteId": 1,
      "right": false,
      "active": true
   },
      {
      "id": 21,
      "libelle": "MQS",
      "libelleSite": "Spain",
      "siteId": 1,
      "right": false,
      "active": true
   },
      {
      "id": 1,
      "libelle": "ASCV",
      "libelleSite": "Italy",
      "siteId": 1,
      "right": false,
      "active": true
   }]
}
</code>```

I use the JsonSlurper class to read the groovy response.

```<code>import groovy.json.JsonSlurper
def responseMessage = messageExchange.response.responseContent
def json = new JsonSlurper().parseText(responseMessage)
</code>```

With this following loop, I achieve in getting each block of list.

```<code>marches.each { n ->
    log.info "Nested $n \n"
}
</code>```

I want for instance check if the value associated to the key "id", "13" is well an integer and so on.

答:
You're almost there. Inside of the .each, it represents the nested object:

```<code>json.marches.each {
  assert it.id instanceof Integer  // one way to do it

  //another way
  if( !(it.libelle instanceof String) ){
    log.info "${it.id} has bad libelle"
  }

  //one more way
  return (it.libelleSite instanceof String) &&
     (it.siteId instanceof Integer) && (it.right instanceof Boolean)
}
</code>```

If you don't care about the specifics and just want to make sure they're all good, you can also use .every:

```<code>assert json.marches.every {
    it.id instanceof Integer &&
    it.libelle instanceof String &&
    it.libelleSite instanceof String &&
    it.active instanceof Boolean  //...and so on
}
</code>```

Body:
I have created a REST web service.

I have in the response, a nested list with 5 key-value associations in each list.
I only want to check if each value has the right format (boolean, string or integer).

So this is the nested list.

{"marches": [
      {
      "id": 13,
      "libelle": "CAS",
      "libelleSite": "USA",
      "siteId": 1,
      "right": false,
      "active": true
   },
      {
      "id": 21,
      "libelle": "MQS",
      "libelleSite": "Spain",
      "siteId": 1,
      "right": false,
      "active": true
   },
      {
      "id": 1,
      "libelle": "ASCV",
      "libelleSite": "Italy",
      "siteId": 1,
      "right": false,
      "active": true
   }]
}

I use the JsonSlurper class to read the groovy response.

import groovy.json.JsonSlurper
def responseMessage = messageExchange.response.responseContent
def json = new JsonSlurper().parseText(responseMessage)

With this following loop, I achieve in getting each block of list.

marches.each { n ->
    log.info "Nested $n \n"
}

I want for instance check if the value associated to the key "id", "13" is well an integer and so on.

Body:
You're almost there. Inside of the .each, it represents the nested object:

json.marches.each {
  assert it.id instanceof Integer  // one way to do it

  //another way
  if( !(it.libelle instanceof String) ){
    log.info "${it.id} has bad libelle"
  }

  //one more way
  return (it.libelleSite instanceof String) &&
     (it.siteId instanceof Integer) && (it.right instanceof Boolean)
}

If you don't care about the specifics and just want to make sure they're all good, you can also use .every:

assert json.marches.every {
    it.id instanceof Integer &&
    it.libelle instanceof String &&
    it.libelleSite instanceof String &&
    it.active instanceof Boolean  //...and so on
}


问:
How to see the graph plotted using DataFrame in PyCharm Community Edition?
I started Python programming today...

I have a simple code that created a Pandas DataFrame from a Input JSON file.
I also plotted a graph. But I don't know how to toggle the output screen visualizing this graph in PyCharm community edition?

The code compiles successfully however with the following warning: "UserWarning: Attempting to set identical left == right == 1.0 results in singular transformations; automatically expanding."

Now how do I view/toggle/export this graph?

```<code># Python program showing
# use of json package

import pandas as pd
import json

with open("test.json", "r") as read_it:
    data = json.load(read_it)

df = pd.DataFrame(data, index=[0])

print(df)
df.plot(x='Rpm', y='Torque')

</code>```

I want to see the actual x y plot itself....

答:
You can save the figure using plt.savefig from matplotlib

```<code>import pandas as pd
import json
import matplotlib.pyplot as plt # <--- Import pyplot

with open("test.json", "r") as read_it:
    data = json.load(read_it)

df = pd.DataFrame(data, index=[0])

print(df)
df.plot(x='Rpm', y='Torque')
plt.savefig('figure.png') # <--- Name the file whatever you want
</code>```

If you want to just visualize it, and not save it, you can use

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

Body:
I started Python programming today...

I have a simple code that created a Pandas DataFrame from a Input JSON file.
I also plotted a graph. But I don't know how to toggle the output screen visualizing this graph in PyCharm community edition?

The code compiles successfully however with the following warning: "UserWarning: Attempting to set identical left == right == 1.0 results in singular transformations; automatically expanding."

Now how do I view/toggle/export this graph?

# Python program showing
# use of json package

import pandas as pd
import json

with open("test.json", "r") as read_it:
    data = json.load(read_it)

df = pd.DataFrame(data, index=[0])

print(df)
df.plot(x='Rpm', y='Torque')

I want to see the actual x y plot itself....

Body:
You can save the figure using plt.savefig from matplotlib

import pandas as pd
import json
import matplotlib.pyplot as plt # <--- Import pyplot

with open("test.json", "r") as read_it:
    data = json.load(read_it)

df = pd.DataFrame(data, index=[0])

print(df)
df.plot(x='Rpm', y='Torque')
plt.savefig('figure.png') # <--- Name the file whatever you want

If you want to just visualize it, and not save it, you can use

plt.show()


问:
Distinct query isn't giving any results with AND operator
Here is the query that i am trying to execute, but i get no results, if you need more information to help regarding this kindly ask in the comments below i would appreciate any assistance Thanks.

```<code>SELECT DISTINCT *
FROM `users`
WHERE ((`height` BETWEEN "139" AND "170"
        AND `language` = "english")
       AND (`active` = "1"
            AND `gender` IN (4525, 4526)
            AND DATEDIFF(CURDATE(), `birthday`) / 365 >= "22"
            AND DATEDIFF(CURDATE(), `birthday`) / 365 <= "55"
            AND `country` = "IT")
       AND `id` NOT IN (SELECT `block_userid`
                        FROM `blocks`
                        WHERE `user_id` = 1)
       AND `id` NOT IN (SELECT `like_userid`
                        FROM `likes`
                        WHERE `user_id` = 1)
       AND `id` NOT IN (SELECT `user_id`
                        FROM `likes`
                        WHERE `like_userid` = 1)
       AND `id` <> "1" )
ORDER BY
    `xlikes_created_at` DESC, `xvisits_created_at` DESC,
    `xmatches_created_at` DESC, `is_pro` DESC
LIMIT 12 OFFSET 0;
</code>```

I tried OR operator but certainly i am not looking for OR i want all conditions to be true then want the results.

```<code>function GetSearchResults($user_id, $limit, $offset, $country = true) {
    $where_or = array();
    $where_and = array();
    $u = auth();

    // main query
    $query = 'SELECT DISTINCT * FROM `users`';

    // Filters
    $where = ' WHERE ( ';
    // must be verified
    $where_and[] = '`active` = "1"';
    //$where_and[] = '`privacy_show_profile_match_profiles` = "1"';

    //********** public search params *****************//
    // check gender from post or from session
    $genders = null;
    if( isset($_SESSION['_gender']) && $_SESSION['_gender'] !== '') {
        $genders = Secure( $_SESSION['_gender'] );
    }

    if( isset($_POST['_gender']) && $_POST['_gender'] !== '') {
        $_SESSION[ '_gender' ] = $_POST['_gender'];
        $genders = Secure( $_POST['_gender'] );
    }

    if( $genders == null || $genders == 'male' || $genders == 'female' ) {
        $genders = '4525, 4526';
    }

    if( is_array($genders)) {
        $genders = @implode( ',' , $genders );
    }

    if( strpos( $genders, ',' ) === false ) {
        $where_and[] = '`gender` = "'. $genders .'"';
    } else {
        $where_and[] = '`gender` IN ('. $genders .')';
    }

    // check age from post or from session
    if(isset($_POST['_age_from']) && !empty($_POST['_age_from']) && isset($_POST['_age_to']) && !empty($_POST['_age_to']) ) {
        $where_and[] = 'DATEDIFF(CURDATE(), `birthday`)/365 >= "'. Secure($_POST['_age_from']) .'" AND DATEDIFF(CURDATE(), `birthday`)/365 <= "'. Secure($_POST['_age_to']) . '"';
    } else {
        if(isset( $_SESSION['_age_from'] ) && isset( $_SESSION['_age_to'] )) {
            $where_and[] = 'DATEDIFF(CURDATE(), `birthday`)/365 >= "'. Secure($_SESSION['_age_from']) .'" AND DATEDIFF(CURDATE(), `birthday`)/365 <= "'. Secure($_SESSION['_age_to']) . '"';
        } else {
            $where_and[] = 'DATEDIFF(CURDATE(), `birthday`)/365 >= "20" AND DATEDIFF(CURDATE(), `birthday`)/365 <= "55"';
        }
    }

    $query_country = '';
    if( $u->show_me_to == '' ) {
        if ((isset($_POST['_lat']) && !empty($_POST['_lat']) && isset($_POST['_lng']) && !empty($_POST['_lng']))
            ||
            (isset($_SESSION['_lat']) && !empty($_SESSION['_lat']) && isset($_SESSION['_lng']) && !empty($_SESSION['_lng']))
         ) {
             $lat = 0;
             $lng = 0;
             $located = 7;

             if(isset( $_SESSION['_lat'] ) ) $lat = Secure($_SESSION['_lat']);
             if(isset( $_POST['_lat'] ) ) $lat = Secure($_POST['_lat']);

             if( isset( $_SESSION['_lng'] ) ) $lng = Secure($_SESSION['_lng']);
             if( isset( $_POST['_lng'] ) ) $lng = Secure($_POST['_lng']);

             if( isset( $_SESSION['_located'] ) ) $located = Secure($_SESSION['_located']);
             if( isset( $_POST['_located'] ) ) $located = Secure($_POST['_located']);

             $distance = 'ROUND( ( 6371 * acos(cos(radians(' . $lat . ')) * cos(radians(`lat`)) * cos(radians(`lng`) - radians(' . $lng . ')) + sin(radians(' . $lat . ')) * sin(radians(`lat`)))) ,1) ';
             $where_and[] = $distance . ' <= ' . $located;
         }
    } else {
        if($country == true) {
            $query_country = ' OR `country` = "' . $u->show_me_to . '"';
            $where_and[] = '`country` = "' . $u->show_me_to . '"';
        }
    }

    //******************* Looks Filters ************************//
    if( isset($_POST['_height_from']) && !empty($_POST['_height_from']) && isset($_POST['_height_to']) && !empty($_POST['_height_to']) ) {
        $where_or[] = '`height` BETWEEN "'. Secure($_POST['_height_from']) .'" AND "'. Secure($_POST['_height_to']) .'"';
    }

    if( isset($_POST['_body']) && !empty($_POST['_body']) ) {
        if( strpos( Secure( $_POST['_body'] ), ',' ) === false ) {
            $where_or[] = '`body` = "'. Secure($_POST['_body']) . '"';
        } else {
            $where_or[] = '`body` IN ('. Secure($_POST['_body']) .')';
        }
    }

    //******************* Background Filter ********************//
    if( isset($_POST['_language']) && !empty($_POST['_language']) ) {
        $where_or[] = '`language` = "'. Secure($_POST['_language']) .'"';
    }

    if( isset($_POST['_ethnicity']) && !empty($_POST['_ethnicity']) ) {
        if( strpos( Secure( $_POST['_ethnicity'] ), ',' ) === false ) {
            $where_or[] = '`ethnicity` = "'. Secure($_POST['_ethnicity']) . '"';
        } else {
            $where_or[] = '`ethnicity` IN ('. Secure($_POST['_ethnicity']) .')';
        }
    }

    if( isset($_POST['_religion']) && !empty($_POST['_religion']) ) {
        if( strpos( Secure( $_POST['_religion'] ), ',' ) === false ) {
            $where_or[] = '`religion` = "'. Secure($_POST['_religion']) . '"';
        } else {
            $where_or[] = '`religion` IN ('. Secure($_POST['_religion']) .')';
        }
    }

    //******************* LifeStyle filter *********************//
    if( isset($_POST['_relationship']) && !empty($_POST['_relationship']) ) {
        if( strpos( Secure( $_POST['_relationship'] ), ',' ) === false ) {
            $where_or[] = '`relationship` = "'. Secure($_POST['_relationship']) .'"';
        } else {
            $where_or[] = '`relationship` IN ('. Secure($_POST['_relationship']) .')';
        }
    }

    if( isset($_POST['_smoke']) && !empty($_POST['_smoke']) ) {
        if( strpos( Secure( $_POST['_smoke'] ), ',' ) === false ) {
            $where_or[] = '`smoke` = "'. Secure($_POST['_smoke']) . '"';
        } else {
            $where_or[] = '`smoke` IN ('. Secure($_POST['_smoke']) .')';
        }
    }

    if( isset($_POST['_drink']) && !empty($_POST['_drink']) ) {
        if( strpos( Secure( $_POST['_drink'] ), ',' ) === false ) {
            $where_or[] = '`drink` = "'. Secure($_POST['_drink']) . '"';
        } else {
            $where_or[] = '`drink` IN ('. Secure($_POST['_drink']) .')';
        }
    }

    //******************* More Filter **************************//
    if( isset($_POST['_interest']) && !empty($_POST['_interest']) ) {
        $where_or[] = '`interest` like "%'. Secure($_POST['_interest']) .'%"';
    }

    if( isset($_POST['_education']) && !empty($_POST['_education']) ) {
        if( strpos( Secure( $_POST['_education'] ), ',' ) === false ) {
            $where_or[] = '`education` = "'. Secure($_POST['_education']) .   '"';
        } else {
            $where_or[] = '`education` IN ('. Secure($_POST['_education']) .')';
        }
    }

    if( isset($_POST['_pets']) && !empty($_POST['_pets']) ) {
        if( strpos( Secure( $_POST['_pets'] ), ',' ) === false ) {
            $where_or[] = '`pets` = "'. Secure($_POST['_pets']) .'"';
        } else {
            $where_or[] = '`pets` IN ('. Secure($_POST['_pets']) .')';
        }
    }
if( !empty($where_or) ){
    $where = $where . '('. implode($where_or, ' AND ') . ') ';
}
if( !empty($where_and) ){
    if( !empty($where_or) ) {
        $where = $where . ' AND (' . implode($where_and, ' AND ') . ')';
    }else{
        $where = $where . ' (' . implode($where_and, ' AND ') . ')';
    }
}

if( isset( $_REQUEST['access_token'] ) ) {
    $uid = GetUserFromSessionID(Secure($_REQUEST['access_token']));
    $u->id = $uid;
}

if( isset( $u->id ) ) {
    // to exclude blocked users
    $notin = ' OR `id` NOT IN (SELECT `block_userid` FROM `blocks` WHERE `user_id` = ' . $u->id . ') ';
    // to exclude liked and disliked users users
    $notin .= ' OR `id` NOT IN (SELECT `like_userid` FROM `likes` WHERE `user_id` = ' . $u->id . ') ';
    $notin .= ' OR `id` NOT IN (SELECT `user_id` FROM `likes` WHERE `like_userid` = ' . $u->id . ') ';
    $notin .= ' OR `id` <> "' . $u->id . '" ';
}

$custom_sql = [];
if(isset($_POST['custom_profile_data'])){
    $count = 100;
    for($i = 0 ; $i <= $count ; $i++ ){
        if(isset($_POST['fid_' . $i])){
            if(!empty($_POST['fid_' . $i])){
                $custom_sql[] = ' id IN (SELECT `user_id` FROM `userfields` WHERE `fid_' . $i .'` = "'.Secure($_POST['fid_' . $i]) . '") ';
            }
        }
    }
}

$custom_sql_text = '';
if(!empty($custom_sql)){
    $custom_sql_text .= ' AND ( ';
    $custom_sql_text .= implode(' OR ', $custom_sql);
    $custom_sql_text .= ' ) ';
}

if( $limit == 0 ) {
    $limit = 20;
}
$orderBy = ' ORDER BY ';
$orderBy .= '`xlikes_created_at` DESC';
$orderBy .= ',`xvisits_created_at` DESC';
$orderBy .= ',`xmatches_created_at` DESC';
$orderBy .= ',`is_pro` DESC';
$query = $query . ' ' . $where . $notin . ') ' . $custom_sql_text . $query_country . $orderBy . ' LIMIT '.$limit.' OFFSET '.$offset.';';
return $query;
</code>```

}

答:
Why you need distinct? usually users are unique

```<code>SELECT DISTINCT * FROM `users`
</code>```

Dont save numeric values as strings

```<code>`height` BETWEEN "139" AND "170"
</code>```

You have the gender condition repeated: And I don't want to sound insensitive but those are a lot of genders.

```<code>`gender` IN (4525,4526,1275,1277,1278,1279,1280,1281,1282,1283)
</code>```

You have 2 date diff, and second one doesn't have a comparator. Also Datediff return a numeric value not a string

```<code>DATEDIFF(CURDATE(), `birthday`)/365 >= "24"
DATEDIFF(CURDATE(), `birthday`)/365  "16"
</code>```

Now if the missing operator on DATEDIFF doesn't solve the problem. Go direct to the DB remove all conditions and start adding those one by one until you found which one cause return 0 rows.

Body:
Here is the query that i am trying to execute, but i get no results, if you need more information to help regarding this kindly ask in the comments below i would appreciate any assistance Thanks.

SELECT DISTINCT *
FROM `users`
WHERE ((`height` BETWEEN "139" AND "170"
        AND `language` = "english")
       AND (`active` = "1"
            AND `gender` IN (4525, 4526)
            AND DATEDIFF(CURDATE(), `birthday`) / 365 >= "22"
            AND DATEDIFF(CURDATE(), `birthday`) / 365 <= "55"
            AND `country` = "IT")
       AND `id` NOT IN (SELECT `block_userid`
                        FROM `blocks`
                        WHERE `user_id` = 1)
       AND `id` NOT IN (SELECT `like_userid`
                        FROM `likes`
                        WHERE `user_id` = 1)
       AND `id` NOT IN (SELECT `user_id`
                        FROM `likes`
                        WHERE `like_userid` = 1)
       AND `id` <> "1" )
ORDER BY
    `xlikes_created_at` DESC, `xvisits_created_at` DESC,
    `xmatches_created_at` DESC, `is_pro` DESC
LIMIT 12 OFFSET 0;

I tried OR operator but certainly i am not looking for OR i want all conditions to be true then want the results.

function GetSearchResults($user_id, $limit, $offset, $country = true) {
    $where_or = array();
    $where_and = array();
    $u = auth();

    // main query
    $query = 'SELECT DISTINCT * FROM `users`';

    // Filters
    $where = ' WHERE ( ';
    // must be verified
    $where_and[] = '`active` = "1"';
    //$where_and[] = '`privacy_show_profile_match_profiles` = "1"';

    //********** public search params *****************//
    // check gender from post or from session
    $genders = null;
    if( isset($_SESSION['_gender']) && $_SESSION['_gender'] !== '') {
        $genders = Secure( $_SESSION['_gender'] );
    }

    if( isset($_POST['_gender']) && $_POST['_gender'] !== '') {
        $_SESSION[ '_gender' ] = $_POST['_gender'];
        $genders = Secure( $_POST['_gender'] );
    }

    if( $genders == null || $genders == 'male' || $genders == 'female' ) {
        $genders = '4525, 4526';
    }

    if( is_array($genders)) {
        $genders = @implode( ',' , $genders );
    }

    if( strpos( $genders, ',' ) === false ) {
        $where_and[] = '`gender` = "'. $genders .'"';
    } else {
        $where_and[] = '`gender` IN ('. $genders .')';
    }

    // check age from post or from session
    if(isset($_POST['_age_from']) && !empty($_POST['_age_from']) && isset($_POST['_age_to']) && !empty($_POST['_age_to']) ) {
        $where_and[] = 'DATEDIFF(CURDATE(), `birthday`)/365 >= "'. Secure($_POST['_age_from']) .'" AND DATEDIFF(CURDATE(), `birthday`)/365 <= "'. Secure($_POST['_age_to']) . '"';
    } else {
        if(isset( $_SESSION['_age_from'] ) && isset( $_SESSION['_age_to'] )) {
            $where_and[] = 'DATEDIFF(CURDATE(), `birthday`)/365 >= "'. Secure($_SESSION['_age_from']) .'" AND DATEDIFF(CURDATE(), `birthday`)/365 <= "'. Secure($_SESSION['_age_to']) . '"';
        } else {
            $where_and[] = 'DATEDIFF(CURDATE(), `birthday`)/365 >= "20" AND DATEDIFF(CURDATE(), `birthday`)/365 <= "55"';
        }
    }

    $query_country = '';
    if( $u->show_me_to == '' ) {
        if ((isset($_POST['_lat']) && !empty($_POST['_lat']) && isset($_POST['_lng']) && !empty($_POST['_lng']))
            ||
            (isset($_SESSION['_lat']) && !empty($_SESSION['_lat']) && isset($_SESSION['_lng']) && !empty($_SESSION['_lng']))
         ) {
             $lat = 0;
             $lng = 0;
             $located = 7;

             if(isset( $_SESSION['_lat'] ) ) $lat = Secure($_SESSION['_lat']);
             if(isset( $_POST['_lat'] ) ) $lat = Secure($_POST['_lat']);

             if( isset( $_SESSION['_lng'] ) ) $lng = Secure($_SESSION['_lng']);
             if( isset( $_POST['_lng'] ) ) $lng = Secure($_POST['_lng']);

             if( isset( $_SESSION['_located'] ) ) $located = Secure($_SESSION['_located']);
             if( isset( $_POST['_located'] ) ) $located = Secure($_POST['_located']);

             $distance = 'ROUND( ( 6371 * acos(cos(radians(' . $lat . ')) * cos(radians(`lat`)) * cos(radians(`lng`) - radians(' . $lng . ')) + sin(radians(' . $lat . ')) * sin(radians(`lat`)))) ,1) ';
             $where_and[] = $distance . ' <= ' . $located;
         }
    } else {
        if($country == true) {
            $query_country = ' OR `country` = "' . $u->show_me_to . '"';
            $where_and[] = '`country` = "' . $u->show_me_to . '"';
        }
    }

    //******************* Looks Filters ************************//
    if( isset($_POST['_height_from']) && !empty($_POST['_height_from']) && isset($_POST['_height_to']) && !empty($_POST['_height_to']) ) {
        $where_or[] = '`height` BETWEEN "'. Secure($_POST['_height_from']) .'" AND "'. Secure($_POST['_height_to']) .'"';
    }

    if( isset($_POST['_body']) && !empty($_POST['_body']) ) {
        if( strpos( Secure( $_POST['_body'] ), ',' ) === false ) {
            $where_or[] = '`body` = "'. Secure($_POST['_body']) . '"';
        } else {
            $where_or[] = '`body` IN ('. Secure($_POST['_body']) .')';
        }
    }

    //******************* Background Filter ********************//
    if( isset($_POST['_language']) && !empty($_POST['_language']) ) {
        $where_or[] = '`language` = "'. Secure($_POST['_language']) .'"';
    }

    if( isset($_POST['_ethnicity']) && !empty($_POST['_ethnicity']) ) {
        if( strpos( Secure( $_POST['_ethnicity'] ), ',' ) === false ) {
            $where_or[] = '`ethnicity` = "'. Secure($_POST['_ethnicity']) . '"';
        } else {
            $where_or[] = '`ethnicity` IN ('. Secure($_POST['_ethnicity']) .')';
        }
    }

    if( isset($_POST['_religion']) && !empty($_POST['_religion']) ) {
        if( strpos( Secure( $_POST['_religion'] ), ',' ) === false ) {
            $where_or[] = '`religion` = "'. Secure($_POST['_religion']) . '"';
        } else {
            $where_or[] = '`religion` IN ('. Secure($_POST['_religion']) .')';
        }
    }

    //******************* LifeStyle filter *********************//
    if( isset($_POST['_relationship']) && !empty($_POST['_relationship']) ) {
        if( strpos( Secure( $_POST['_relationship'] ), ',' ) === false ) {
            $where_or[] = '`relationship` = "'. Secure($_POST['_relationship']) .'"';
        } else {
            $where_or[] = '`relationship` IN ('. Secure($_POST['_relationship']) .')';
        }
    }

    if( isset($_POST['_smoke']) && !empty($_POST['_smoke']) ) {
        if( strpos( Secure( $_POST['_smoke'] ), ',' ) === false ) {
            $where_or[] = '`smoke` = "'. Secure($_POST['_smoke']) . '"';
        } else {
            $where_or[] = '`smoke` IN ('. Secure($_POST['_smoke']) .')';
        }
    }

    if( isset($_POST['_drink']) && !empty($_POST['_drink']) ) {
        if( strpos( Secure( $_POST['_drink'] ), ',' ) === false ) {
            $where_or[] = '`drink` = "'. Secure($_POST['_drink']) . '"';
        } else {
            $where_or[] = '`drink` IN ('. Secure($_POST['_drink']) .')';
        }
    }

    //******************* More Filter **************************//
    if( isset($_POST['_interest']) && !empty($_POST['_interest']) ) {
        $where_or[] = '`interest` like "%'. Secure($_POST['_interest']) .'%"';
    }

    if( isset($_POST['_education']) && !empty($_POST['_education']) ) {
        if( strpos( Secure( $_POST['_education'] ), ',' ) === false ) {
            $where_or[] = '`education` = "'. Secure($_POST['_education']) .   '"';
        } else {
            $where_or[] = '`education` IN ('. Secure($_POST['_education']) .')';
        }
    }

    if( isset($_POST['_pets']) && !empty($_POST['_pets']) ) {
        if( strpos( Secure( $_POST['_pets'] ), ',' ) === false ) {
            $where_or[] = '`pets` = "'. Secure($_POST['_pets']) .'"';
        } else {
            $where_or[] = '`pets` IN ('. Secure($_POST['_pets']) .')';
        }
    }
if( !empty($where_or) ){
    $where = $where . '('. implode($where_or, ' AND ') . ') ';
}
if( !empty($where_and) ){
    if( !empty($where_or) ) {
        $where = $where . ' AND (' . implode($where_and, ' AND ') . ')';
    }else{
        $where = $where . ' (' . implode($where_and, ' AND ') . ')';
    }
}

if( isset( $_REQUEST['access_token'] ) ) {
    $uid = GetUserFromSessionID(Secure($_REQUEST['access_token']));
    $u->id = $uid;
}

if( isset( $u->id ) ) {
    // to exclude blocked users
    $notin = ' OR `id` NOT IN (SELECT `block_userid` FROM `blocks` WHERE `user_id` = ' . $u->id . ') ';
    // to exclude liked and disliked users users
    $notin .= ' OR `id` NOT IN (SELECT `like_userid` FROM `likes` WHERE `user_id` = ' . $u->id . ') ';
    $notin .= ' OR `id` NOT IN (SELECT `user_id` FROM `likes` WHERE `like_userid` = ' . $u->id . ') ';
    $notin .= ' OR `id` <> "' . $u->id . '" ';
}

$custom_sql = [];
if(isset($_POST['custom_profile_data'])){
    $count = 100;
    for($i = 0 ; $i <= $count ; $i++ ){
        if(isset($_POST['fid_' . $i])){
            if(!empty($_POST['fid_' . $i])){
                $custom_sql[] = ' id IN (SELECT `user_id` FROM `userfields` WHERE `fid_' . $i .'` = "'.Secure($_POST['fid_' . $i]) . '") ';
            }
        }
    }
}

$custom_sql_text = '';
if(!empty($custom_sql)){
    $custom_sql_text .= ' AND ( ';
    $custom_sql_text .= implode(' OR ', $custom_sql);
    $custom_sql_text .= ' ) ';
}

if( $limit == 0 ) {
    $limit = 20;
}
$orderBy = ' ORDER BY ';
$orderBy .= '`xlikes_created_at` DESC';
$orderBy .= ',`xvisits_created_at` DESC';
$orderBy .= ',`xmatches_created_at` DESC';
$orderBy .= ',`is_pro` DESC';
$query = $query . ' ' . $where . $notin . ') ' . $custom_sql_text . $query_country . $orderBy . ' LIMIT '.$limit.' OFFSET '.$offset.';';
return $query;

}

Body:
Why you need distinct? usually users are unique

SELECT DISTINCT * FROM `users`

Dont save numeric values as strings

`height` BETWEEN "139" AND "170"

You have the gender condition repeated: And I don't want to sound insensitive but those are a lot of genders.

`gender` IN (4525,4526,1275,1277,1278,1279,1280,1281,1282,1283)

You have 2 date diff, and second one doesn't have a comparator. Also Datediff return a numeric value not a string

DATEDIFF(CURDATE(), `birthday`)/365 >= "24"
DATEDIFF(CURDATE(), `birthday`)/365  "16"

Now if the missing operator on DATEDIFF doesn't solve the problem. Go direct to the DB remove all conditions and start adding those one by one until you found which one cause return 0 rows.


问:
Populating HTML table from 2 different Array in PHP
I am trying to create an HTML table from 2 different PHP arrays. Here are those arrays -

```<code>Array
(
    [0] => test1
    [1] => test2
)
Array
(
    [0] => column1
    [1] => column2
)
</code>```

I am creating those arrays like this -

```<code>$query = $_GET['query'];
$query_arr = explode(",", $query);
print_r($query_arr);
$boid = $_GET['boid'];
$boid_arr = explode(",", $boid);
print_r($boid_arr);
</code>```

I need a table something like below -

```<code>DATA    COLUMN
test1   column1
test2   column2
</code>```

I am not able to figure out how to achieve this. Any help will be appreciated.

答:
```<code><table>
    <tr>
        <td>DATA</td>
        <td>COLUMN</td>
    </tr>
<?php
// Add any markup that you need in `foreach`
foreach ($query_arr as $key => $value) {?>
    <tr>
        <td><?=$value?></td>
        <td><?=$boid_arr[$key]?></td>
    </tr>
<?php
}?>
</table>
</code>```

Body:
I am trying to create an HTML table from 2 different PHP arrays. Here are those arrays -

Array
(
    [0] => test1
    [1] => test2
)
Array
(
    [0] => column1
    [1] => column2
)

I am creating those arrays like this -

$query = $_GET['query'];
$query_arr = explode(",", $query);
print_r($query_arr);
$boid = $_GET['boid'];
$boid_arr = explode(",", $boid);
print_r($boid_arr);

I need a table something like below -

DATA    COLUMN
test1   column1
test2   column2

I am not able to figure out how to achieve this. Any help will be appreciated.


问:
How to repeat a trigger keydown event?
I'm setting a little help system (step-by-step) with html and jquery. When you complete one step, if you click in the "Next" button, you can see the next step. I would like to allow user to press also the right arrow key to move forward whit the guide.
I setting the trigger to simulate the click but it works only once time.

```<code>
$(".next").click(function(){
    //function
});

$("body").keydown(function(e) {
  if(e.keyCode == 39) { // right
    $(".next").trigger('click'); // simulate the click on .next
  }
}); // keydown
</code>```

Here a demo:
http://jsfiddle.net/mlarsen1982/sqrx9gz7/5

答:
Faking key events is notoriously unreliable due to the security features of modern browsers. A more reliable solution would be to extract the logic of the keypress event to its own function and call it directly, for example:

```<code>$(".next").click(function(){
  showNext();
});

$("body").keydown(function(e) {
  if (e.which === 39) {
    showNext();
  }
});

function showNext() {
  // your logic here...
}
</code>```

Title: How to repeat a trigger keydown event?

Body:
I'm setting a little help system (step-by-step) with html and jquery. When you complete one step, if you click in the "Next" button, you can see the next step. I would like to allow user to press also the right arrow key to move forward whit the guide.
I setting the trigger to simulate the click but it works only once time.

$(".next").click(function(){
    //function
});

$("body").keydown(function(e) {
  if(e.keyCode == 39) { // right
    $(".next").trigger('click'); // simulate the click on .next
  }
}); // keydown

Here a demo:
http://jsfiddle.net/mlarsen1982/sqrx9gz7/5

Body:
Faking key events is notoriously unreliable due to the security features of modern browsers. A more reliable solution would be to extract the logic of the keypress event to its own function and call it directly, for example:

$(".next").click(function(){
  showNext();
});

$("body").keydown(function(e) {
  if (e.which === 39) {
    showNext();
  }
});

function showNext() {
  // your logic here...
}


问:
Advanced table-layout to CSS
I have gotten the assignment to code a website from tables to CSS. While this is easy I have one question on how to recreate one of the site's biggest detail.

Site is: www.optimizer.dk.

How can I recreate the labels coming out of the left side, while still having the content in the middle?

Rest of the site is no worries.

Is the solution to:

```<code>     padding-left: 200000px;
     margin-left: -200000px;
</code>```

To fake the expansion to the left?

答:
i would put it all in a div and set position:absolute;. then put your buttons in there own divs so you can move them.

or

put it all in a div and set the margin to -5%(mite need to play with this into it works). then make the image the background and put you text buttons in there own div's so you can move then to where you want them.

Then use float:left; to line them up

Title: Advanced table-layout to CSS

Body:
I have gotten the assignment to code a website from tables to CSS. While this is easy I have one question on how to recreate one of the site's biggest detail.

Site is: www.optimizer.dk.

How can I recreate the labels coming out of the left side, while still having the content in the middle?

Rest of the site is no worries.

Is the solution to:

     padding-left: 200000px;
     margin-left: -200000px;

To fake the expansion to the left?


问:
How to pad images to a specific size like 720*576 with a pixel value/border value?
I have images of various sizes like 122*98, 98*65, 320*256, 620*540. How to make all images to a fixed size say 720*576 by padding them with border/some pixel value? Is there a generic way to do it which works for input images of any size? I tried some methods using PIL module, but didn't get a generic solution.</p>

答:
I am assuming you are pretty tool-agnostic since you have tagged with OpenCV, PIL/Pillow and skimage, so I would suggest just using ImageMagick on the command line:

So, starting with these images as 1.png, 2.png and 3.png:

You can make an output directory and put them all in the North-West corner of a magenta background:

```<code>mkdir output
magick mogrify -path output -background magenta -extent 720x576 [123].png
</code>```

Or, put them all in the centre of a yellow background:

```<code>magick mogrify -path output -gravity center -background yellow  -extent 720x576 [123].png
</code>```

Omit the -path output if you want the files overwritten in place.

Omit the word magick if running v6 or older.

If you specifically want to do it in Python, one way is to make a solid canvas of the correct size and padding colour that you want as an output image and then paste your image onto that canvas, either at top-left or centred using some simple maths.

Another option is PIL/Pillow's ImageOps.expand() like here.

Body:
I am assuming you are pretty tool-agnostic since you have tagged with OpenCV, PIL/Pillow and skimage, so I would suggest just using ImageMagick on the command line:

So, starting with these images as 1.png, 2.png and 3.png:

You can make an output directory and put them all in the North-West corner of a magenta background:

mkdir output
magick mogrify -path output -background magenta -extent 720x576 [123].png

Or, put them all in the centre of a yellow background:

magick mogrify -path output -gravity center -background yellow  -extent 720x576 [123].png

Omit the -path output if you want the files overwritten in place.

Omit the word magick if running v6 or older.

If you specifically want to do it in Python, one way is to make a solid canvas of the correct size and padding colour that you want as an output image and then paste your image onto that canvas, either at top-left or centred using some simple maths.

Another option is PIL/Pillow's ImageOps.expand() like here.


问:
CORS policy when deleting an item
error message in google chromeWhen I try to delete an item I am getting an error.

When I added spring security to my backend i faced problem with csrf and could not event display my data from database in Angular. So, I made some steps:
I have added @WebSecurityConfigurerAdapter into my backend. Later set Interceptor in Angular and after this I was able to load my data using spring security in background.

```<code>@EnableWebSecurity
@Configuration
public class SpringSecurity extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
                .anyRequest().authenticated()
                .and()
                //.formLogin().and()
                .httpBasic();
    }
}
</code>```

Angular part my service with Interceptor

```<code>import { Injectable } from '@angular/core';
import {HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class HttpInterceptorService implements HttpInterceptor {

  intercept(request: HttpRequest<any>, next: HttpHandler) {
    const username = 'damian';
    const password = 'damian';
    const basicAutHeaderString = 'Basic ' + window.btoa(username + ':' + password);

    request = request.clone(
      {
        setHeaders: {
          Authorization: basicAutHeaderString
        }
      }
    );
    return next.handle(request);
  }

  constructor() { }

}
</code>```

Getting single item from backend:

```<code>  deleteSingleTodo(id) {
    return this.http.delete<Todo>(`http://localhost:8081/${id}`);
  }
</code>```

My delete method which is triggered by (click) button:

```<code>  deleteTodo(id) {
    console.log(`delete todo ${id}` )
    this.getDataService.deleteSingleTodo( id).subscribe (
      response => {
        console.log(response);
        this.message = `Delete of Todo ${id} Successful!`;
        this.refreshTodos();
      }
    );
  }

I also provided HTTP_INTERCEPTORS in app.module.ts
 providers: [
    { provide: HTTP_INTERCEPTORS, `useClass: HttpInterceptorService, multi:` true}
</code>```

],[my error message in google][1]

答:
Can you simply add a filter for applying CORS like as shown below to see if it is working</p>

```<code>@Component
public class CrossOriginFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(CrossOriginFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        // Called by the web container to indicate to a filter that it is being
        // placed into service.
        // We do not want to do anything here.
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        log.info("Applying CORS filter");
        HttpServletResponse response = (HttpServletResponse) resp;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, X-Requested-With, Content-Type, Accept, X-Auth-Token, X-CSRF-TOKEN");
        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {

        // Called by the web container to indicate to a filter that it is being
        // taken out of service.
        // We do not want to do anything here.
    }
}
</code>```

Title: CORS policy when deleting an item

Body:
error message in google chromeWhen I try to delete an item I am getting an error.

When I added spring security to my backend i faced problem with csrf and could not event display my data from database in Angular. So, I made some steps:
I have added @WebSecurityConfigurerAdapter into my backend. Later set Interceptor in Angular and after this I was able to load my data using spring security in background.

@EnableWebSecurity
@Configuration
public class SpringSecurity extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
                .anyRequest().authenticated()
                .and()
                //.formLogin().and()
                .httpBasic();
    }
}

Angular part my service with Interceptor

import { Injectable } from '@angular/core';
import {HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class HttpInterceptorService implements HttpInterceptor {

  intercept(request: HttpRequest<any>, next: HttpHandler) {
    const username = 'damian';
    const password = 'damian';
    const basicAutHeaderString = 'Basic ' + window.btoa(username + ':' + password);

    request = request.clone(
      {
        setHeaders: {
          Authorization: basicAutHeaderString
        }
      }
    );
    return next.handle(request);
  }

  constructor() { }

}

Getting single item from backend:

  deleteSingleTodo(id) {
    return this.http.delete<Todo>(`http://localhost:8081/${id}`);
  }

My delete method which is triggered by (click) button:

  deleteTodo(id) {
    console.log(`delete todo ${id}` )
    this.getDataService.deleteSingleTodo( id).subscribe (
      response => {
        console.log(response);
        this.message = `Delete of Todo ${id} Successful!`;
        this.refreshTodos();
      }
    );
  }

I also provided HTTP_INTERCEPTORS in app.module.ts
 providers: [
    { provide: HTTP_INTERCEPTORS, `useClass: HttpInterceptorService, multi:` true}

],[my error message in google][1]

Body:
Can you simply add a filter for applying CORS like as shown below to see if it is working

@Component
public class CrossOriginFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(CrossOriginFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        // Called by the web container to indicate to a filter that it is being
        // placed into service.
        // We do not want to do anything here.
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        log.info("Applying CORS filter");
        HttpServletResponse response = (HttpServletResponse) resp;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, X-Requested-With, Content-Type, Accept, X-Auth-Token, X-CSRF-TOKEN");
        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {

        // Called by the web container to indicate to a filter that it is being
        // taken out of service.
        // We do not want to do anything here.
    }
}


问:
How to fix "Error: Can not find or load the main class"?
I'm trying to execute a simple java code.

the code worked fine using comand line : javac Go.java and java Go, but in Spring Tool Suite 3, the code did not work and I got the error below.

Note that I'm using jdk1.8.0_211

```<code>package com.test;

public class Go {

public static void main(String[] args) {
    System.out.println("test");
  }

}
</code>```

I expect print test, but I get this error :

```<code>Error: Can not find or load the main class.
</code>```

答: the cause of the problem is that I'm not the owner of the Laptop, it is managed by the administrator of the company where I work. I noticed that when I change the version of JAVA, the code runs correctly, but after restarting the Laptop, I get the same error again, so the cause was that every restart of the laptop, it updates java version, I fixed my PC to not updating java version again and it works

Body:
I'm trying to execute a simple java code.

the code worked fine using comand line : javac Go.java and java Go, but in Spring Tool Suite 3, the code did not work and I got the error below.

Note that I'm using jdk1.8.0_211

package com.test;

public class Go {

public static void main(String[] args) {
    System.out.println("test");
  }

}

I expect print test, but I get this error :

Error: Can not find or load the main class.


问:
Link to id but navbar in the way
I have a navbar with links to a article with id="about", but my navbar is fixed-top, so when I click on the link, my navbar is in front of the title of the section.

I solved this problem by using this:

```<code>.main-content article .anchor{
    position: absolute;
    top: -106px;
}
</code>```

But for scrollspy I need the href of the link to be the same as the id of the section where I want to "scrollspy" but I can't use the same id twice.

How can I solve this? Is there a way to go to add -100px to your href or something like that?

答:
You can try with jquery like this:</p>

```<code>$(document).ready(function() {
  $('a[href^="#"]').click(function() {
      var target = $(this.hash);
      $('html, body').animate({ scrollTop: target.offset().top-100 }, 1000);
  }
}
</code>```

Title: Link to id but navbar in the way

Body:
I have a navbar with links to a article with id="about", but my navbar is fixed-top, so when I click on the link, my navbar is in front of the title of the section.

I solved this problem by using this:

.main-content article .anchor{
    position: absolute;
    top: -106px;
}

But for scrollspy I need the href of the link to be the same as the id of the section where I want to "scrollspy" but I can't use the same id twice.

How can I solve this? Is there a way to go to add -100px to your href or something like that?

Body:
You can try with jquery like this:

$(document).ready(function() {
  $('a[href^="#"]').click(function() {
      var target = $(this.hash);
      $('html, body').animate({ scrollTop: target.offset().top-100 }, 1000);
  }
}


问:
Coding a subtraction loop that takes in a list
I am making a calculator and need a subtraction loop for the code to work. Right now it is scanning the list but only doing the first and last numbers not the entire list.

```<code>if(a.equals("Subtract")) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        System.out.println("Enter integers one at a time in order");
        System.out.println("When completed type done");
        while (scan.hasNextInt()) {
            list.add(scan.nextInt());
        }
        Integer[] nums = list.toArray(new Integer[0]);
        for (int i = 0; i < nums.length-1; i++) {
            sum = nums[0];
            sum = sum - nums[i+1];
        }
        System.out.println("Your total is " + sum);
        System.out.println("-----------------------------");
        main(args);
        }
</code>```

Only subtracts the first and last numbers of loop not entire loop in order

答:
You're almost there.
Move the assignment of the first value outside the loop and start the loop from the second element of the array (index=1):

```<code>sum = nums[0];
for (int i = 1; i < nums.length; i++) {
    sum = sum - nums[i];
}
</code>```

EDIT: Thanks Joakim for your remark. Fixed the end condition in the for loop

Body:
I am making a calculator and need a subtraction loop for the code to work. Right now it is scanning the list but only doing the first and last numbers not the entire list.

if(a.equals("Subtract")) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        System.out.println("Enter integers one at a time in order");
        System.out.println("When completed type done");
        while (scan.hasNextInt()) {
            list.add(scan.nextInt());
        }
        Integer[] nums = list.toArray(new Integer[0]);
        for (int i = 0; i < nums.length-1; i++) {
            sum = nums[0];
            sum = sum - nums[i+1];
        }
        System.out.println("Your total is " + sum);
        System.out.println("-----------------------------");
        main(args);
        }

Only subtracts the first and last numbers of loop not entire loop in order

Body:
You're almost there.
Move the assignment of the first value outside the loop and start the loop from the second element of the array (index=1):

sum = nums[0];
for (int i = 1; i < nums.length; i++) {
    sum = sum - nums[i];
}

EDIT: Thanks Joakim for your remark. Fixed the end condition in the for loop


问:
Google Web App: Can't read or write on my label after evaluate the page
I have a label on my HTML page which shows number returned values. I can't read or change that when it is loaded? but locally I can do that with a console log.

```<code><p name= 'message' id='ftext' > This team have
  <label id="teams" > <?= teamSize ?> </label>
  members.  </p>
</code>```

it returns null for both of these tag ids document.getElementById('team') or document.getElementById('ftext'), so I can't get their innerText or text Contents.
I am using HtmlService.createTemplateFromFile(file).evaluate() for rendering the page.

here is a link to my project: Attendance Form

Thanks for your help,

M

答:
You said that document.getElementById('team') didn't work, but you actually named your id "teams".

If that fix doesn't work, can you share your code?

It's really frustrating to get variables between the frontend and the backend in GAS!

Something like this:

```<code>  google.script.run
  .withSuccessHandler(finishedOutput)
  .withFailureHandler(errorOutput)
  .split(); // SPLIT IS THE GS SCRIPT THAT PASSES BACK THE NUMBER YOU WANT
</code>```

and then this

```<code>  function finishedOutput(info) //INFO IS THE THING THAT GOT PASSED BACK BEFORE
  {
    var br='<br />';
    var outputDiv = document.getElementById('status');
    outputDiv.innerHTML = 'The spreadsheet has been split.' + br +'New files in this folder: ' + info.link + br ;
    document.getElementById('process').style.display="none";

  };
</code>```

In my example I was passing back an object that had a info key but you can do this with a number or a string rather than an object.

these are both inside  on the html page, and then the "split" function is on Code.gs and is a GAS function. Messy, right?

Body:
I have a label on my HTML page which shows number returned values. I can't read or change that when it is loaded? but locally I can do that with a console log.

 This team have
   <?= teamSize ?>
  members.

it returns null for both of these tag ids document.getElementById('team') or document.getElementById('ftext'), so I can't get their innerText or text Contents.
I am using HtmlService.createTemplateFromFile(file).evaluate() for rendering the page.

here is a link to my project: Attendance Form

Thanks for your help,

M

Body:
You said that document.getElementById('team') didn't work, but you actually named your id "teams".

If that fix doesn't work, can you share your code?

It's really frustrating to get variables between the frontend and the backend in GAS!

Something like this:

  google.script.run
  .withSuccessHandler(finishedOutput)
  .withFailureHandler(errorOutput)
  .split(); // SPLIT IS THE GS SCRIPT THAT PASSES BACK THE NUMBER YOU WANT

and then this

  function finishedOutput(info) //INFO IS THE THING THAT GOT PASSED BACK BEFORE
  {
    var br='<br />';
    var outputDiv = document.getElementById('status');
    outputDiv.innerHTML = 'The spreadsheet has been split.' + br +'New files in this folder: ' + info.link + br ;
    document.getElementById('process').style.display="none";

  };

In my example I was passing back an object that had a info key but you can do this with a number or a string rather than an object.

these are both inside  on the html page, and then the "split" function is on Code.gs and is a GAS function. Messy, right?


问:
Assigning new value to a variable cleans old value from memory?
I have a class that holds a reference to another class

```<code>class Monkey {
  constructor(){
    this.banana = null
  }

  getNewBanana() {
    this.banana = new Banana()
  }

  ...otherMethods

}
</code>```

If I call getNewBanana more than one time, the instances of Banana will be deleted from memory? Or I need to do something to delete it?

I'm going to make a class that will do alot of this.something = new AnyThing() and I want to make sure that there is no memory leak or something like that.

答: According to https://javascript.info/garbage-collection, automatic Garbage Collector removes the unreachable object from memory, so there won't be a memory leak, however, the garbage collector tries to run only while the CPU is idle, to reduce the possible effect on the execution. If the Banana object is very huge and the application does lots of processes while creating many of the objects it can affect the app performance.</p>

Body:
I have a class that holds a reference to another class

class Monkey {
  constructor(){
    this.banana = null
  }

  getNewBanana() {
    this.banana = new Banana()
  }

  ...otherMethods

}

If I call getNewBanana more than one time, the instances of Banana will be deleted from memory? Or I need to do something to delete it?

I'm going to make a class that will do alot of this.something = new AnyThing() and I want to make sure that there is no memory leak or something like that.


问:
Why can't a nullable int be implicitly conversion to an int ? Technical reason or design choice?
In C#, there is no implicit conversion from the int? type to the int type.

I have defined the following implicit operator

```<code>namespace System
{
    public partial struct Int32
    {
        public static implicit operator Int32(int? v)
        {
            return (Int32)(v ?? 0);
        }
    }
}
</code>```

Which allows me to compile the following code

```<code>int? nullableInt = 0;
Int32 regularInt = nullableInt;
</code>```

but if I define regularInt as an int instead of Int32 I get the following error

Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)

I expected int and Int32 to be interchangeable but the C# language clearly hasn't been built with this functionality in mind.

Is there a technical reason behind the impossibility of defining this operation, is it a decision made to prevent potential code smell ?

I'm aware that defining such an implicit operator could result in some very unexpected behavior, as the conversion from a null value to a 0 integer doesn't make sense in every situation. This question is more about "why can't it be done" than "why doing it is a really  bad idea"

答:
The code you have doesn't add an implicit conversion from the .NET's nullable int to .NET's int.  It creates a whole new type, called Int32, in the System namespace, but as it's in a different assembly than Core.dll, it's a different type.  (Take a look at typeof(int).FullName and typeof(int32).FullName to see this.)

The code you showed to try to test this implicit conversion is set up so that it's trying to convert the system's nullable type to your own new type, and since you created such an implicit conversion, it succeeds.  It fails when you use the system type instead of your own new type because there is no implicit conversion between those types.

You cannot create implicit (or explicit) conversions for types from outside the definition of one of those types, and since you can't access the source of either Nullable or the .NET Int32, you can't add an implicit conversion.

Body:
In C#, there is no implicit conversion from the int? type to the int type.

I have defined the following implicit operator

namespace System
{
    public partial struct Int32
    {
        public static implicit operator Int32(int? v)
        {
            return (Int32)(v ?? 0);
        }
    }
}

Which allows me to compile the following code

int? nullableInt = 0;
Int32 regularInt = nullableInt;

but if I define regularInt as an int instead of Int32 I get the following error

Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)

I expected int and Int32 to be interchangeable but the C# language clearly hasn't been built with this functionality in mind.

Is there a technical reason behind the impossibility of defining this operation, is it a decision made to prevent potential code smell ?

I'm aware that defining such an implicit operator could result in some very unexpected behavior, as the conversion from a null value to a 0 integer doesn't make sense in every situation. This question is more about "why can't it be done" than "why doing it is a really  bad idea"


问:
Py_Initialize undefined reference
I want to add python functions in  C++ code.

I made a GUI in gtk (on the Raspberry PI) and now I want to work with a camera module which is easy to handle in python. (I want to start a video directly when I push a button.)

So I included the file Python.h

```<code>#include <python3.4m/Python.h>
#include <python3.4m/pythonrun.h>
</code>```

then I thought it should work, but when I try to compile Py_Initialize()

I get the error:

undefined reference to Py_Initialize.

I think this is strange because, when I type in, there came the selection for Py_Initialize.

答:
Maybe you can see my answer in another question:

if with python 3.x installed, maybe this command can work:

```<code>g++ hw.cpp `/usr/bin/python3-config --cflags` `/usr/python3-config --ldflags`
</code>```

By the way, you should check you gcc and python version.

As I know, if gcc version is 5.4 and python version is 3.7, it doesn't work.(python 3.5 >is work)

When you run /usr/bin/python3-config --cflags, in fact, it is the compile option.

Title: Py_Initialize undefined reference

Body:
I want to add python functions in  C++ code.

I made a GUI in gtk (on the Raspberry PI) and now I want to work with a camera module which is easy to handle in python. (I want to start a video directly when I push a button.)

So I included the file Python.h

#include <python3.4m/Python.h>
#include <python3.4m/pythonrun.h>

then I thought it should work, but when I try to compile Py_Initialize()

I get the error:

undefined reference to Py_Initialize.

I think this is strange because, when I type in, there came the selection for Py_Initialize.

Body:
Maybe you can see my answer in another question:

if with python 3.x installed, maybe this command can work:

g++ hw.cpp `/usr/bin/python3-config --cflags` `/usr/python3-config --ldflags`

By the way, you should check you gcc and python version.

As I know, if gcc version is 5.4 and python version is 3.7, it doesn't work.(python 3.5 >is work)

When you run /usr/bin/python3-config --cflags, in fact, it is the compile option.


问:
R data.table calculations with previous row dependencies
Below is some data which I currently calculate in Excel.

```<code>col_A   col _B  col_C col_D col_E   col_F    col_G
-1.5%   0.010   1.00    1   1.00     -       -
-5.4%   0.024   1.00    1   1.00     0.01   -0.00
-7.9%   0.036   1.00    1   1.00     0.02   -0.00
-12.7%  0.052   0.99    1   0.99     0.06   -0.01
-4.6%   0.049   0.98    1   0.98     0.19   -0.01
-8.3%   0.051   0.95    1   0.95     0.39   -0.03
-7.3%   0.052   0.88    1   0.88     1.00   -0.07
-9.2%   0.055   0.69    1   0.69     2.31   -0.21
-7.9%   0.055   0.38    1   0.38     5.63   -0.44
-2.2%   0.051   0.29    1   0.29     11.13  -0.24
</code>```

I have been trying to perform the calculations in R using data.table. The problem I have is that data.table performs calculation column-wise. I need the calculations to be performed row-wise, because of dependencies on the results of previous row values. The Excel-formulas for the calculated columns are given below, with "T" indicating "current row" and "T-1" indication "previous row"

col_C: (col_C.T-1) * (1 + col_G.T)

col_D: max (Col_C.T, col_D.T-1)

col_E: (col_C.T / col_D.T)

col_F: max ((1 - (col_C.T-1 / col_D.T-1)) / col B.T-1), 0.01)

col_G: col_A * col_F

Any assistance is greatly appreciated.

Body:
Below is some data which I currently calculate in Excel.

col_A   col _B  col_C col_D col_E   col_F    col_G
-1.5%   0.010   1.00    1   1.00     -       -
-5.4%   0.024   1.00    1   1.00     0.01   -0.00
-7.9%   0.036   1.00    1   1.00     0.02   -0.00
-12.7%  0.052   0.99    1   0.99     0.06   -0.01
-4.6%   0.049   0.98    1   0.98     0.19   -0.01
-8.3%   0.051   0.95    1   0.95     0.39   -0.03
-7.3%   0.052   0.88    1   0.88     1.00   -0.07
-9.2%   0.055   0.69    1   0.69     2.31   -0.21
-7.9%   0.055   0.38    1   0.38     5.63   -0.44
-2.2%   0.051   0.29    1   0.29     11.13  -0.24

I have been trying to perform the calculations in R using data.table. The problem I have is that data.table performs calculation column-wise. I need the calculations to be performed row-wise, because of dependencies on the results of previous row values. The Excel-formulas for the calculated columns are given below, with "T" indicating "current row" and "T-1" indication "previous row"

col_C: (col_C.T-1) * (1 + col_G.T)

col_D: max (Col_C.T, col_D.T-1)

col_E: (col_C.T / col_D.T)

col_F: max ((1 - (col_C.T-1 / col_D.T-1)) / col B.T-1), 0.01)

col_G: col_A * col_F

Any assistance is greatly appreciated.

Body:
If there are no other conditions which require to use data.table I suggest to implement  the rowwise calculations using a matrix:

m <- data.matrix(dt)
m[, 3:7] <- NA

for (i in seq.int(nrow(m))) {
  if (i == 1L) {
    m[i, "col_F"] <- 0
    m[i, "col_G"] <- 0
    m[i, "col_C"] <- 1
    m[i, "col_D"] <- 1
  } else {
    m[i, "col_F"] <- max((1 - (m[i-1, "col_C"] / m[i-1, "col_D"])) / m[i-1, "col_B"], 0.01)
    m[i, "col_G"] <- m[i, "col_A"] * m[i, "col_F"]
    m[i, "col_C"] <- m[i-1, "col_C"] * (1 + m[i, "col_G"])
    m[i, "col_D"] <- max(m[i, "col_C"], m[i-1, "col_D"])
  }
m[i, "col_E"] <- m[i, "col_C"] / m[i, "col_D"]
}

m

       col_A col_B     col_C col_D     col_E       col_F        col_G
 [1,] -0.015 0.010 1.0000000     1 1.0000000  0.00000000  0.000000000
 [2,] -0.054 0.024 0.9994600     1 0.9994600  0.01000000 -0.000540000
 [3,] -0.079 0.036 0.9976835     1 0.9976835  0.02250000 -0.001777500
 [4,] -0.127 0.052 0.9895302     1 0.9895302  0.06434834 -0.008172239
 [5,] -0.046 0.049 0.9803653     1 0.9803653  0.20134322 -0.009261788
 [6,] -0.083 0.051 0.9477596     1 0.9477596  0.40070748 -0.033258721
 [7,] -0.073 0.052 0.8768905     1 0.8768905  1.02432085 -0.074775422
 [8,] -0.092 0.055 0.6858958     1 0.6858958  2.36749020 -0.217809099
 [9,] -0.079 0.055 0.3764416     1 0.3764416  5.71098585 -0.451167882
[10,] -0.022 0.051 0.2825483     1 0.2825483 11.33742486 -0.249423347

The deviations in the last 4 rows of col_F from OP's expected result might be due to the limited precision of the posted values of col_A and col_B.

Data

library(data.table)

dt <- fread("col_A   col_B  col_C col_D col_E   col_F    col_G
-1.5%   0.010   1.00    1   1.00     -       -
-5.4%   0.024   1.00    1   1.00     0.01   -0.00
-7.9%   0.036   1.00    1   1.00     0.02   -0.00
-12.7%  0.052   0.99    1   0.99     0.06   -0.01
-4.6%   0.049   0.98    1   0.98     0.19   -0.01
-8.3%   0.051   0.95    1   0.95     0.39   -0.03
-7.3%   0.052   0.88    1   0.88     1.00   -0.07
-9.2%   0.055   0.69    1   0.69     2.31   -0.21
-7.9%   0.055   0.38    1   0.38     5.63   -0.44
-2.2%   0.051   0.29    1   0.29     11.13  -0.24 ", na.strings = "-")
# convert percent string to numeric
dt[, col_A := readr::parse_number(col_A) / 100]


问:
Monitor POST requests to server in localhost
I wrote a simple route where my React app makes POST requests to and I would like to monitor those requests while in dev mode.

Despite I am logging it to console my terminal is not showing it, because I am running the app from React. How can I monitor post requests in my localhost?

```<code>app.post("/api/product_ids", (req, res) => {
  res.send({ BODY: req.query });
  console.log(res.query);
});
</code>```

答:
I think you need to console.log before you res.send. Make sure you are grabbing the right values too. </p>

```<code>app.post("/api/product_ids", (req, res) => {
  console.log(req.body);
  res.send(...);
});
</code>```

Body:
I wrote a simple route where my React app makes POST requests to and I would like to monitor those requests while in dev mode.

Despite I am logging it to console my terminal is not showing it, because I am running the app from React. How can I monitor post requests in my localhost?

app.post("/api/product_ids", (req, res) => {
  res.send({ BODY: req.query });
  console.log(res.query);
});

Body:
I think you need to console.log before you res.send. Make sure you are grabbing the right values too.

app.post("/api/product_ids", (req, res) => {
  console.log(req.body);
  res.send(...);
});