问:
Postgresql : "OR" does'nt work like I want
I've got some problem with my request :

This request work :

```<code>SELECT o.nom, a.url, a.apikey
FROM Organisation o, API a, Acheter ac
WHERE o.id_organisation = a.id_organisation
AND ac.id_organisation = o.id_organisation
AND ac.id_device = :idd ;
</code>```

This request work :

```<code>SELECT o.nom, a.url, a.apikey
FROM Organisation o, API a, Louer l
WHERE o.id_organisation = a.id_organisation
AND l.id_organisation = o.id_organisation
AND l.id_device = :idd
AND l.dateLocation + l.dureeLocation * interval '1 day' < CURRENT_DATE;
</code>```

But when I put an "OR" between the both requests, it doesn't work :

```<code>SELECT o.nom, a.url, a.apikey
FROM Organisation o, API a, Acheter ac, Louer l

WHERE o.id_organisation = a.id_organisation

AND (ac.id_organisation = o.id_organisation
AND ac.id_device = :idd)

OR (l.id_organisation = o.id_organisation
AND l.id_device = :idd
AND l.dateLocation + l.dureeLocation * interval '1 day' < CURRENT_DATE);
</code>```

I've tried to put parentheses, but the request still doesn't work.

Do you have any idea ?

答:
Becomes easier to read when you use joins:

```<code>SELECT o.nom, a.url, a.apikey
FROM Organisation AS o
LEFT JOIN API AS a ON o.id_organisation = a.id_organisation
LEFT JOIN Acheter AS ac ON ac.id_organisation = o.id_organisation
WHERE ac.id_device = :idd ;

SELECT o.nom, a.url, a.apikey
FROM Organisation o
LEFT JOIN API AS a ON o.id_organisation = a.id_organisation
LEFT JOIN Louer AS l ON l.id_organisation = o.id_organisation
WHERE l.id_device = :idd
AND l.dateLocation + l.dureeLocation * interval '1 day' < CURRENT_DATE;
</code>```

And now combine them:

```<code>SELECT o.nom, a.url, a.apikey
FROM Organisation o
LEFT JOIN API AS a ON o.id_organisation = a.id_organisation
LEFT JOIN Louer AS l ON l.id_organisation = o.id_organisation
LEFT JOIN Acheter AS ac ON ac.id_organisation = o.id_organisation

WHERE ac.id_device = :idd
      OR (
        l.id_device = :idd AND
        l.dateLocation + l.dureeLocation * interval '1 day' < CURRENT_DATE
      )
</code>```

Now where is the difference? You had a mistake in your parentheses. The o.id_organisation = a.id_organisation was canceled out by the or-condition.

Body:
I've got some problem with my request :

This request work :

SELECT o.nom, a.url, a.apikey
FROM Organisation o, API a, Acheter ac
WHERE o.id_organisation = a.id_organisation
AND ac.id_organisation = o.id_organisation
AND ac.id_device = :idd ;

This request work :

SELECT o.nom, a.url, a.apikey
FROM Organisation o, API a, Louer l
WHERE o.id_organisation = a.id_organisation
AND l.id_organisation = o.id_organisation
AND l.id_device = :idd
AND l.dateLocation + l.dureeLocation * interval '1 day' < CURRENT_DATE;

But when I put an "OR" between the both requests, it doesn't work :

SELECT o.nom, a.url, a.apikey
FROM Organisation o, API a, Acheter ac, Louer l

WHERE o.id_organisation = a.id_organisation

AND (ac.id_organisation = o.id_organisation
AND ac.id_device = :idd)

OR (l.id_organisation = o.id_organisation
AND l.id_device = :idd
AND l.dateLocation + l.dureeLocation * interval '1 day' < CURRENT_DATE);

I've tried to put parentheses, but the request still doesn't work.

Do you have any idea ?

Body:
Becomes easier to read when you use joins:

SELECT o.nom, a.url, a.apikey
FROM Organisation AS o
LEFT JOIN API AS a ON o.id_organisation = a.id_organisation
LEFT JOIN Acheter AS ac ON ac.id_organisation = o.id_organisation
WHERE ac.id_device = :idd ;

SELECT o.nom, a.url, a.apikey
FROM Organisation o
LEFT JOIN API AS a ON o.id_organisation = a.id_organisation
LEFT JOIN Louer AS l ON l.id_organisation = o.id_organisation
WHERE l.id_device = :idd
AND l.dateLocation + l.dureeLocation * interval '1 day' < CURRENT_DATE;

And now combine them:

SELECT o.nom, a.url, a.apikey
FROM Organisation o
LEFT JOIN API AS a ON o.id_organisation = a.id_organisation
LEFT JOIN Louer AS l ON l.id_organisation = o.id_organisation
LEFT JOIN Acheter AS ac ON ac.id_organisation = o.id_organisation

WHERE ac.id_device = :idd
      OR (
        l.id_device = :idd AND
        l.dateLocation + l.dureeLocation * interval '1 day' < CURRENT_DATE
      )

Now where is the difference? You had a mistake in your parentheses. The o.id_organisation = a.id_organisation was canceled out by the or-condition.


来源: stackexchange

问:
jQuery-Ajax doesn't send data
I use asp.net core for my project's backend but my method doesn't get data that I sent them by jQuery ajax

These are my scripts to send data:

```<code>function ChangeCount(productId, count) {
    $.ajax({
        type: "POST",
        data: JSON.stringify({ ProductId: productId, Count: count }),
        url:'@(Url.Action("ChangeOrderCount", "Payment"))',
        contentType: "application/json;",
        dataType:"json"
    }).done(function (result) {
        if(!isNaN(result)) {
            var NewProductCount = parseInt(result)
            if (NewProductCount == 0) {
                $("#Order-" + productId).fadeOut();
            }
            else {
                $("#OrderCount-" + productId).html(NewProductCount);
            }
        } else {
            alert(result);
        }
    });
}
</code>```

And this is my backend code:

```<code>public JsonResult ChangeOrderCount(int ProductId, int Count)
{
    string userId = userRepository.GetUserByEmail(User.Identity.Name).Id;
    bool result = bascketrepository.AddToCart(userId, ProductId, Count);
    if (result)
        return Json(bascketrepository.GetProductOrderCountInCurrentBascket(userId,ProductId));
    else
        return Json("خطایی رخ داده است");
}
</code>```

答:
In you ajax method,the contentType is “ application/json”,so the controller cannot analysis the data.If you want ajax pass data to controller,you need to change the contenttype in ajax.
Here is my controller and view,and it worked.

Controller:

```<code>[HttpPost]
        public JsonResult ChangeOrderCount(int ProductId, int Count)
        {
            Console.WriteLine(ProductId + "," + Count);
            return Json("success");
        }
        [HttpGet]
        public IActionResult ChangeOrderCount()
        {
            return View();
        }
</code>```

View:

```<code>@section scripts{
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            var productId = 1;
            var count = 2;
            ChangeCount(productId, count);
        })
        function ChangeCount(productId, count) {
            $.ajax({
                type: "POST",
                data: { ProductId: productId, Count: count },
                url: '@(Url.Action("ChangeOrderCount", "Payment"))',
                contentType: "application/x-www-form-urlencoded",
            }).done(function (result) {
                if (!isNaN(result)) {
                    var NewProductCount = parseInt(result)
                    if (NewProductCount == 0) {
                        $("#Order-" + productId).fadeOut();
                    }
                    else {
                        $("#OrderCount-" + productId).html(NewProductCount);
                    }
                } else {
                    alert(result);
                }
            });
        }

    </script>
}
</code>```

And this is the result:

or you can just change the code of controller:

Model:

```<code>public class ProductCount
    {
        public int ProductId { get; set; }
        public int Count { get; set; }
    }
</code>```

Controller:

```<code>[HttpPost]
        public JsonResult ChangeOrderCount([FromBody]ProductCount productCount)
        {
            Console.WriteLine(productCount.ProductId + "," + productCount.Count);
            return Json("success");
        }
        [HttpGet]
        public IActionResult ChangeOrderCount()
        {
            return View();
        }
</code>```

View:

```<code>$(function () {
        var productId = 1;
        var count = 2;
        ChangeCount(productId, count);
    })
    function ChangeCount(productId, count) {
        $.ajax({
            type: "POST",
            data: JSON.stringify({ ProductId: productId, Count: count }),
            url: '@(Url.Action("ChangeOrderCount", "Payment"))',
            contentType: "application/json",
        }).done(function (result) {
            if (!isNaN(result)) {
                var NewProductCount = parseInt(result)
                if (NewProductCount == 0) {
                    $("#Order-" + productId).fadeOut();
                }
                else {
                    $("#OrderCount-" + productId).html(NewProductCount);
                }
            } else {
                alert(result);
            }
        });
    }
</code>```

And this is the result:

ContentLicense: CC BY-SA 4.0

Title: jQuery-Ajax doesn't send data

Body:
I use asp.net core for my project's backend but my method doesn't get data that I sent them by jQuery ajax

These are my scripts to send data:

function ChangeCount(productId, count) {
    $.ajax({
        type: "POST",
        data: JSON.stringify({ ProductId: productId, Count: count }),
        url:'@(Url.Action("ChangeOrderCount", "Payment"))',
        contentType: "application/json;",
        dataType:"json"
    }).done(function (result) {
        if(!isNaN(result)) {
            var NewProductCount = parseInt(result)
            if (NewProductCount == 0) {
                $("#Order-" + productId).fadeOut();
            }
            else {
                $("#OrderCount-" + productId).html(NewProductCount);
            }
        } else {
            alert(result);
        }
    });
}

And this is my backend code:

public JsonResult ChangeOrderCount(int ProductId, int Count)
{
    string userId = userRepository.GetUserByEmail(User.Identity.Name).Id;
    bool result = bascketrepository.AddToCart(userId, ProductId, Count);
    if (result)
        return Json(bascketrepository.GetProductOrderCountInCurrentBascket(userId,ProductId));
    else
        return Json("خطایی رخ داده است");
}

Body:
In you ajax method,the contentType is “ application/json”,so the controller cannot analysis the data.If you want ajax pass data to controller,you need to change the contenttype in ajax.
Here is my controller and view,and it worked.

Controller:

[HttpPost]
        public JsonResult ChangeOrderCount(int ProductId, int Count)
        {
            Console.WriteLine(ProductId + "," + Count);
            return Json("success");
        }
        [HttpGet]
        public IActionResult ChangeOrderCount()
        {
            return View();
        }

View:

@section scripts{
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            var productId = 1;
            var count = 2;
            ChangeCount(productId, count);
        })
        function ChangeCount(productId, count) {
            $.ajax({
                type: "POST",
                data: { ProductId: productId, Count: count },
                url: '@(Url.Action("ChangeOrderCount", "Payment"))',
                contentType: "application/x-www-form-urlencoded",
            }).done(function (result) {
                if (!isNaN(result)) {
                    var NewProductCount = parseInt(result)
                    if (NewProductCount == 0) {
                        $("#Order-" + productId).fadeOut();
                    }
                    else {
                        $("#OrderCount-" + productId).html(NewProductCount);
                    }
                } else {
                    alert(result);
                }
            });
        }

    </script>
}

And this is the result:

or you can just change the code of controller:

Model:

public class ProductCount
    {
        public int ProductId { get; set; }
        public int Count { get; set; }
    }

Controller:

[HttpPost]
        public JsonResult ChangeOrderCount([FromBody]ProductCount productCount)
        {
            Console.WriteLine(productCount.ProductId + "," + productCount.Count);
            return Json("success");
        }
        [HttpGet]
        public IActionResult ChangeOrderCount()
        {
            return View();
        }

View:

$(function () {
        var productId = 1;
        var count = 2;
        ChangeCount(productId, count);
    })
    function ChangeCount(productId, count) {
        $.ajax({
            type: "POST",
            data: JSON.stringify({ ProductId: productId, Count: count }),
            url: '@(Url.Action("ChangeOrderCount", "Payment"))',
            contentType: "application/json",
        }).done(function (result) {
            if (!isNaN(result)) {
                var NewProductCount = parseInt(result)
                if (NewProductCount == 0) {
                    $("#Order-" + productId).fadeOut();
                }
                else {
                    $("#OrderCount-" + productId).html(NewProductCount);
                }
            } else {
                alert(result);
            }
        });
    }

And this is the result:


问:
Django runserver stuck on Performing system checks
I am running python manage.py runserver or migrate and in both commands it is getting stuck on Performing system checks...  Can you please help me out to understand what is the issue and how to solve it?</p>

```<code>Admins-MacBook-Pro:driveu_backend gathole$ python manage.py runserver
/Users/gathole/.virtualenvs/du/lib/python2.7/site-packages/social_auth/models.py:4: RemovedInDjango19Warning: django.utils.importlib will be removed in Django 1.9.
  from django.utils.importlib import import_module

/Users/gathole/.virtualenvs/du/lib/python2.7/site-packages/social_auth/utils.py:14: RemovedInDjango19Warning: The utilities in django.db.models.loading are deprecated in favor of the new application loading system.
  from django.db.models.loading import get_model

/Users/gathole/.virtualenvs/du/lib/python2.7/site-packages/social_auth/models.py:4: RemovedInDjango19Warning: django.utils.importlib will be removed in Django 1.9.
  from django.utils.importlib import import_module

/Users/gathole/.virtualenvs/du/lib/python2.7/site-packages/social_auth/utils.py:14: RemovedInDjango19Warning: The utilities in django.db.models.loading are deprecated in favor of the new application loading system.
  from django.db.models.loading import get_model

Performing system checks...
</code>```

答:
This is probably a network problem. My code worked fine before but one day I add client = BertClient() in some files and I forgot to start the bert server (bert is an ML model). As a results, I encountered the same problem of starting my Django app.

You can check start from the app's urls.py file by commenting/uncommenting imports.

ContentLicense: CC BY-SA 3.0

Body:
I am running python manage.py runserver or migrate and in both commands it is getting stuck on Performing system checks...  Can you please help me out to understand what is the issue and how to solve it?

Admins-MacBook-Pro:driveu_backend gathole$ python manage.py runserver
/Users/gathole/.virtualenvs/du/lib/python2.7/site-packages/social_auth/models.py:4: RemovedInDjango19Warning: django.utils.importlib will be removed in Django 1.9.
  from django.utils.importlib import import_module

/Users/gathole/.virtualenvs/du/lib/python2.7/site-packages/social_auth/utils.py:14: RemovedInDjango19Warning: The utilities in django.db.models.loading are deprecated in favor of the new application loading system.
  from django.db.models.loading import get_model

/Users/gathole/.virtualenvs/du/lib/python2.7/site-packages/social_auth/models.py:4: RemovedInDjango19Warning: django.utils.importlib will be removed in Django 1.9.
  from django.utils.importlib import import_module

/Users/gathole/.virtualenvs/du/lib/python2.7/site-packages/social_auth/utils.py:14: RemovedInDjango19Warning: The utilities in django.db.models.loading are deprecated in favor of the new application loading system.
  from django.db.models.loading import get_model

Performing system checks...


问:
Read multiple strings from a file and store it in a single character array
I want to store a line of string in a single line to a single charracter array such as, Let file content to be this:

```<code>1 Bar of Chocolate 45
</code>```

I want to store "Bar of Chocolate" to a single character array when using fscanf. When I try fscanf it only reads "Bar" as a single string.

答:
Following program can be used as starting point:

```<code>#include <stdio.h>
#include <stdlib.h>

int main() {

    int nb1;
    int nb2;
    char s1[50];

    int rc;

    printf("Please enter data:");
    rc = scanf("%d %[a-zA-Z ] %d", &nb1, s1, &nb2);

    printf("\nMatched input items=%d\n", rc);
    printf("\nEntered data: nb1=%d s1=%s nb2=%d\n", nb1, s1, nb2);

    return 0;
}
</code>```

Execution:

```<code>./scanf
Please enter data:1 Bar Of Chocolate 45

Matched input items=3

Entered data: nb1=1 s1=Bar Of Chocolate  nb2=45
</code>```

Body:
I want to store a line of string in a single line to a single charracter array such as, Let file content to be this:

1 Bar of Chocolate 45

I want to store "Bar of Chocolate" to a single character array when using fscanf. When I try fscanf it only reads "Bar" as a single string.

Body:
Following program can be used as starting point:

#include <stdio.h>
#include <stdlib.h>

int main() {

    int nb1;
    int nb2;
    char s1[50];

    int rc;

    printf("Please enter data:");
    rc = scanf("%d %[a-zA-Z ] %d", &nb1, s1, &nb2);

    printf("\nMatched input items=%d\n", rc);
    printf("\nEntered data: nb1=%d s1=%s nb2=%d\n", nb1, s1, nb2);

    return 0;
}

Execution:

./scanf
Please enter data:1 Bar Of Chocolate 45

Matched input items=3

Entered data: nb1=1 s1=Bar Of Chocolate  nb2=45


问:
Is it possible to update pipeline parameter value from mapping data flow?
use-case :

Trying to create a pipeline which receives bulk data from source SQL and to sink to different tables in destination SQL based on one column. The column dedicates the table name in the destination.

I have declared a parameter at data flow which needs to be updated based on the column value and use the same value as dynamic table name in the sink.

any thoughts ?

答:
As far as I am aware,it is impossible.

According to this document,you can get values and change them from pipeline in data flow,but you can't update them from data flow.

Hope this can help you.


问:
Colouring a matplotlib.pyplot line plot piecewise without the use of loops
I have some python code which produces a finite number of sequential points in the 2-D plane, and I am using matpoltlib to try to plot these points with a connecting line, which is there to illustrate the order the points were returned in. For example, if I had the points (0,0), (0,1), (1,1), (1,-1), (-1,-1), (-1,2),... (describing the square spiral), I could plot this with the code:

```<code>import matplotlib.pyplot as plt

x = [0,1,1,-1,-1,2,2,-2,-2]
y = [0,0,1,1,-1,-1,2,2,-2]

plt.plot(x,y)
plt.show()
</code>```

Which would return the plot:

To better highlight the order the points are returned in, I would however like a gradient colour scheme to be applied to this plot, with each constituent line being coloured differently (while being coloured consistently across that line segment). So that something to this effect would be returned:

I realise this can be done with through a loop, drawing each line individually and colouring it as required. But this is tediously slow, and as the number of points increase my computer near draws to a halt. As such, is there a way this can be achieved in some sort of optimised manner?

答:
You can do this by arranging your data a bit differently such that the x and y in plt.plot are both 2d list of starts and end points e.g.

```<code>import matplotlib.pyplot as plt

x = [-2, -2, 2, 2, -1, -1, 1, 1, 0]
y = [-2, 2, 2, -1, -1, 1, 1, 0, 0]

plt.plot([x[:-1], x[1:]], [y[:-1], y[1:]])
</code>```

This will give you the plot you want (albeit with some extra styling needed for the colours of your choice)

Edit:

Why does matplotlib do this? Well, to some extent that is just how pyplot.plt works. The key bit is under Plotting multiple sets of data: "Alternatively, if your data is already a 2d array, you can pass it directly to x, y. A separate data set will be drawn for every column."

By doing [x[:-1], x[1:]] we are essentially making our x into a 2d list:

```<code>[[-2, -2, 2,  2, -1, -1, 1, 1],
 [-2,  2, 2, -1, -1,  1, 1, 0]]
</code>```

and each column is of this is considered as a separate line (when matched with y in the same format).

To colour the individual lines using this method you might want to use the object-oriented api (ax instead of plt), and use ax.set_prop_cycle to set the colours from a colour map, such as the Spectral colour map. Your final code will look something like

```<code>fig, ax = plt.subplots()
n = len(x)
colors = plt.cm.Spectral([i / n for i in range(1, n+1)])
ax.set_prop_cycle('color', colors)
ax.plot([x[:-1], x[1:]], [y[:-1], y[1:]])
</code>```

(or with numpy)

```<code>colors = plt.cm.Spectral(np.linspace(0, 1, len(x)))
</code>```

The first version will give you

Body:
I have some python code which produces a finite number of sequential points in the 2-D plane, and I am using matpoltlib to try to plot these points with a connecting line, which is there to illustrate the order the points were returned in. For example, if I had the points (0,0), (0,1), (1,1), (1,-1), (-1,-1), (-1,2),... (describing the square spiral), I could plot this with the code:

import matplotlib.pyplot as plt

x = [0,1,1,-1,-1,2,2,-2,-2]
y = [0,0,1,1,-1,-1,2,2,-2]

plt.plot(x,y)
plt.show()

Which would return the plot:

To better highlight the order the points are returned in, I would however like a gradient colour scheme to be applied to this plot, with each constituent line being coloured differently (while being coloured consistently across that line segment). So that something to this effect would be returned:

I realise this can be done with through a loop, drawing each line individually and colouring it as required. But this is tediously slow, and as the number of points increase my computer near draws to a halt. As such, is there a way this can be achieved in some sort of optimised manner?

Body:
You can do this by arranging your data a bit differently such that the x and y in plt.plot are both 2d list of starts and end points e.g.

import matplotlib.pyplot as plt

x = [-2, -2, 2, 2, -1, -1, 1, 1, 0]
y = [-2, 2, 2, -1, -1, 1, 1, 0, 0]

plt.plot([x[:-1], x[1:]], [y[:-1], y[1:]])

This will give you the plot you want (albeit with some extra styling needed for the colours of your choice)

Edit:

Why does matplotlib do this? Well, to some extent that is just how pyplot.plt works. The key bit is under Plotting multiple sets of data: "Alternatively, if your data is already a 2d array, you can pass it directly to x, y. A separate data set will be drawn for every column."

By doing [x[:-1], x[1:]] we are essentially making our x into a 2d list:

[[-2, -2, 2,  2, -1, -1, 1, 1],
 [-2,  2, 2, -1, -1,  1, 1, 0]]

and each column is of this is considered as a separate line (when matched with y in the same format).

To colour the individual lines using this method you might want to use the object-oriented api (ax instead of plt), and use ax.set_prop_cycle to set the colours from a colour map, such as the Spectral colour map. Your final code will look something like

fig, ax = plt.subplots()
n = len(x)
colors = plt.cm.Spectral([i / n for i in range(1, n+1)])
ax.set_prop_cycle('color', colors)
ax.plot([x[:-1], x[1:]], [y[:-1], y[1:]])

(or with numpy)

colors = plt.cm.Spectral(np.linspace(0, 1, len(x)))

The first version will give you


问:
Regex credit card number tests
I'm testing one application where Regex pattern match credit card then such numbers should be highlighted. I'm using site http://regexpal.com/ to create test credit credit card numbers for my testing. my requirement is to have valid credit card numbers which can have "-" and/or "," between them.I was not successful to build such a number as when i test it using the site

http://regexpal.com.

I need few credit numbers with scenarios below

valid credit card number which can have "-" between any digit.

valid credit card number which can have "," between any digit.

valid credit card number which can have cobination of  "," or "-" between any digit.

Title: Regex credit card number tests

Body:
Here is my method for detecting card network (updated 2020):

function getCardBrandId($pan)
    {
        $regs = [
            ELECTRON => "/^(4026|417500|4405|4508|4844|4913|4917)\d+$/",
            MAESTRO  => "/^(?:50|5[6-9]|6[0-9])\d+$/",
            DANKORT  => "/^(5019|4571)\d+$/",
            CUP      => "/^(62|81)\d+$/",
            VISA     => "/^4[0-9]\d+$/",
            DINERS   => "/^(?:5[45]|36|30[0-5]|3095|3[8-9])\d+$/",
            MC       => "/^(?:5[1-5]|222[1-9]|22[3-9][0-9]|2[3-6][0-9][0-9]|27[0-1][0-9]|2720)\d+$/",
            AMEX     => "/^(34|37)\d+$/",
            DISCOVER => "/^6(?:011|22(12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|9[01][0-9]|92[0-5])|5|4|2[4-6][0-9]{3}|28[2-8][0-9]{2})\d+$/",
            JCB      => "/^(?:35[2-8][0-9])\d+$/",
            INTERPAY => "/^(636)\d+$/",
            KOREAN   => "/^9[0-9]\d+$/",
            MIR      => "/^(?:220[0-4])\d+$/",
        ];

        foreach ($regs as $brand => $reg) {
            if (preg_match($reg, $pan)) {
                return $brand;
            }
        }

        return "Unknown";
    }


问:
autocomplete by ajax php mysql
test.php

```<code><html>
    <head>
        <script type="text/javascript">
            function callajax()
            {
                if (window.XMLHttpRequest)
                {// code for IE7+, Firefox, Chrome, Opera, Safari
                    xmlhttp=new XMLHttpRequest();
                }
                else
                {// code for IE6, IE5
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
                xmlhttp.onreadystatechange=function()
                {
                    if (xmlhttp.readyState==4 && xmlhttp.status==200)
                    {
                        var customarray=new Array();
                        var str=xmlhttp.responseText;
                        customarray=str.split(",");
                        var obj = actb(document.getElementById('tb_name'),customarray);
                        alert(customarray[0]);
                    }
                }

                var username=document.getElementById('tb_name').value;

                xmlhttp.open("POST","fetchvalue.php",true);
                xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                xmlhttp.send("userid="+username);
            }
        </script>
        <script language="javascript" type="text/javascript" src="actb.js"></script>
        <script language="javascript" type="text/javascript" src="common.js"></script>
    </head>
    <body>
        <form action='' method='post'>
            <table>
                <tr>
                    <td><input type="text" name="tb_name" onkeyup="callajax();" id='tb_name'/></td>
                </tr>
            </table>
        </form>
    </body>
</html>

<script>
</script>
</code>```

fetchvalue.php

```<code>    $link = mysql_connect($host, $user, $pass);
    if (!mysql_select_db($db, $link)) {
        echo 'Could not select database';
        exit;
    }
    $uid=$_POST['userid'];
    //$uid='a';
    $select=mysql_query("select * from login where user LIKE '%$uid%'");
?>
<?php
    while($f=mysql_fetch_array($select)){
        echo $f['user'].',';
    }
?>
</code>```

its work fine but we have to use this alert(customarray[0]);

plz help me..

答:
I strongly discourage to use custom made solution when there are pretty good alternative already builted.

See jQuery UI autocomplete here http://jqueryui.com/demos/autocomplete/

Title: autocomplete by ajax php mysql

Body:
test.php

        <form action='' method='post'>

                    <input type="text" name="tb_name" onkeyup="callajax();" id='tb_name'/>

        </form>

fetchvalue.php

    $link = mysql_connect($host, $user, $pass);
    if (!mysql_select_db($db, $link)) {
        echo 'Could not select database';
        exit;
    }
    $uid=$_POST['userid'];
    //$uid='a';
    $select=mysql_query("select * from login where user LIKE '%$uid%'");
?>
<?php
    while($f=mysql_fetch_array($select)){
        echo $f['user'].',';
    }
?>

its work fine but we have to use this alert(customarray[0]);

plz help me..


问:
Is it possible to use NGraphics to draw geometric shapes on .net Forms?
I am trying to draw some geometric shapes using NGraphics in a picture box on a WinForm:

```<code>public partial class DrawingForm : Form
{
    public DrawingForm()
    {
        InitializeComponent();
    }

    private void DrawingForm_Load(object sender, EventArgs e)
    {
        var canvas = Platforms.Current.CreateImageCanvas(new NGraphics.Size(100), scale: 2);

        var skyBrush = new LinearGradientBrush(NGraphics.Point.Zero, NGraphics.Point.OneY, Colors.Blue, Colors.White);
        canvas.FillRectangle(new Rect(canvas.Size), skyBrush);
        canvas.FillEllipse(10, 10, 30, 30, Colors.Yellow);
        canvas.FillRectangle(50, 60, 60, 40, Colors.LightGray);
        canvas.FillPath(new PathOp[] {  new MoveTo (40, 60),
                                        new LineTo (120, 60),
                                        new LineTo (80, 30),
                                        new ClosePath ()
                                    }, Colors.Gray);

        this.pictureBox1.Image = (Image)canvas.GetImage();
    }
}
</code>```

This source code is giving the following exception:

```<code>Additional information: Unable to cast object of type 'NGraphics.ImageImage' to type 'System.Drawing.Image'.
</code>```

This is one problem. Another question is: is it possible to draw shapes directly on the Forms?

答:
Take a look at the source code for the NGraphics package, it looks like you should construct the GraphicsCanvas based on a standard Graphics context that you could obtain from the form.

https://github.com/praeclarum/NGraphics/blob/master/Platforms/NGraphics.Net/SystemDrawingPlatform.cs#L152

Something like this perhaps

```<code>var canvas = new GraphicsCanvas(this.CreateGraphics());
</code>```

The other thing you need to do is use the Paint event

```<code>private void Form1_Paint(object sender, PaintEventArgs e)
{
    var graphics = this.CreateGraphics();

    var canvas = new GraphicsCanvas(graphics);

    var skyBrush = new LinearGradientBrush(NGraphics.Point.Zero,
        NGraphics.Point.OneY, Colors.Blue, Colors.White);

    canvas.FillRectangle(new Rect(0, 0, 100, 100), skyBrush);
    canvas.FillEllipse(10, 10, 30, 30, Colors.Yellow);
    canvas.FillRectangle(50, 60, 60, 40, Colors.LightGray);

    canvas.FillPath(new PathOp[] {  new MoveTo (40, 60),
                            new LineTo (120, 60),
                            new LineTo (80, 30),
                            new ClosePath ()
                        }, Colors.Gray);
}
</code>```

Body:
I am trying to draw some geometric shapes using NGraphics in a picture box on a WinForm:

public partial class DrawingForm : Form
{
    public DrawingForm()
    {
        InitializeComponent();
    }

    private void DrawingForm_Load(object sender, EventArgs e)
    {
        var canvas = Platforms.Current.CreateImageCanvas(new NGraphics.Size(100), scale: 2);

        var skyBrush = new LinearGradientBrush(NGraphics.Point.Zero, NGraphics.Point.OneY, Colors.Blue, Colors.White);
        canvas.FillRectangle(new Rect(canvas.Size), skyBrush);
        canvas.FillEllipse(10, 10, 30, 30, Colors.Yellow);
        canvas.FillRectangle(50, 60, 60, 40, Colors.LightGray);
        canvas.FillPath(new PathOp[] {  new MoveTo (40, 60),
                                        new LineTo (120, 60),
                                        new LineTo (80, 30),
                                        new ClosePath ()
                                    }, Colors.Gray);

        this.pictureBox1.Image = (Image)canvas.GetImage();
    }
}

This source code is giving the following exception:

Additional information: Unable to cast object of type 'NGraphics.ImageImage' to type 'System.Drawing.Image'.

This is one problem. Another question is: is it possible to draw shapes directly on the Forms?

Body:
Take a look at the source code for the NGraphics package, it looks like you should construct the GraphicsCanvas based on a standard Graphics context that you could obtain from the form.

https://github.com/praeclarum/NGraphics/blob/master/Platforms/NGraphics.Net/SystemDrawingPlatform.cs#L152

Something like this perhaps

var canvas = new GraphicsCanvas(this.CreateGraphics());

The other thing you need to do is use the Paint event

private void Form1_Paint(object sender, PaintEventArgs e)
{
    var graphics = this.CreateGraphics();

    var canvas = new GraphicsCanvas(graphics);

    var skyBrush = new LinearGradientBrush(NGraphics.Point.Zero,
        NGraphics.Point.OneY, Colors.Blue, Colors.White);

    canvas.FillRectangle(new Rect(0, 0, 100, 100), skyBrush);
    canvas.FillEllipse(10, 10, 30, 30, Colors.Yellow);
    canvas.FillRectangle(50, 60, 60, 40, Colors.LightGray);

    canvas.FillPath(new PathOp[] {  new MoveTo (40, 60),
                            new LineTo (120, 60),
                            new LineTo (80, 30),
                            new ClosePath ()
                        }, Colors.Gray);
}


问:
Spark Dataframe delete to Elasticsearch
I am using Apache Spark DataFrame and I want to Delete data to Elasticsearch.
For adding and updating I am using below command

val esURL = "https://56h874526b6741db87c3c91324g755.westeurope.azure.elastic-cloud.com:9243"
 var indexName =  "test_elastic/test_elastic"
    df.write
      .format("org.elasticsearch.spark.sql")
      .option("es.nodes.wan.only","true")
      .option("es.port","443")
      .option("es.net.ssl","true")
      .option("es.net.http.auth.user","userid")
      .option("es.net.http.auth.pass","pwd")
      .option("es.nodes", esURL)
      .option("es.mapping.id", "primary_key")
      .mode("append")
      .save(indexName)
```

My question is how I can delete some rows from elasticsearch index. In my case elasticsearch index is "test_elastic".

答:
A quick search in the repository mentions first support for deletes on the ElasticSearch Hadoop connector for the 8.x and 7.8 versions, neither of which are currently released the moment I write this.

https://github.com/elastic/elasticsearch-hadoop/pull/1324

From maintainer jbaiera :

jbaiera left a comment •

LGTM! Thanks very much for your dedication on getting this in! I'll go ahead and merge it in to master and backport it to the 7.x branch. It should be available in the 7.8.0 release when that lands.

From the current code changes, supported ES versions should be 2.x to 8.x, but there is no documentation yet that I could find (did not look much though), and no information about a direct usage in the Spark API (and I'm not even sure a delete API exists on Spark Dataframes, whatever their data source).

On the other hand, there exists a write mode called "overwrite", that is working and could allow you achieve data deletion, but overwriting the whole index may not be practical depending on the volumetry.

I think your best bet would be to drop out of the spark dataframe API to switch to one (or several) direct call(s) to bulk delete.

Title: Spark Dataframe delete to Elasticsearch

Body:
I am using Apache Spark DataFrame and I want to Delete data to Elasticsearch.
For adding and updating I am using below command

val esURL = "https://56h874526b6741db87c3c91324g755.westeurope.azure.elastic-cloud.com:9243"
 var indexName =  "test_elastic/test_elastic"
    df.write
      .format("org.elasticsearch.spark.sql")
      .option("es.nodes.wan.only","true")
      .option("es.port","443")
      .option("es.net.ssl","true")
      .option("es.net.http.auth.user","userid")
      .option("es.net.http.auth.pass","pwd")
      .option("es.nodes", esURL)
      .option("es.mapping.id", "primary_key")
      .mode("append")
      .save(indexName)

My question is how I can delete some rows from elasticsearch index. In my case elasticsearch index is "test_elastic".


问:
What are the differences between a WAV file (.wav) and a WAVE audio file (.wave)?
I am trying to use the PyAudio library to record guitar audio through my USB audio interface in a python project. When I use audio applications such as Audacity to save the audio I get a WAV (.wav) file which can be played using apps such as Groove music, windows media player etc. and I am able to manipulate the files as I need.

However, now I need to implement recording into the project and when I use PyAudio to record guitar input, it saves the audio as a WAVE Audio File (.wave) file which cannot be manipulated in the program and cannot be played using the playsound library. When I try to play it from my file manager it will only play using Itunes while Groove music and windows media player don't support it.

Anywhere I check online describes WAVE and WAV files as the same thing so I am unsure why I am having this issue. My code is as shown below. Any help or advice would be appreciated!

```<code>import pyaudio
import wave
from playsound import playsound

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "live_guitar_input.wave"

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

print("NOW RECORDING")

frames = []
for i in range(0, int(RATE/CHUNK*RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

print("Finished Recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
playsound(WAVE_OUTPUT_FILENAME)
</code>```

答: As pointed out by the O.P. "wave" and "wav" are the same thing. But the file manager application does not recognize wave extension. The solution is just to rename the "file.wave" to "file.wav".</p>

Body:
I am trying to use the PyAudio library to record guitar audio through my USB audio interface in a python project. When I use audio applications such as Audacity to save the audio I get a WAV (.wav) file which can be played using apps such as Groove music, windows media player etc. and I am able to manipulate the files as I need.

However, now I need to implement recording into the project and when I use PyAudio to record guitar input, it saves the audio as a WAVE Audio File (.wave) file which cannot be manipulated in the program and cannot be played using the playsound library. When I try to play it from my file manager it will only play using Itunes while Groove music and windows media player don't support it.

Anywhere I check online describes WAVE and WAV files as the same thing so I am unsure why I am having this issue. My code is as shown below. Any help or advice would be appreciated!

import pyaudio
import wave
from playsound import playsound

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "live_guitar_input.wave"

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

print("NOW RECORDING")

frames = []
for i in range(0, int(RATE/CHUNK*RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

print("Finished Recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
playsound(WAVE_OUTPUT_FILENAME)


问:
UISearchBar with a white background is impossible?
I really thought it would be easy to set the background color of my UISearchBar's text field to white. But no matter what I try, it always stays offwhite / light gray (#efeff0).

import UIKit

class ViewController: UIViewController {
  private let searchController = UISearchController()

  override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.title = "Hello World"
    view.backgroundColor = #colorLiteral(red: 0.9588784575, green: 0.9528519511, blue: 0.9350754619, alpha: 1)
    searchController.searchBar.searchTextField.backgroundColor = .white
    navigationItem.searchController = searchController
  }
}
```

How can I make the search bar have a pure white background color? App is iOS 13+, if that helps.

Tiny test project: https://github.com/kevinrenskers/WhiteSearch.

答:
It's possible. Set the background of the search field with a white image.

let size = CGSize(width: searchController.searchBar.frame.size.width - 12, height: searchController.searchBar.frame.size.height - 12)
let backgroundImage = createWhiteBG(size)!
let imageWithCorner = backgroundImage.createImageWithRoundBorder(cornerRadiuos: 10)!

searchController.searchBar.setSearchFieldBackgroundImage(imageWithCorner, for: UIControl.State.normal)
```

<p>If you don't want to input an image to app. Try this for create one programmatically.</p>

<pre class="lang-swift prettyprint-override"><code>func createWhiteBG(_ frame : CGSize) -> UIImage? {
    var rect = CGRect(x: 0, y: 0, width: 0, height: 0)
    rect.size = frame
    UIGraphicsBeginImageContext(rect.size)
    let context = UIGraphicsGetCurrentContext()
    context?.setFillColor(UIColor.white.cgColor)
    context?.fill(rect)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}

extension UIImage {
    func createImageWithRoundBorder(cornerRadiuos : CGFloat) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(self.size, false, scale)
        let rect = CGRect(origin:CGPoint(x: 0, y: 0), size: self.size)
        let context = UIGraphicsGetCurrentContext()

        let path = UIBezierPath(
            roundedRect: rect,
            cornerRadius: cornerRadiuos
        )
        context?.beginPath()
        context?.addPath(path.cgPath)
        context?.closePath()
        context?.clip()
        self.draw(at: CGPoint.zero)
        context?.restoreGState()
        path.lineWidth = 1.5
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}
</code>```

Body:
I really thought it would be easy to set the background color of my UISearchBar's text field to white. But no matter what I try, it always stays offwhite / light gray (#efeff0).

import UIKit

class ViewController: UIViewController {
  private let searchController = UISearchController()

  override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.title = "Hello World"
    view.backgroundColor = #colorLiteral(red: 0.9588784575, green: 0.9528519511, blue: 0.9350754619, alpha: 1)
    searchController.searchBar.searchTextField.backgroundColor = .white
    navigationItem.searchController = searchController
  }
}

How can I make the search bar have a pure white background color? App is iOS 13+, if that helps.

Tiny test project: https://github.com/kevinrenskers/WhiteSearch.

Body:
It's possible. Set the background of the search field with a white image.

let size = CGSize(width: searchController.searchBar.frame.size.width - 12, height: searchController.searchBar.frame.size.height - 12)
let backgroundImage = createWhiteBG(size)!
let imageWithCorner = backgroundImage.createImageWithRoundBorder(cornerRadiuos: 10)!

searchController.searchBar.setSearchFieldBackgroundImage(imageWithCorner, for: UIControl.State.normal)

If you don't want to input an image to app. Try this for create one programmatically.

func createWhiteBG(_ frame : CGSize) -> UIImage? {
    var rect = CGRect(x: 0, y: 0, width: 0, height: 0)
    rect.size = frame
    UIGraphicsBeginImageContext(rect.size)
    let context = UIGraphicsGetCurrentContext()
    context?.setFillColor(UIColor.white.cgColor)
    context?.fill(rect)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}

extension UIImage {
    func createImageWithRoundBorder(cornerRadiuos : CGFloat) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(self.size, false, scale)
        let rect = CGRect(origin:CGPoint(x: 0, y: 0), size: self.size)
        let context = UIGraphicsGetCurrentContext()

        let path = UIBezierPath(
            roundedRect: rect,
            cornerRadius: cornerRadiuos
        )
        context?.beginPath()
        context?.addPath(path.cgPath)
        context?.closePath()
        context?.clip()
        self.draw(at: CGPoint.zero)
        context?.restoreGState()
        path.lineWidth = 1.5
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}


问:
databases and data not saving ~Linux QubeOS~
when i create a postgresql database and create tables and columns and even insert data into the columns. I cant restart my machine without losing the created databases and all the data.

i have tried changing a coupe things in the configuration file but nothing helped.

I also have to reset the password for postgres everytime I restart my machine. I mainly use mongodb I am just learning postgreSQL just so I can use it if I ever need to in the future. I am runing a Linux machine QubesOS. I have a few problems like this useing QubesOS. every tutorial I watch everybody uses Macs. Which a mac seems good and all kinda a mix between windows and linux The best of both worlds. Easy package installs and terminal control but I dont want to trade my linux machine for a Mac I would much rather just fix these problems I am having with PostgreSQL on my linux machine

答:
You ran into an important security feature of QubesOS:  All data modifications are discarded on shutdown of a so called "Qube".  They are reset to their original state.

But there is the exception of data kept in some very special directories.
If you convince your data base packages to put their data into these directories, it will be preserved over reboots of your data base Qube:
Read this documentation for more information.


问:
how do I pass information from one class to another
I am creating a program which allows the user to input details of customers. When they have saved each customers record there is the choice to add additional information. I am having trouble getting the the name of the saved file in my append class. I need the filename so I  can then save the additional information to the same file already created for the customer. How do I pass the file name from one file to another.

```<code>File FName = fileChooser.getSelectedFile();
      String name = FName.getName();

 public String getname() { return name; }
</code>```

This code is in my customer class how do I get this information in my append class??

答:
Possibly something like this:

```<code>Customer customer = new Customer();
// do some stuff with your customer object, including initiating the File and saving its name to a String field called name
Append append = new Append();
append.foo(customer.getName()); // passes the name of the file to the foo method of class Append
</code>```

This assumes that you'll only want the name of the file in that one method (though you could save it to a field as part of method foo()). You'd need to implement a method foo(String name) in class Append.

Another option would be to pass it as a constructor of Append:

```<code>Append append = new Append(customer.getName());
append.foo();
</code>```

For this, you'd need to implement a constructor Append(String name) in class Append.

Body:
I am creating a program which allows the user to input details of customers. When they have saved each customers record there is the choice to add additional information. I am having trouble getting the the name of the saved file in my append class. I need the filename so I  can then save the additional information to the same file already created for the customer. How do I pass the file name from one file to another.

File FName = fileChooser.getSelectedFile();
      String name = FName.getName();

 public String getname() { return name; }

This code is in my customer class how do I get this information in my append class??

Body:
Possibly something like this:

Customer customer = new Customer();
// do some stuff with your customer object, including initiating the File and saving its name to a String field called name
Append append = new Append();
append.foo(customer.getName()); // passes the name of the file to the foo method of class Append

This assumes that you'll only want the name of the file in that one method (though you could save it to a field as part of method foo()). You'd need to implement a method foo(String name) in class Append.

Another option would be to pass it as a constructor of Append:

Append append = new Append(customer.getName());
append.foo();

For this, you'd need to implement a constructor Append(String name) in class Append.


问:
What are all possible reasons for ie11 memory leaks?
I have a SPA application that works great without memory leaks in chrome.

However, IE11 (Windows 10) crashes every 15 minutes.

Please don't tell me IE11 is deprecated. My company supports IE11 and our customers are using IE11.

I know IFrames cause memory leaks on IE11.

I heard gifs cause memory leaks as well on IE11, Is it true?

From your experience:

What are the reasons that might cause IE11 to have a memory leak?

How to avoid those memory leaks?

Is there a good valid way without interrupting user experience to "release" memory leaks on IE every x minutes?

I would like to collect here all possible reasons for IE11 memory leak.

答:
What are the reasons that might cause IE11 to have a memory leak?

There are many reasons that can cause the memory leaks, here we don't have any information about your SPA so it is hard for us to say what caused the memory leak in it.

I suggest you visit the following links that may give you an idea about the possible causes of memory leaks.

Memory Leakage in Internet Explorer - Revisited

Edge/Internet Explorer memory leak

How to avoid those memory leaks?

The links that I have shared in the 1st point will also give suggestions to avoid the leaks.

I tried to refer to the official Microsoft docs on this topic. I found that links in those docs are broken.

Tools for Detecting Memory Leaks

JavaScript Memory Leak Detector for Internet Explorer

Is there a good valid way without interrupting user experience to "release" memory leaks on IE every x minutes?

You may need to refresh the page. In some situations, it can work. Obviously, the user will be interrupted.

Here is an example:

```<code>var startTime, endTime;

function start() {
    startTime = new Date();
};

function end() {
    endTime = new Date();
    var timeDiff = endTime - startTime; //in ms
    // strip the ms
    timeDiff /= 1000;

    // get seconds
    var seconds = Math.round(timeDiff);
    console.log(seconds + " seconds");

    if (seconds > 60)
        console.log("IE11 just froze. We need to refresh.");
}

start();

setInterval(function () {
    end();

    start();
}, 1000);
</code>```

Detect when IE11, with its built-in memory leak, runs out of memory (1.5GB recyclable pool)

Body:
What are the reasons that might cause IE11 to have a memory leak?

There are many reasons that can cause the memory leaks, here we don't have any information about your SPA so it is hard for us to say what caused the memory leak in it.

I suggest you visit the following links that may give you an idea about the possible causes of memory leaks.

Memory Leakage in Internet Explorer - Revisited

Edge/Internet Explorer memory leak

How to avoid those memory leaks?

The links that I have shared in the 1st point will also give suggestions to avoid the leaks.

I tried to refer to the official Microsoft docs on this topic. I found that links in those docs are broken.

Tools for Detecting Memory Leaks

JavaScript Memory Leak Detector for Internet Explorer

Is there a good valid way without interrupting user experience to "release" memory leaks on IE every x minutes?

You may need to refresh the page. In some situations, it can work. Obviously, the user will be interrupted.

Here is an example:

var startTime, endTime;

function start() {
    startTime = new Date();
};

function end() {
    endTime = new Date();
    var timeDiff = endTime - startTime; //in ms
    // strip the ms
    timeDiff /= 1000;

    // get seconds
    var seconds = Math.round(timeDiff);
    console.log(seconds + " seconds");

    if (seconds > 60)
        console.log("IE11 just froze. We need to refresh.");
}

start();

setInterval(function () {
    end();

    start();
}, 1000);

Detect when IE11, with its built-in memory leak, runs out of memory (1.5GB recyclable pool)


问:
How should I run compensations/rollback steps for a Saga Orchestration with Axon Framework?
For a use case where I want to implement a Saga Orchestration for a couple services with Axon, I've built:

order-service (saga orchestrator with Spring boot + Axon Framework)

payment-service (microservice)

shipping-service (microservice)

Then I have a class annotated with @Saga with 3 steps/event handlers:

Order created (first service)

Payment done (second service)

Order shipped (third service)

Order effectively created

My question is how I'm supposed to rollback/compensate all previous executed steps if, for example, shipping service fails?

From documentation I've got some doubts on:

do I need to create a new class with @Saga?

on the service that failed should I throw an Exception or send error to another Command/Event

how should I call SagaLifecycle.end()

That would be great to have a solution showing some code. Thanks!

答:
A well implemented Saga can deal with any faulty scenarios occurring from the transaction said Saga is managing. Thus, upon any operation dispatched from within the saga, you should be able to expect an exceptional case which you would react on. It is this reaction which is the compensating action you are looking for.

Now, to go over you exact questions:

do I need to create a new class with @Saga?

Pretty confident that you do not need a new saga to resolve the exceptional cases in your domain. So no.

on the service that failed should I throw an Exception or send error to another Command/Event

I would go either with an exception or an event here, not a command (as an (Axon) Saga does not handle commands). Whether you go either route depends on whether the event is a valuable business occurrence, thus requires to be stored indefinite in an event. Using an event will however mean you are splitting the fault tolerant behaviour of your Saga between distinct saga event handlers, which I personally wouldn't prefer. Thus, throwing an exception from one of the services to be handled by the saga would have my preference. Subsequently, if you need to store the exceptional occurrence, just publish an event next to it.

how should I call SagaLifecycle.end()

Not sure what you are looking for with this question to be honest.
The SagaLifecycle.end() should be called once the Saga's lifecycle has ended. Thus, when that transaction is done. When it is done is entirely up to your domain and note something necessitated by the fact you need to dispatch a compensating action.

To clarify my intent, here's some (pseudo)code showing where I would perform the compensating action:

private transient CommandGateway commandGateway;

@SagaEventHandler(assocationProperty = "some-association)
public void on(SomeEvent event) {
    // Validate/set state if necessary
    commandGateway.send(new SomeCommand(...))
                  .exceptionally(exception -> {
                      // Dispatch compensating action through service/CommandGateway
                  });
}
```


问:
Web Applications Converted To Desktop Applications
I have been reading some of the posts here, but haven't really seen the answers to my questions directly.  I am a web developer and need to integrate some of my web applications to some sort of desktop application.  For example, say a business has some kind of booking, it needs to be available offline (desktop in office/stores) and online, with the master database offline.  What I would like to know is the best way in doing something like this and different options.  If I can use web technology like PHP/MySQL and then use something like WinBinder to be able to handle all the work, then great, but from my research, I get the impression this is not a great approach.  PHP/MySQL is what I mainly use for backend development, however know some other languages, just haven't mastered them yet.

Can you guys suggest some methods of acheiving what I need and what languages, etc are the best?  Can I stick with web technologies, but create simple install packages so clients can install the application easily?

Thanks in advance for your help.

答:
It sounds like you need a Rich Internet Application.  Here is a good explanation.

http://searchsoa.techtarget.com/definition/Rich-Internet-Application-RIA

Microsoft Silverlight has one of the best offerings because they can run integrated within a web page as well as a desktop application.

Java Web Start and Flash are similar offerrings as well.

EDIT: I just want to say that PHP is all kinds of wrong for this type of solution.


问:
How to merge flow and channel in Kotlin?
I need to create an API, it should be flow, which collects events. The problem is that these events may be from a channel (I need an analog for PublishSubject) and from a flow (which does a network request).

I also not sure if it's the best solution, so let me know if I can make it better.

What am I doing:

My api:

```<code>override val statusFlow = trackStatus()

private fun trackStatus(): Flow<State> = flow { ... }

private val deviceChannel = Channel<State>(CONFLATED)
</code>```

So statusFlow should return a flow from which I can receive data from both flow and channel.

I tried to convert the channel to flow by consumeAsflow, but it doesn't work.

I see a solution as

```<code>private fun trackStatus(): Flow<State> = flowOf(channel.toFlow(), flow).flattenMerge()
</code>```

What is the proper way to do it?

答:
The solution for this case is merge(), as noticed in the province answer, but it won't work like that.
You should use BroadcastChannel instead of Channel as the last one can give only one subscription during a lifetime. Also, you should use asFlow() to transform such channel to the flow.</p>

Body:
I need to create an API, it should be flow, which collects events. The problem is that these events may be from a channel (I need an analog for PublishSubject) and from a flow (which does a network request).

I also not sure if it's the best solution, so let me know if I can make it better.

What am I doing:

My api:

override val statusFlow = trackStatus()

private fun trackStatus(): Flow<State> = flow { ... }

private val deviceChannel = Channel<State>(CONFLATED)

So statusFlow should return a flow from which I can receive data from both flow and channel.

I tried to convert the channel to flow by consumeAsflow, but it doesn't work.

I see a solution as

private fun trackStatus(): Flow<State> = flowOf(channel.toFlow(), flow).flattenMerge()

What is the proper way to do it?


问:
How to use replaceAll when input contains spaces
I have a newbie question about replaceAll method on String. It works fine as long as the input does not contain any type of space (breaking/non-breaking etc).

How to sanitize the input so it covers all cases for special space characters and I can use something like this:

```<code>String replaced = replaced.replaceAll("my-test (2)", "test"); // not working
</code>```

I tried various types of regex with \\s, \u00A0 etc.

EDIT: I noticed that the braces are also causing some problems with replaceAll.

This is my case:

```<code>"my-value (2)".replaceAll("my-value (2)", "test);
</code>```

答:
Instead of using replaceAll() method, you can use replace(CharSequence target, CharSequence replacement). This will remove all the occurrence of the given string with new one.
EX.

```<code>String sub=s.replace("my-test (2)", "test");
</code>```

Body:
I have a newbie question about replaceAll method on String. It works fine as long as the input does not contain any type of space (breaking/non-breaking etc).

How to sanitize the input so it covers all cases for special space characters and I can use something like this:

String replaced = replaced.replaceAll("my-test (2)", "test"); // not working

I tried various types of regex with \\s, \u00A0 etc.

EDIT: I noticed that the braces are also causing some problems with replaceAll.

This is my case:

"my-value (2)".replaceAll("my-value (2)", "test);

Body:
Instead of using replaceAll() method, you can use replace(CharSequence target, CharSequence replacement). This will remove all the occurrence of the given string with new one.
EX.

String sub=s.replace("my-test (2)", "test");


问:
How to retrieve elements in foreach loop in Mule4?
I have defined a variable to keep application/json collection.

```<code><set-variable value="#[payload.'IntegrationEntities'.'amendmentId']" doc:name="AmendmentIds" doc:id="03b6c46a-fc7b-43d4-b23a-502146ef0b13" variableName="amendmentids"/>
<logger level="INFO" doc:name="Logger" doc:id="6a1ad892-65f9-4dd2-9891-bdf3ad64c908" message="#[vars.amendmentids]" />
</code>```

It prints as;

```<code>[
  "8a9a84b76b5a5a59016b687bae35012e",
  "8a9a84b76b5a5a59016b6888e90e0144"
]
</code>```

Then I use ForEach loop to define few process logic for each Id,
Within foreach loop how I can get, each above id?
I used,vars.amendmentids[vars.counter]], but getting following error[1]

```<code><foreach doc:name="For Each" doc:id="7b741315-aa28-4704-82f0-629c21d93853" collection="#[vars.amendmentids]">
            <logger level="INFO" doc:name="Logger" doc:id="049c3137-2f92-4077-8e3f-b26516cc5528" message="#[vars.amendmentids[vars.counter]]"/>

        </foreach>
</code>```

[1]

```<code>Message               : "Internal execution exception while executing the script, this is most probably a bug, file an issue with the script and the input data.
Caused by:
java.lang.RuntimeException: Unable to infer a output media type as more than one is being used: application/json,application/java please specify using: output <your mime-type> --- <expr>
    at org.mule.weave.v2.el.MuleDataWeaveHelper$.inferImplicitOutput(MuleDataWeaveHelper.scala:69)
.............
" evaluating expression: "vars.amendmentids[vars.counter]".
Error type            : MULE:EXPRESSION
</code>```

答:
you need to access the payload only in foreach scope:

```<code><foreach doc:name="For Each" collection="#[vars.amendmentids]">
  <logger level="INFO" doc:name="Logger" message="#[payload]"/>
</foreach>
</code>```

As in foreach each element of your collection will be the payload.

Body:
I have defined a variable to keep application/json collection.

<set-variable value="#[payload.'IntegrationEntities'.'amendmentId']" doc:name="AmendmentIds" doc:id="03b6c46a-fc7b-43d4-b23a-502146ef0b13" variableName="amendmentids"/>
<logger level="INFO" doc:name="Logger" doc:id="6a1ad892-65f9-4dd2-9891-bdf3ad64c908" message="#[vars.amendmentids]" />

It prints as;

[
  "8a9a84b76b5a5a59016b687bae35012e",
  "8a9a84b76b5a5a59016b6888e90e0144"
]

Then I use ForEach loop to define few process logic for each Id,
Within foreach loop how I can get, each above id?
I used,vars.amendmentids[vars.counter]], but getting following error[1]

<foreach doc:name="For Each" doc:id="7b741315-aa28-4704-82f0-629c21d93853" collection="#[vars.amendmentids]">
            <logger level="INFO" doc:name="Logger" doc:id="049c3137-2f92-4077-8e3f-b26516cc5528" message="#[vars.amendmentids[vars.counter]]"/>

        </foreach>

[1]

Message               : "Internal execution exception while executing the script, this is most probably a bug, file an issue with the script and the input data.
Caused by:
java.lang.RuntimeException: Unable to infer a output media type as more than one is being used: application/json,application/java please specify using: output <your mime-type> --- <expr>
    at org.mule.weave.v2.el.MuleDataWeaveHelper$.inferImplicitOutput(MuleDataWeaveHelper.scala:69)
.............
" evaluating expression: "vars.amendmentids[vars.counter]".
Error type            : MULE:EXPRESSION

Body:
you need to access the payload only in foreach scope:

<foreach doc:name="For Each" collection="#[vars.amendmentids]">
  <logger level="INFO" doc:name="Logger" message="#[payload]"/>
</foreach>

As in foreach each element of your collection will be the payload.


问:
Date difference in years in PySpark dataframe
I come from Pandas background and new to Spark. I have a dataframe which has id, dob, age as columns. I want to get the age of the user from his dob (in some cases age column is NULL).

```<code>+----+------+----------+
| id | age  |   dob    |
+----+------+----------+
|  1 | 24   | NULL     |
|  2 | 25   | NULL     |
|  3 | NULL | 1/1/1973 |
|  4 | NULL | 6/6/1980 |
|  5 | 46   |          |
|  6 | NULL | 1/1/1971 |
+----+------+----------+
</code>```

I want a new column which will calculate age from dob and current date.

I tried this, but not getting any results from it:

```<code>df.withColumn("diff",
              datediff(to_date(lit("01-06-2020")),
                       to_date(unix_timestamp('dob', "dd-MM-yyyy").cast("timestamp")))).show()
</code>```

答:
You need to compute the date difference and convert the result to years, something like this:

```<code>df.withColumn('diff',
    when(col('age').isNull(),
         floor(datediff(current_date(), to_date(col('dob'), 'M/d/yyyy'))/365.25))\
  .otherwise(col('age'))).show()
</code>```

Which produces:

```<code>+---+----+--------+----+
| id| age|     dob|diff|
+---+----+--------+----+
|  1|  24|    null|  24|
|  2|  25|    null|  25|
|  3|null|1/1/1973|  47|
|  4|null|6/6/1980|  39|
|  5|  46|    null|  46|
|  6|null|1/1/1971|  49|
+---+----+--------+----+
</code>```

It preserves the age column where not null and computes the difference (in days) between dob and today where age is null. The result is then converted to years (by dividing by 365.25; you may want to confirm this) then floored.

Body:
I come from Pandas background and new to Spark. I have a dataframe which has id, dob, age as columns. I want to get the age of the user from his dob (in some cases age column is NULL).

+----+------+----------+
| id | age  |   dob    |
+----+------+----------+
|  1 | 24   | NULL     |
|  2 | 25   | NULL     |
|  3 | NULL | 1/1/1973 |
|  4 | NULL | 6/6/1980 |
|  5 | 46   |          |
|  6 | NULL | 1/1/1971 |
+----+------+----------+

I want a new column which will calculate age from dob and current date.

I tried this, but not getting any results from it:

df.withColumn("diff",
              datediff(to_date(lit("01-06-2020")),
                       to_date(unix_timestamp('dob', "dd-MM-yyyy").cast("timestamp")))).show()

Body:
You need to compute the date difference and convert the result to years, something like this:

df.withColumn('diff',
    when(col('age').isNull(),
         floor(datediff(current_date(), to_date(col('dob'), 'M/d/yyyy'))/365.25))\
  .otherwise(col('age'))).show()

Which produces:

+---+----+--------+----+
| id| age|     dob|diff|
+---+----+--------+----+
|  1|  24|    null|  24|
|  2|  25|    null|  25|
|  3|null|1/1/1973|  47|
|  4|null|6/6/1980|  39|
|  5|  46|    null|  46|
|  6|null|1/1/1971|  49|
+---+----+--------+----+

It preserves the age column where not null and computes the difference (in days) between dob and today where age is null. The result is then converted to years (by dividing by 365.25; you may want to confirm this) then floored.


问:
Javascript invalid label error
I am sorry if this question is a repeat of someother. I have looked into some of them but they don't answer my particular question.

I get an "invalid label" error where I am printing my alert statement in the code below:

```<code>    $(document).ready(
    function(){
        if( $('map#map').length > 0 ){
            //alert('found a map!');
            $('map#map area').each($area,
                function(i, val){
                    alert('Found: ' + val ):
                }
            );
        }
    }
);
</code>```

I get the same error is I do the following: alert('Found: ' + $(this) );

Can anyone tell me why this is happening, please?

ps: the elements I am attempting to read are as follows:

```<code><map id="map" name="imgmap20116293122">
<area alt="" coords="11,76,97,127" href="" shape="rect" target="" title="" />
<area alt="" coords="12,28,96,74" href="" shape="rect" target="" title="" />
<area alt="" coords="100,28,160,73" href="" shape="rect" target="" title="" />
<area alt="" coords="162,28,221,73" href="" shape="rect" target="" title="" />
<area alt="" coords="502,239,549,282" href="" shape="rect" target="" title="" />
<area alt="" coords="473,284,554,330" href="" shape="rect" target="" title="" /-->
</code>```

答:
You put a colon in stead of a semicolon:</p>

```<code>alert('Found: ' + val );
</code>```

Title: Javascript invalid label error

Body:
I am sorry if this question is a repeat of someother. I have looked into some of them but they don't answer my particular question.

I get an "invalid label" error where I am printing my alert statement in the code below:

    $(document).ready(
    function(){
        if( $('map#map').length > 0 ){
            //alert('found a map!');
            $('map#map area').each($area,
                function(i, val){
                    alert('Found: ' + val ):
                }
            );
        }
    }
);

I get the same error is I do the following: alert('Found: ' + $(this) );

Can anyone tell me why this is happening, please?

ps: the elements I am attempting to read are as follows:

<map id="map" name="imgmap20116293122">
<area alt="" coords="11,76,97,127" href="" shape="rect" target="" title="" />
<area alt="" coords="12,28,96,74" href="" shape="rect" target="" title="" />
<area alt="" coords="100,28,160,73" href="" shape="rect" target="" title="" />
<area alt="" coords="162,28,221,73" href="" shape="rect" target="" title="" />
<area alt="" coords="502,239,549,282" href="" shape="rect" target="" title="" />
<area alt="" coords="473,284,554,330" href="" shape="rect" target="" title="" /-->

Body:
You put a colon in stead of a semicolon:

alert('Found: ' + val );


问:
Stream uploaded file via flask API to MinIO storage
In our flask API, we have an endpoint for uploading a document. This endpoint receives the uploaded document, does some checks and uploads this document to MinIO.
We want to stream the received document directly to the remote storage without actually processing it via the API.

One idea is to do the following:

```<code>@app.route('/upload', methods=['POST'])
def upload():
   upload_url = get_presigned_upload_url()
   response = requests.put(url=upload_url, files={'file': request.stream})
</code>```

I can see two problems in the above code:

1- How can I make sure that the stream consists of only one file

2- How can I extract the mimetype from the actual file, without just trusting the file extension

答:
Following the suggestion in here for uploading large files, I was able to get all the info that I need including mimetype and number of files uploaded.

The code that I have used:

```<code>@app.route('/upload', methods=['POST'])
def upload():
   upload_url = get_presigned_upload_url()

   def custom_stream_factory(total_content_length, filename, content_type, content_length=None):
    import tempfile
    tmpfile = tempfile.NamedTemporaryFile('wb+', prefix='flaskapp', suffix='.nc')
    return tmpfile

    import werkzeug, flask
    stream, form, files = werkzeug.formparser.parse_form_data(flask.request.environ,
       stream_factory=custom_stream_factory)

     files_list = []
     for fil in files.values():
         files_list.append(
           ('file', (fil.filename, fil, fil.mimetype))
         )
         break
     response = requests.put(url=upload_url, files=files_list)
</code>```

Body:
In our flask API, we have an endpoint for uploading a document. This endpoint receives the uploaded document, does some checks and uploads this document to MinIO.
We want to stream the received document directly to the remote storage without actually processing it via the API.

One idea is to do the following:

@app.route('/upload', methods=['POST'])
def upload():
   upload_url = get_presigned_upload_url()
   response = requests.put(url=upload_url, files={'file': request.stream})

I can see two problems in the above code:

1- How can I make sure that the stream consists of only one file

2- How can I extract the mimetype from the actual file, without just trusting the file extension

Body:
Following the suggestion in here for uploading large files, I was able to get all the info that I need including mimetype and number of files uploaded.

The code that I have used:

@app.route('/upload', methods=['POST'])
def upload():
   upload_url = get_presigned_upload_url()

   def custom_stream_factory(total_content_length, filename, content_type, content_length=None):
    import tempfile
    tmpfile = tempfile.NamedTemporaryFile('wb+', prefix='flaskapp', suffix='.nc')
    return tmpfile

    import werkzeug, flask
    stream, form, files = werkzeug.formparser.parse_form_data(flask.request.environ,
       stream_factory=custom_stream_factory)

     files_list = []
     for fil in files.values():
         files_list.append(
           ('file', (fil.filename, fil, fil.mimetype))
         )
         break
     response = requests.put(url=upload_url, files=files_list)


问:
Loading of dependency in gradle
I am about to setup a new Gradle project in Intellij Idea.
But I am alrady failing at loading dependencies.
This is my gradle file:

```<code>plugins {
    id 'java'
}

group 'ch.demo'
version '7.4.5.0'

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'com.google.gwt', name: 'gwt', version: '2.9.0'
}
</code>```

If I execute this gradle script, I get the error 'Could not resolve com.google.gwt:gwt:2.9.0.'

The maven module should be correct, it's available here:
https://repo.maven.apache.org/maven2/com/google/gwt/gwt/2.9.0/

It seems I am doing something wrong. Does anyone know how to solve this?

Also tried compile 'com.google.gwt:gwt:2.9.0' but that didn't work either.

Edit:

I used the command "Reimport all Gradle Projects" so far. If I press "Execute Gradle Task" -> "gradle build", I get the following error:

```<code>Execution failed for task ':compileJava'.
> Could not resolve all files for configuration ':compileClasspath'.
   > Could not resolve com.google.gwt:gwt:2.9.0.
     Required by:
         project :
      > Could not resolve com.google.gwt:gwt:2.9.0.
         > Could not get resource 'https://repo.maven.apache.org/maven2/com/google/gwt/gwt/2.9.0/gwt-2.9.0.pom'.
            > Could not GET 'https://repo.maven.apache.org/maven2/com/google/gwt/gwt/2.9.0/gwt-2.9.0.pom'.
               > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

</code>```

答:
Try like this:

```<code>dependencies {
       implementation 'com.google.gwt:gwt:2.9.0'
}
</code>```

It is recommended to use implementation instead of compile. Further on that can be found here:

What's the difference between implementation and compile in Gradle?

update:
I just tried in my machine and this works fine:

Create a new gradle project via IntelliJ

Modify your gradle.build to look like this:

```<code>  plugins {
            id 'java'
        }

    group 'org.example'
    version '1.0-SNAPSHOT'

    repositories {
        mavenCentral()
    }

    dependencies {
        implementation 'com.google.gwt:gwt:2.9.0'
    }
</code>```

Demostration how I created the project and message on terminal saying that build passed:

Title: Loading of dependency in gradle

Body:
I am about to setup a new Gradle project in Intellij Idea.
But I am alrady failing at loading dependencies.
This is my gradle file:

plugins {
    id 'java'
}

group 'ch.demo'
version '7.4.5.0'

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'com.google.gwt', name: 'gwt', version: '2.9.0'
}

If I execute this gradle script, I get the error 'Could not resolve com.google.gwt:gwt:2.9.0.'

The maven module should be correct, it's available here:
https://repo.maven.apache.org/maven2/com/google/gwt/gwt/2.9.0/

It seems I am doing something wrong. Does anyone know how to solve this?

Also tried compile 'com.google.gwt:gwt:2.9.0' but that didn't work either.

Edit:

I used the command "Reimport all Gradle Projects" so far. If I press "Execute Gradle Task" -> "gradle build", I get the following error:

Execution failed for task ':compileJava'.
> Could not resolve all files for configuration ':compileClasspath'.
   > Could not resolve com.google.gwt:gwt:2.9.0.
     Required by:
         project :
      > Could not resolve com.google.gwt:gwt:2.9.0.
         > Could not get resource 'https://repo.maven.apache.org/maven2/com/google/gwt/gwt/2.9.0/gwt-2.9.0.pom'.
            > Could not GET 'https://repo.maven.apache.org/maven2/com/google/gwt/gwt/2.9.0/gwt-2.9.0.pom'.
               > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Body:
Try like this:

dependencies {
       implementation 'com.google.gwt:gwt:2.9.0'
}

It is recommended to use implementation instead of compile. Further on that can be found here:

What's the difference between implementation and compile in Gradle?

update:
I just tried in my machine and this works fine:

Create a new gradle project via IntelliJ

Modify your gradle.build to look like this:

  plugins {
            id 'java'
        }

    group 'org.example'
    version '1.0-SNAPSHOT'

    repositories {
        mavenCentral()
    }

    dependencies {
        implementation 'com.google.gwt:gwt:2.9.0'
    }

Demostration how I created the project and message on terminal saying that build passed:


问:
Cannot send firebase push notification from lambda
I am hoping someone can help me point my mistake here.

I am trying to send a firebase push notification through a lambda using the HTTP legacy endpoint

https://fcm.googleapis.com/fcm/send

I am following the guide from:
https://craigrussell.io/2019/03/send-firebase-fcm-push-notification-from-aws-lambda/

Here is my code:

```<code>const authHeader ='key=A****IV';
const deviceToken ='eut4****pm';
</code>```

```<code>  console.log('sending Push notification');
  return new Promise((resolve, reject) => {
    const options = {
      host: 'fcm.googleapis.com',
      path: '/fcm/send',
      method: 'POST',
      headers: {
        'Authorization': authHeader,
        'Content-Type': 'application/json',
      },
    };

    const req = http.request(options, (res) => {
      console.log('success');
      resolve('success');
    });

    req.on('error', (e) => {
      console.log('failuree' + e.message);
      reject(e.message);
    });

    // const reqBody = '{"to":"' + deviceToken + '", "priority" : "high"}';
    const reqBody = '{"to":"' + deviceToken + '", "priority": "high", "notification": {"title": "Test", "body": "Test"}}';
    console.log(reqBody);

    req.write(reqBody);
    req.end();
  });
};
</code>```

I do not receive any push notification after this . Am i doing something wrong here?

答:
I think the key point is that you use the http module. Actually, it works well when using https module on my side.

```<code>var https = require('https');
</code>```

The complete code is as follows:

```<code>var https = require('https');
exports.handler = async(event) => {
const authHeader = 'key=AA***y';
const deviceToken = 'fG***-';
return new Promise((resolve, reject) => {
    const options = {
        host: 'fcm.googleapis.com',
        path: '/fcm/send',
        method: 'POST',
        headers: {
            'Authorization': authHeader,
            'Content-Type': 'application/json',
        },
    };

    console.log(options);
    const req = https.request(options, (res) => {
        console.log('success');
        console.log(res.statusCode);
        resolve('success');
    });

    req.on('error', (e) => {
        console.log('failuree' + e.message);
        reject(e.message);
    });

    // const reqBody = '{"to":"' + deviceToken + '", "priority" : "high"}';
    const reqBody = '{"to":"' + deviceToken + '", "priority": "high", "notification": {"title": "Test", "body": "Test"}}';
    console.log(reqBody);

    req.write(reqBody);
    req.end();
});
};
</code>```

For more details, you can see the res field after http request, it will show statusCode 403 when you use http.

Body:
I am hoping someone can help me point my mistake here.

I am trying to send a firebase push notification through a lambda using the HTTP legacy endpoint

https://fcm.googleapis.com/fcm/send

I am following the guide from:
https://craigrussell.io/2019/03/send-firebase-fcm-push-notification-from-aws-lambda/

Here is my code:

const authHeader ='key=A****IV';
const deviceToken ='eut4****pm';

  console.log('sending Push notification');
  return new Promise((resolve, reject) => {
    const options = {
      host: 'fcm.googleapis.com',
      path: '/fcm/send',
      method: 'POST',
      headers: {
        'Authorization': authHeader,
        'Content-Type': 'application/json',
      },
    };

    const req = http.request(options, (res) => {
      console.log('success');
      resolve('success');
    });

    req.on('error', (e) => {
      console.log('failuree' + e.message);
      reject(e.message);
    });

    // const reqBody = '{"to":"' + deviceToken + '", "priority" : "high"}';
    const reqBody = '{"to":"' + deviceToken + '", "priority": "high", "notification": {"title": "Test", "body": "Test"}}';
    console.log(reqBody);

    req.write(reqBody);
    req.end();
  });
};

I do not receive any push notification after this . Am i doing something wrong here?

Body:
I think the key point is that you use the http module. Actually, it works well when using https module on my side.

var https = require('https');

The complete code is as follows:

var https = require('https');
exports.handler = async(event) => {
const authHeader = 'key=AA***y';
const deviceToken = 'fG***-';
return new Promise((resolve, reject) => {
    const options = {
        host: 'fcm.googleapis.com',
        path: '/fcm/send',
        method: 'POST',
        headers: {
            'Authorization': authHeader,
            'Content-Type': 'application/json',
        },
    };

    console.log(options);
    const req = https.request(options, (res) => {
        console.log('success');
        console.log(res.statusCode);
        resolve('success');
    });

    req.on('error', (e) => {
        console.log('failuree' + e.message);
        reject(e.message);
    });

    // const reqBody = '{"to":"' + deviceToken + '", "priority" : "high"}';
    const reqBody = '{"to":"' + deviceToken + '", "priority": "high", "notification": {"title": "Test", "body": "Test"}}';
    console.log(reqBody);

    req.write(reqBody);
    req.end();
});
};

For more details, you can see the res field after http request, it will show statusCode 403 when you use http.


问:
pyqt5 - How to put multiple UI classes to one UI together
imagine i have a window with a lot of widgets and i dont want to have one big class, but several small classes.
How can i write in in a main.py that content of both classes should show up in one window window side by side?
I dont want multiple windows in one window.
I only want all widgets together in one window
I am creating my classes with the QTDesigner.

Example:
person.py

```<code># -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'person.ui'
#
# Created by: PyQt5 UI code generator 5.14.2
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(467, 300)
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(10, 40, 51, 16))
        self.label.setObjectName("label")
        self.lineEdit = QtWidgets.QLineEdit(Form)
        self.lineEdit.setGeometry(QtCore.QRect(80, 40, 71, 20))
        self.lineEdit.setObjectName("lineEdit")
        self.label_2 = QtWidgets.QLabel(Form)
        self.label_2.setGeometry(QtCore.QRect(10, 80, 51, 16))
        self.label_2.setObjectName("label_2")
        self.lineEdit_2 = QtWidgets.QLineEdit(Form)
        self.lineEdit_2.setGeometry(QtCore.QRect(80, 80, 71, 20))
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.lineEdit_3 = QtWidgets.QLineEdit(Form)
        self.lineEdit_3.setGeometry(QtCore.QRect(80, 10, 71, 20))
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.label_3 = QtWidgets.QLabel(Form)
        self.label_3.setGeometry(QtCore.QRect(10, 10, 51, 16))
        self.label_3.setObjectName("label_3")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label.setText(_translate("Form", "First name"))
        self.label_2.setText(_translate("Form", "Last name"))
        self.label_3.setText(_translate("Form", "Salutation"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())
</code>```

address.py

```<code># -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'address.ui'
#
# Created by: PyQt5 UI code generator 5.14.2
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(467, 300)
        self.label_4 = QtWidgets.QLabel(Form)
        self.label_4.setGeometry(QtCore.QRect(290, 20, 51, 16))
        self.label_4.setObjectName("label_4")
        self.lineEdit_6 = QtWidgets.QLineEdit(Form)
        self.lineEdit_6.setGeometry(QtCore.QRect(370, 90, 71, 20))
        self.lineEdit_6.setObjectName("lineEdit_6")
        self.label_5 = QtWidgets.QLabel(Form)
        self.label_5.setGeometry(QtCore.QRect(290, 50, 71, 16))
        self.label_5.setObjectName("label_5")
        self.lineEdit_4 = QtWidgets.QLineEdit(Form)
        self.lineEdit_4.setGeometry(QtCore.QRect(340, 20, 71, 20))
        self.lineEdit_4.setObjectName("lineEdit_4")
        self.label_6 = QtWidgets.QLabel(Form)
        self.label_6.setGeometry(QtCore.QRect(290, 90, 71, 16))
        self.label_6.setObjectName("label_6")
        self.lineEdit_5 = QtWidgets.QLineEdit(Form)
        self.lineEdit_5.setGeometry(QtCore.QRect(370, 50, 71, 20))
        self.lineEdit_5.setObjectName("lineEdit_5")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label_4.setText(_translate("Form", "Street"))
        self.label_5.setText(_translate("Form", "House number"))
        self.label_6.setText(_translate("Form", "Post Code"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

</code>```

Result:

答:
Since you have hard-coded the left and right-shift of the labels and line edits in the two UIs, could create a new python file (main.py, say), import person.py and address.py in the new file, create a QWidget and apply person.Ui_Form().setupUi and address.Ui_Form().setupUi on the same widget in this particular case. This would mean that main.py would look something like

```<code>import from PyQt5 import QtWidgets
import person, address

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    widget = QtWidgets.QWidget()

    person_ui = person.Ui_Form()
    address_ui = address.Ui_Form()

    person_ui.setupUi(widget)
    address_ui.setupUi(widget)

    widget.show()
    sys.exit(app.exec_())
</code>```

Result:

Edit: At the request of OP I've added a different approach using layouts. As I mentioned in a comment, you could use form layouts to layout the labels and line edits in the person and address widgets. For this, open the layouts for the person and address widgets in Qt Designer, right-click in the Form object in the Object Inspector and choose Lay out > Lay out in a Form Layout from the context menu. Save and export the layouts as usual.

Then in the main .py file, you would need to create separate widgets for the person,  the address, and the main widget, set a QHBoxLayout as the layout manager for the main widget and add the person and address widgets to this layout. You could do all this in the same way as before, but if you want to add extra functionality to your main widget you could also consider sub-classing QWidget and using that to setup the main widget, e.g.

```<code>from PyQt5 import QtWidgets, uic

class MainWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        # setup person widget
        self.person_widget = QtWidgets.QWidget()
        self.person_ui = uic.loadUi('person.ui', self.person_widget)

        # setup address widget
        self.address_widget = QtWidgets.QWidget()
        self.address_ui = uic.loadUi('address.ui', self.address_widget)

        # setup main layout
        hlayout = QtWidgets.QHBoxLayout(self)
        hlayout.addWidget(self.person_widget)
        hlayout.addWidget(self.address_widget)

if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    widget = MainWidget()
    widget.show()
    app.exec()
</code>```

Result:

Body:
imagine i have a window with a lot of widgets and i dont want to have one big class, but several small classes.
How can i write in in a main.py that content of both classes should show up in one window window side by side?
I dont want multiple windows in one window.
I only want all widgets together in one window
I am creating my classes with the QTDesigner.

Example:
person.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'person.ui'
#
# Created by: PyQt5 UI code generator 5.14.2
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(467, 300)
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(10, 40, 51, 16))
        self.label.setObjectName("label")
        self.lineEdit = QtWidgets.QLineEdit(Form)
        self.lineEdit.setGeometry(QtCore.QRect(80, 40, 71, 20))
        self.lineEdit.setObjectName("lineEdit")
        self.label_2 = QtWidgets.QLabel(Form)
        self.label_2.setGeometry(QtCore.QRect(10, 80, 51, 16))
        self.label_2.setObjectName("label_2")
        self.lineEdit_2 = QtWidgets.QLineEdit(Form)
        self.lineEdit_2.setGeometry(QtCore.QRect(80, 80, 71, 20))
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.lineEdit_3 = QtWidgets.QLineEdit(Form)
        self.lineEdit_3.setGeometry(QtCore.QRect(80, 10, 71, 20))
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.label_3 = QtWidgets.QLabel(Form)
        self.label_3.setGeometry(QtCore.QRect(10, 10, 51, 16))
        self.label_3.setObjectName("label_3")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label.setText(_translate("Form", "First name"))
        self.label_2.setText(_translate("Form", "Last name"))
        self.label_3.setText(_translate("Form", "Salutation"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

address.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'address.ui'
#
# Created by: PyQt5 UI code generator 5.14.2
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(467, 300)
        self.label_4 = QtWidgets.QLabel(Form)
        self.label_4.setGeometry(QtCore.QRect(290, 20, 51, 16))
        self.label_4.setObjectName("label_4")
        self.lineEdit_6 = QtWidgets.QLineEdit(Form)
        self.lineEdit_6.setGeometry(QtCore.QRect(370, 90, 71, 20))
        self.lineEdit_6.setObjectName("lineEdit_6")
        self.label_5 = QtWidgets.QLabel(Form)
        self.label_5.setGeometry(QtCore.QRect(290, 50, 71, 16))
        self.label_5.setObjectName("label_5")
        self.lineEdit_4 = QtWidgets.QLineEdit(Form)
        self.lineEdit_4.setGeometry(QtCore.QRect(340, 20, 71, 20))
        self.lineEdit_4.setObjectName("lineEdit_4")
        self.label_6 = QtWidgets.QLabel(Form)
        self.label_6.setGeometry(QtCore.QRect(290, 90, 71, 16))
        self.label_6.setObjectName("label_6")
        self.lineEdit_5 = QtWidgets.QLineEdit(Form)
        self.lineEdit_5.setGeometry(QtCore.QRect(370, 50, 71, 20))
        self.lineEdit_5.setObjectName("lineEdit_5")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label_4.setText(_translate("Form", "Street"))
        self.label_5.setText(_translate("Form", "House number"))
        self.label_6.setText(_translate("Form", "Post Code"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

Result:

Body:
Since you have hard-coded the left and right-shift of the labels and line edits in the two UIs, could create a new python file (main.py, say), import person.py and address.py in the new file, create a QWidget and apply person.Ui_Form().setupUi and address.Ui_Form().setupUi on the same widget in this particular case. This would mean that main.py would look something like

import from PyQt5 import QtWidgets
import person, address

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    widget = QtWidgets.QWidget()

    person_ui = person.Ui_Form()
    address_ui = address.Ui_Form()

    person_ui.setupUi(widget)
    address_ui.setupUi(widget)

    widget.show()
    sys.exit(app.exec_())

Result:

Edit: At the request of OP I've added a different approach using layouts. As I mentioned in a comment, you could use form layouts to layout the labels and line edits in the person and address widgets. For this, open the layouts for the person and address widgets in Qt Designer, right-click in the Form object in the Object Inspector and choose Lay out > Lay out in a Form Layout from the context menu. Save and export the layouts as usual.

Then in the main .py file, you would need to create separate widgets for the person,  the address, and the main widget, set a QHBoxLayout as the layout manager for the main widget and add the person and address widgets to this layout. You could do all this in the same way as before, but if you want to add extra functionality to your main widget you could also consider sub-classing QWidget and using that to setup the main widget, e.g.

from PyQt5 import QtWidgets, uic

class MainWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        # setup person widget
        self.person_widget = QtWidgets.QWidget()
        self.person_ui = uic.loadUi('person.ui', self.person_widget)

        # setup address widget
        self.address_widget = QtWidgets.QWidget()
        self.address_ui = uic.loadUi('address.ui', self.address_widget)

        # setup main layout
        hlayout = QtWidgets.QHBoxLayout(self)
        hlayout.addWidget(self.person_widget)
        hlayout.addWidget(self.address_widget)

if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    widget = MainWidget()
    widget.show()
    app.exec()

Result: