问:
How to map from JPA Object in spring boot
good day all: I have a little issue I want you help me to resolve.
My problem is the next, I have to find the shorter distance of the stores according to google maps and according the latitude and longitude, anyway, I have the query that do these,
my problem is when I call to jparepository it returns an array and I need to return me with a specific format.

This is my end-point I'm trying to get from jparepository

@RequestMapping(value = "api/promos/distance/", method = RequestMethod.GET)
public ResponseEntity<?> distance(@RequestParam(required = false) Double latitude, Double longitude, Long radius) {
    try {
        return ResponseEntity.status(HttpStatus.OK)
                .body(locationDAO.findDistance(latitude,longitude,radius));

    } catch (Exception ex){
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.toString());
    }
}
```

<p>this is my repository with the params and return 2 values</p>

```@Query(value = "select sp.id as id, \n" +
            "          ( 6371  * acos( cos( radians(:latitude) ) \n" +
            "      * cos( radians( sp.latitude )) \n" +
            "      * cos( radians( sp.longitude ) - radians(:longitude)) \n" +
            "      + sin( radians(:latitude) ) \n" +
            "      * sin( radians( sp.latitude ) ) ) ) AS distance \n" +
            "        from promo_locations sp \n" +
            "having distance < :radius ORDER BY distance ASC", nativeQuery = true)
    List<Object> findDistance(
            @Param("latitude") Double latitude,
            @Param("longitude") Double longitude,
            @Param("radius") Long radius);
```

<p>and it show me this</p>

```[
    [
        1,
        137.94383549078196
    ],
    [
        2,
        137.94383549078196
    ]
]
```

<p>but I need to show me in this format:</p>

```[
    {
        "id" : 1,
        "distance" : 137.94383549078196
    },
    {
        "id" : 2,
        "distance" :137.94383549078196
    }
]
```

If someone knows how to map or how to convert I will thank you so much

答:
take a look at this and this

basically you need to define SqlResultSetMapping for your native query

Body:
good day all: I have a little issue I want you help me to resolve.
My problem is the next, I have to find the shorter distance of the stores according to google maps and according the latitude and longitude, anyway, I have the query that do these,
my problem is when I call to jparepository it returns an array and I need to return me with a specific format.

This is my end-point I'm trying to get from jparepository

@RequestMapping(value = "api/promos/distance/", method = RequestMethod.GET)
public ResponseEntity<?> distance(@RequestParam(required = false) Double latitude, Double longitude, Long radius) {
    try {
        return ResponseEntity.status(HttpStatus.OK)
                .body(locationDAO.findDistance(latitude,longitude,radius));

    } catch (Exception ex){
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.toString());
    }
}

this is my repository with the params and return 2 values

@Query(value = "select sp.id as id, \n" +
            "          ( 6371  * acos( cos( radians(:latitude) ) \n" +
            "      * cos( radians( sp.latitude )) \n" +
            "      * cos( radians( sp.longitude ) - radians(:longitude)) \n" +
            "      + sin( radians(:latitude) ) \n" +
            "      * sin( radians( sp.latitude ) ) ) ) AS distance \n" +
            "        from promo_locations sp \n" +
            "having distance < :radius ORDER BY distance ASC", nativeQuery = true)
    List<Object> findDistance(
            @Param("latitude") Double latitude,
            @Param("longitude") Double longitude,
            @Param("radius") Long radius);

and it show me this

[
    [
        1,
        137.94383549078196
    ],
    [
        2,
        137.94383549078196
    ]
]

but I need to show me in this format:

[
    {
        "id" : 1,
        "distance" : 137.94383549078196
    },
    {
        "id" : 2,
        "distance" :137.94383549078196
    }
]

If someone knows how to map or how to convert I will thank you so much


来源: stackexchange

问:
How do I concatenate outer joins on multiple tables in postgres?
I want to return all orders from the database between two given dates. I want to return all orders even if the orders do not have specified values from joined tables (contacts, addresses, etc).

When I run query 1 I see I have 39 orders as a result.
But when I run query 2 with my joins I only return 31 orders.
I checked the database and it's because 8 orders do not have records on the joined tables.

But I thought a RIGHT OUTER JOIN would return all values from the join, even if there is a NULL value in the joined table?

Query 1

```<code>SELECT * FROM orders
WHERE orders.created_at > '2020-02-01' AND orders.created_at < '2020-02-02'
</code>```

Query 2

```<code>SELECT orders.id, orders.status, orders.created_at AS "Date-Time", orders.inbound_ticker, orders.inbound_sum, orders.outbound_ticker, orders.outbound_sum, orders.outbound_type,
    CASE WHEN orders.inbound_type='Cryptocurrency' OR orders.outbound_type='Cryptocurrency' THEN 'Crypto' ELSE 'Fiat' END AS "tx type",
    customers.first_name AS "Customer First Name", customers.last_name AS "Customer Last Name", addresses.street, addresses.city, addresses.state, addresses.country, addresses.postal_code
    FROM orders
RIGHT OUTER JOIN customers ON orders.customer_id = customers.id
RIGHT OUTER JOIN contacts ON contacts.contactable_id = customers.id
RIGHT OUTER JOIN addresses ON customers.id = addresses.locatable_id
WHERE orders.created_at >= '2020-2-01' AND orders.created_at < '2020-2-02'
ORDER BY orders.created_at ASC;
</code>```

答:
If you want all orders, start with orders in the FROM clause and use LEFT JOIN:

```<code>FROM orders LEFT JOIN
     customers
     ON orders.customer_id = customers.id LEFT JOIN
     contacts
     ON contacts.contactable_id = customers.id LEFT JOIN
     addresses
     ON customers.id = addresses.locatable_id
WHERE orders.created_at >= '2020-02-01' AND
      orders.created_at < '2020-02-02'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to return all orders from the database between two given dates. I want to return all orders even if the orders do not have specified values from joined tables (contacts, addresses, etc).

When I run query 1 I see I have 39 orders as a result.
But when I run query 2 with my joins I only return 31 orders.
I checked the database and it's because 8 orders do not have records on the joined tables.

But I thought a RIGHT OUTER JOIN would return all values from the join, even if there is a NULL value in the joined table?

Query 1

SELECT * FROM orders
WHERE orders.created_at > '2020-02-01' AND orders.created_at < '2020-02-02'

Query 2

SELECT orders.id, orders.status, orders.created_at AS "Date-Time", orders.inbound_ticker, orders.inbound_sum, orders.outbound_ticker, orders.outbound_sum, orders.outbound_type,
    CASE WHEN orders.inbound_type='Cryptocurrency' OR orders.outbound_type='Cryptocurrency' THEN 'Crypto' ELSE 'Fiat' END AS "tx type",
    customers.first_name AS "Customer First Name", customers.last_name AS "Customer Last Name", addresses.street, addresses.city, addresses.state, addresses.country, addresses.postal_code
    FROM orders
RIGHT OUTER JOIN customers ON orders.customer_id = customers.id
RIGHT OUTER JOIN contacts ON contacts.contactable_id = customers.id
RIGHT OUTER JOIN addresses ON customers.id = addresses.locatable_id
WHERE orders.created_at >= '2020-2-01' AND orders.created_at < '2020-2-02'
ORDER BY orders.created_at ASC;

Body:
If you want all orders, start with orders in the FROM clause and use LEFT JOIN:

FROM orders LEFT JOIN
     customers
     ON orders.customer_id = customers.id LEFT JOIN
     contacts
     ON contacts.contactable_id = customers.id LEFT JOIN
     addresses
     ON customers.id = addresses.locatable_id
WHERE orders.created_at >= '2020-02-01' AND
      orders.created_at < '2020-02-02'


问:
How to upload photos/pictures to Zoom API using Python (multipart/form-data) with JWT?
I have been racking my brains trying to get this to work with Python. I see you can do this using Curl and JavaScript, but I prefer not to leave Python. Reading the documents (though, they are pretty bare), it says you must simply format the data in the headers as multipart/form-data and send the file as a binary.

```<code>import requests

userid = 'myuserid@place.com'
url = 'https://api.zoom.us/v2/users/{0}/picture'.format(userid)
jwt_token = '<supersecretkey>'
filepath = '/Users/me/Pictures/myprofilepic.jpg'

headers = {
  'Content-Type': 'multipart/form-data',
  'Authorization': 'Bearer {0}'.format(jwt_token)
}

files = [
  ('pic_file', open('<filepath>','rb'))
]

response = requests.request('POST', url, headers=headers, files=files)

print(response.status_code)
</code>```

This example, however, does not work. I keep getting 500 errors. I opened a support case with Zoom and received this exact same code to run. I tried to tackle this myself by formatting and setting my boundaries.

```<code>import requests
import binascii
import os
import base64

jwt_token = '<supersecretkey>'
filepath = '/Users/me/Pictures/myprofilepic.jpg'

def encode_image_base64(filename):
    with open(filename,'rb') as file:
        data_read = file.read()
        data = base64.b64encode(data_read)
    return data

def base64_encode_multipart_formdata(name,filename,content_type):
    base64image = encode_image_base64(filename)
    boundary = binascii.hexlify(os.urandom(16)).decode('ascii')
    body = '--{0}\r\nContent-Disposition: form-data; name="{1}"; filename="{2}"\r\nContent-Type: {3}\r\n\r\n{4}\r\n--{0}--'.format(boundary,name,filename,content_type,base64image)
    content_type = "multipart/form-data; boundary={}".format(boundary)
    return( body, content_type)

def main():
    name = 'pic_file'
    content_type = 'image/jpeg'
    body , ct = base64_encode_multipart_formdata(name,filepath,content_type)
    headers = {
        'Content-Type': '{}'.format(ct),
        'Authorization': 'Bearer {}'.format(jwt_token)
    }
    response = requests.post(url, headers=headers, data=body)
    print(response.status_code)
</code>```

This does not work either.

答:
So it turns out, multipart/form-data DOES NOT WORK for Zoom API Photo Upload but instead, you must remove Content-Type and replace that with 'Accept': 'application/json'. Simple change but voila! it will now upload photos.

```<code>import requests

userid = 'myuserid@place.com'
jwt_token = '<supersecretkey>'
filepath = '/Users/me/Pictures/myprofilepic.jpg'

url = 'https://api.zoom.us/v2/users/{0}/picture'.format(userid)

headers = {'Authorization': 'Bearer {}'.format(jwt_token),
           'Accept': 'application/json',
           }
files = {'pic_file': open(filepath, 'rb'))}

response = requests.post(url, files=files, headers=headers)
print response.content
</code>```

I hope this saves some headaches for people that are dealing with the Zoom API.

Body:
I have been racking my brains trying to get this to work with Python. I see you can do this using Curl and JavaScript, but I prefer not to leave Python. Reading the documents (though, they are pretty bare), it says you must simply format the data in the headers as multipart/form-data and send the file as a binary.

import requests

userid = 'myuserid@place.com'
url = 'https://api.zoom.us/v2/users/{0}/picture'.format(userid)
jwt_token = '<supersecretkey>'
filepath = '/Users/me/Pictures/myprofilepic.jpg'

headers = {
  'Content-Type': 'multipart/form-data',
  'Authorization': 'Bearer {0}'.format(jwt_token)
}

files = [
  ('pic_file', open('<filepath>','rb'))
]

response = requests.request('POST', url, headers=headers, files=files)

print(response.status_code)

This example, however, does not work. I keep getting 500 errors. I opened a support case with Zoom and received this exact same code to run. I tried to tackle this myself by formatting and setting my boundaries.

import requests
import binascii
import os
import base64

jwt_token = '<supersecretkey>'
filepath = '/Users/me/Pictures/myprofilepic.jpg'

def encode_image_base64(filename):
    with open(filename,'rb') as file:
        data_read = file.read()
        data = base64.b64encode(data_read)
    return data

def base64_encode_multipart_formdata(name,filename,content_type):
    base64image = encode_image_base64(filename)
    boundary = binascii.hexlify(os.urandom(16)).decode('ascii')
    body = '--{0}\r\nContent-Disposition: form-data; name="{1}"; filename="{2}"\r\nContent-Type: {3}\r\n\r\n{4}\r\n--{0}--'.format(boundary,name,filename,content_type,base64image)
    content_type = "multipart/form-data; boundary={}".format(boundary)
    return( body, content_type)

def main():
    name = 'pic_file'
    content_type = 'image/jpeg'
    body , ct = base64_encode_multipart_formdata(name,filepath,content_type)
    headers = {
        'Content-Type': '{}'.format(ct),
        'Authorization': 'Bearer {}'.format(jwt_token)
    }
    response = requests.post(url, headers=headers, data=body)
    print(response.status_code)

This does not work either.

Body:
So it turns out, multipart/form-data DOES NOT WORK for Zoom API Photo Upload but instead, you must remove Content-Type and replace that with 'Accept': 'application/json'. Simple change but voila! it will now upload photos.

import requests

userid = 'myuserid@place.com'
jwt_token = '<supersecretkey>'
filepath = '/Users/me/Pictures/myprofilepic.jpg'

url = 'https://api.zoom.us/v2/users/{0}/picture'.format(userid)

headers = {'Authorization': 'Bearer {}'.format(jwt_token),
           'Accept': 'application/json',
           }
files = {'pic_file': open(filepath, 'rb'))}

response = requests.post(url, files=files, headers=headers)
print response.content

I hope this saves some headaches for people that are dealing with the Zoom API.


问:
Enable scrolling touch IE
In my site i have this problem:

I want that all pages is scrollable if the device have a touch display. My site run into IE

I try with apply touch-action pan-y on my principal div but no result.

答:
Add style to head of your html document

```<code><style>.tst{overflow: hidden;}</style>

Add this line in body tag
<body  class="tst" onload ="NoScroll()">

//content here
</code>```

Add this inside script tags

```<code>function noScroll() {
var page = document.getElementsByTagName("body")[0];
if ('ontouchstart' in document.documentElement) {
console.log("touch device detected");
page.classList.remove("tst");
}
else{
console.log("desktop mode");
page.classList.add("tst");
}
}
</code>```

Title: Enable scrolling touch IE

Body:
Add style to head of your html document

<style>.tst{overflow: hidden;}</style>

Add this line in body tag
<body  class="tst" onload ="NoScroll()">

//content here

Add this inside script tags

function noScroll() {
var page = document.getElementsByTagName("body")[0];
if ('ontouchstart' in document.documentElement) {
console.log("touch device detected");
page.classList.remove("tst");
}
else{
console.log("desktop mode");
page.classList.add("tst");
}
}


问:
Bootstrap 4 dropdown not-visible inside datatable
I have seen Bootstrap button drop-down inside responsive table not visible because of scroll and this Bootstrap 4 drop-down menu in table question but the solutions does not work with me because I'm using the DataTables plugin.

The dropdown menu should be above everything, but even after using data-boundary="window" as the Bootstrap 4 documentation tells, it still does not work.

You can see the problem in this JSFiddle.

Without the code of DataTables, it works just fine.

```<code>$(table).DataTable(
{
    'bPaginate'         : true,
    'bLengthChange'     : false,
    'bFilter'           : true,
    'bInfo'             : true,
    'bAutoWidth'        : false,
    'aoColumnDefs'      : [
      {
        'bSortable'     : false,
        'aTargets'      : ['nosorting']
      }],
    'aaSorting'         : [],
})
</code>```

答:
Just added in datatable configuration 'scrollY': '50vh', 'scrollCollapse': true

$(function() {
  var table = $('table');

  $(table).DataTable({
    'bPaginate': true,
    'bLengthChange': false,
    'bFilter': true,
    'bInfo': true,
    'bAutoWidth': false,
    'aoColumnDefs': [{
      'bSortable': false,
      'aTargets': ['nosorting']
    }],
    'aaSorting': [],
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet" type="text/css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/js/dataTables.bootstrap4.min.js" type="text/javascript"></script>

<div class="container">
  <div class="row">
    <div class="col-12">
      <div class="table-responsive">
        <table class="table table-hover">
          <thead>
            <tr>
              <th>Name</th>
              <th>Options</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>John</td>
              <td>
                <div class="btn-group dropup">

            Title
            <span class="caret"></span>

                  <ul class="dropdown-menu">
                    <li class="dropdown-submenu"><a>Option 1</a></li>
                    <li class="dropdown-submenu"><a>Option 1</a></li>
                  </ul>
                </div>
                <div class="btn-group dropleft">
                  <button class="btn btn-secondary dropdown-toggle font-10-px" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" data-boundary="window">Options</button>
                  <div class="dropdown-menu">
                    <button class="dropdown-item font-12-px" type="button">Option 1</button>
                    <button class="dropdown-item font-12-px" type="button">Option 2</button>
                    <button class="dropdown-item font-12-px" type="button">Option 3</button>
                    <button class="dropdown-item font-12-px" type="button">Option 4</button>
                  </div>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div></code>```

Body:
I have seen Bootstrap button drop-down inside responsive table not visible because of scroll and this Bootstrap 4 drop-down menu in table question but the solutions does not work with me because I'm using the DataTables plugin.

The dropdown menu should be above everything, but even after using data-boundary="window" as the Bootstrap 4 documentation tells, it still does not work.

You can see the problem in this JSFiddle.

Without the code of DataTables, it works just fine.

$(table).DataTable(
{
    'bPaginate'         : true,
    'bLengthChange'     : false,
    'bFilter'           : true,
    'bInfo'             : true,
    'bAutoWidth'        : false,
    'aoColumnDefs'      : [
      {
        'bSortable'     : false,
        'aTargets'      : ['nosorting']
      }],
    'aaSorting'         : [],
})

Body:
Just added in datatable configuration 'scrollY': '50vh', 'scrollCollapse': true

$(function() {
  var table = $('table');

  $(table).DataTable({
    'bPaginate': true,
    'bLengthChange': false,
    'bFilter': true,
    'bInfo': true,
    'bAutoWidth': false,
    'aoColumnDefs': [{
      'bSortable': false,
      'aTargets': ['nosorting']
    }],
    'aaSorting': [],
  })
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet" type="text/css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/js/dataTables.bootstrap4.min.js" type="text/javascript"></script>

<div class="container">
  <div class="row">
    <div class="col-12">
      <div class="table-responsive">
        <table class="table table-hover">
          <thead>
            <tr>
              <th>Name</th>
              <th>Options</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>John</td>
              <td>
                <div class="btn-group dropup">
                  <a class="btn dropdown-toggle" data-toggle="dropdown">
            Title
            <span class="caret"></span>
          </a>
                  <ul class="dropdown-menu">
                    <li class="dropdown-submenu"><a>Option 1</a></li>
                    <li class="dropdown-submenu"><a>Option 1</a></li>
                  </ul>
                </div>
                <div class="btn-group dropleft">
                  <button class="btn btn-secondary dropdown-toggle font-10-px" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" data-boundary="window">Options</button>
                  <div class="dropdown-menu">
                    <button class="dropdown-item font-12-px" type="button">Option 1</button>
                    <button class="dropdown-item font-12-px" type="button">Option 2</button>
                    <button class="dropdown-item font-12-px" type="button">Option 3</button>
                    <button class="dropdown-item font-12-px" type="button">Option 4</button>
                  </div>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>


问:
Using Circe to decode Json String
I have a Json string as

```<code>val configInfo =   {
      "car": {
        "requesters": {
          "request1": "key1",
          "request2": "key2"
        },
        "provider": {
          "request1": "key3",
          "request2": "key4"
        }
      },
      "truck": {
        "requesters": {
          "request1": "key2",
          "request2": "key3"
        },
        "provider": {
          "request1": "key2",
          "request2": "key3"
        }
      }
    }
</code>```

I have the following case class to decode json string.

```<code>final case class TenantSettings(requesters: Map[String, String], provider: Map[String, String] = Map.empty)
</code>```

Also, providers in above case class is optional, it may or may not be present in json string.

I want to decode this using circe to

```<code>val value = decode[Map[String, TenantSettings]](configInfo)
</code>```

I understand I need to use custom circe codec, but I am unable to do it, Can someone please help out on this.

答:
You do not need a custom codec. You only need to need to configure the derived codec using circe-generic-extras.

So given:

```<code>val configInfo =
    """{
        "car": {
          "requesters": {
            "request1": "key1",
            "request2": "key2"
          },
          "provider": {
            "request1": "key3",
            "request2": "key4"
          }
        },
        "truck": {
          "requesters": {
            "request1": "key2",
            "request2": "key3"
          },
          "provider": {
            "request1": "key2",
            "request2": "key3"
          }
        },
        "blah": {
          "requesters": {
            "request1": "key2"
          }
        }
      }"""
</code>```

You can:

```<code>import io.circe.Decoder
import io.circe.generic.extras.Configuration
import io.circe.generic.extras.semiauto.deriveConfiguredDecoder

final case class TenantSettings(requesters: Map[String, String], provider: Map[String, String] = Map.empty)
object TentantSettings {
  private implicit final val customConfig: Configuration = Configuration.default.withDefaults
  implicit final val TenantSettingsDecoder: Decoder[TenantSettings] = deriveConfiguredDecoder
}
</code>```

And then:

```<code>io.circe.parser.decode[Map[String, TenantSettings]](configInfo)
// res: Either[io.circe.Error, Map[String, TenantSettings]] = Right(
//   Map(
//     "car" -> TenantSettings(Map("request1" -> "key1", "request2" -> "key2"), Map("request1" -> "key3", "request2" -> "key4")),
//     "truck" -> TenantSettings(Map("request1" -> "key2", "request2" -> "key3"), Map("request1" -> "key2", "request2" -> "key3")),
//     "blah" -> TenantSettings(Map("request1" -> "key2"), Map())
//   )
// )
</code>```

Title: Using Circe to decode Json String

Body:
I have a Json string as

val configInfo =   {
      "car": {
        "requesters": {
          "request1": "key1",
          "request2": "key2"
        },
        "provider": {
          "request1": "key3",
          "request2": "key4"
        }
      },
      "truck": {
        "requesters": {
          "request1": "key2",
          "request2": "key3"
        },
        "provider": {
          "request1": "key2",
          "request2": "key3"
        }
      }
    }

I have the following case class to decode json string.

final case class TenantSettings(requesters: Map[String, String], provider: Map[String, String] = Map.empty)

Also, providers in above case class is optional, it may or may not be present in json string.

I want to decode this using circe to

val value = decode[Map[String, TenantSettings]](configInfo)

I understand I need to use custom circe codec, but I am unable to do it, Can someone please help out on this.

Body:
You do not need a custom codec. You only need to need to configure the derived codec using circe-generic-extras.

So given:

val configInfo =
    """{
        "car": {
          "requesters": {
            "request1": "key1",
            "request2": "key2"
          },
          "provider": {
            "request1": "key3",
            "request2": "key4"
          }
        },
        "truck": {
          "requesters": {
            "request1": "key2",
            "request2": "key3"
          },
          "provider": {
            "request1": "key2",
            "request2": "key3"
          }
        },
        "blah": {
          "requesters": {
            "request1": "key2"
          }
        }
      }"""

You can:

import io.circe.Decoder
import io.circe.generic.extras.Configuration
import io.circe.generic.extras.semiauto.deriveConfiguredDecoder

final case class TenantSettings(requesters: Map[String, String], provider: Map[String, String] = Map.empty)
object TentantSettings {
  private implicit final val customConfig: Configuration = Configuration.default.withDefaults
  implicit final val TenantSettingsDecoder: Decoder[TenantSettings] = deriveConfiguredDecoder
}

And then:

io.circe.parser.decode[Map[String, TenantSettings]](configInfo)
// res: Either[io.circe.Error, Map[String, TenantSettings]] = Right(
//   Map(
//     "car" -> TenantSettings(Map("request1" -> "key1", "request2" -> "key2"), Map("request1" -> "key3", "request2" -> "key4")),
//     "truck" -> TenantSettings(Map("request1" -> "key2", "request2" -> "key3"), Map("request1" -> "key2", "request2" -> "key3")),
//     "blah" -> TenantSettings(Map("request1" -> "key2"), Map())
//   )
// )


问:
Display of music21, musicXML PNG objects using iPython Notebook/Enthought Canopy
I am experimenting with the music21 library, in preparation for a Machine Learning project that involves genre classification and categorization. I and following some tutorials available here. I am using MuseScore as my MusicXML program, and I am trying to run the whole thing from iPython.

Although I can run the some of the turtorials from the terminal, some elements don't seem to run well from inside iPython. For example:

```<code>In [3]: sBach.show()
Out[3]: <music21.ipython21.objects.IPythonPNGObject at 0x10da0aa10>
</code>```

The line above shows that the PNG object is created, but not displayed. The expected output for 3 above is the following:

Experimenting with the following iPython command, I get a placeholder for an image, but not image.

```<code>In [6]: %load_ext music21.ipython21.ipExtension
In [7]: sBach.show()
</code>```

I can't find any problem with my MusicXMLPath. This tutorial refers to the use of musc21 with Anaconda, but all my developments is done with Enthought, so I prefer not to run another virtual environment to use music21 with iPython.

Is there any way to run music21 in an Enthought/iPython notebook?

答: For me the issue was solved by uninstalling the snap version of musescore and installing it from ppa:mscore-ubuntu/mscore3-stable via https://launchpad.net/~mscore-ubuntu/+archive/ubuntu/mscore3-stable</p>

ContentLicense: CC BY-SA 3.0

Body:
I am experimenting with the music21 library, in preparation for a Machine Learning project that involves genre classification and categorization. I and following some tutorials available here. I am using MuseScore as my MusicXML program, and I am trying to run the whole thing from iPython.

Although I can run the some of the turtorials from the terminal, some elements don't seem to run well from inside iPython. For example:

In [3]: sBach.show()
Out[3]: <music21.ipython21.objects.IPythonPNGObject at 0x10da0aa10>

The line above shows that the PNG object is created, but not displayed. The expected output for 3 above is the following:

Experimenting with the following iPython command, I get a placeholder for an image, but not image.

In [6]: %load_ext music21.ipython21.ipExtension
In [7]: sBach.show()

I can't find any problem with my MusicXMLPath. This tutorial refers to the use of musc21 with Anaconda, but all my developments is done with Enthought, so I prefer not to run another virtual environment to use music21 with iPython.

Is there any way to run music21 in an Enthought/iPython notebook?


问:
Error: signInWithPhoneNumber failed: Seconde argument "ApplicationVerifier" must be an implementation of firebase.auth.ApplicationVerifier
I'm working on graduation project, trying to create signIn with phone number Interface with React Native,
I found some codes for SMS Verification here : https://www.instamobile.io/mobile-development/firebase-phone-authentication-react-native/ .... But it gives me an Error !! " Error: signInWithPhoneNumber failed: Seconde argument "ApplicationVerifier" must be an implementation of firebase.auth.ApplicationVerifier"
I tried to connect Xcode with the app by ULR Scheme But its still not working!

Here is my code Hope Can HeLp ME :

```<code>import React, { Component } from 'react';
import {
  StyleSheet,
  SafeAreaView,
  TouchableOpacity,
  View,
  Text,
  TextInput
} from 'react-native';

//import Firebase from '../components/Firebase'
import {Actions} from 'react-native-router-flux';
import * as firebase from 'firebase';

const Config = {
  apiKey: "AIzaSyAsT6g2R1lXZb8soYZB9MtbM**********",
    authDomain: "********application.firebaseapp.com",
    databaseURL: "https://********application.firebaseio.com",
    projectId: "********application",
    storageBucket: "********application.appspot.com",
    messagingSenderId: "*****102252",
    appId: "1:35406102252:web:8c19bfa513e6**********",
    measurementId: "G-V4S6YST***"
};

firebase.initializeApp(Config);

class PhoneAuthScreen extends Component {
  state = {
    phone: '',
    confirmResult: null,
    verificationCode: '',
    userId: '',

  }

  validatePhoneNumber = () => {
    var regexp = /^\+[0-9]?()[0-9](\s|\S)(\d[0-9]{8,16})$/
    return regexp.test(this.state.phone)
  }

  handleSendCode = () => {
    var appVerifier = window.recaptchaVerifier;

    // Request to send OTP
    if (this.validatePhoneNumber()) {
      firebase
        .auth()
        .signInWithPhoneNumber(this.state.phone, appVerifier)
        .then(confirmResult => {
          this.setState({ confirmResult })
        })
        .catch(error => {
          alert(error.message)

          console.log(error)
        })
    } else {
      alert('Invalid Phone Number')
    }

  this.setState({ confirmResult: null, verificationCode: '' })
}
 handleVerifyCode = () => {
 // Request for OTP verification
 const { confirmResult, verificationCode } = this.state
 if (verificationCode.length == 6) {
 confirmResult
 .confirm(verificationCode)
 .then(user => {
 this.setState({ userId: user.uid })
 alert(`Verified! ${user.uid}`)
 })
 .catch(error => {
 alert(error.message)
 console.log(error)
 })
 } else {
 alert('Please enter a 6 digit OTP code.')
 }
 }
 renderConfirmationCodeView = () => {
 return (
 <View style={styles.verificationView}>
 <TextInput
 style={styles.textInput}
 placeholder='Verification code'
 placeholderTextColor='#eee'
 value={this.state.verificationCode}
 keyboardType='numeric'
 onChangeText={verificationCode => {
 this.setState({ verificationCode })
 }}
 maxLength={6}
 />
 <TouchableOpacity
 style={[styles.themeButton, { marginTop: 20 }]}
 onPress={this.handleVerifyCode}>
 <Text style={styles.themeButtonTitle}>Verify Code</Text>
 </TouchableOpacity>
 </View>
 )
 }

 render() {
  return (
  <SafeAreaView style={[styles.container, { backgroundColor: '#333' }]}>
  <View style={styles.page}>
  <TextInput
  style={styles.textInput}
  placeholder='Phone Number with country code'
  placeholderTextColor='#eee'
  keyboardType='phone-pad'
  value={this.state.phone}
  onChangeText={phone => {
  this.setState({ phone })
  }}
  maxLength={15}
  editable={this.state.confirmResult ? false : true}
  />

  <TouchableOpacity
  style={[styles.themeButton, { marginTop: 20 }]}
  onPress={
  this.state.confirmResult
  ? this.changePhoneNumber
  : this.handleSendCode
  }>
  <Text style={styles.themeButtonTitle}>
  {this.state.confirmResult ? 'Change Phone Number' : 'Send Code'}
  </Text>
  </TouchableOpacity>

  {this.state.confirmResult ? this.renderConfirmationCodeView() : null}
  </View>
  </SafeAreaView>
  )
};
}

  const styles = StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: '#aaa'
    },
    page: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center'
    },
    textInput: {
      marginTop: 20,
      width: '90%',
      height: 40,
      borderColor: '#555',
      borderWidth: 2,
      borderRadius: 5,
      paddingLeft: 10,
      color: '#fff',
      fontSize: 16
    },
    themeButton: {
      width: '90%',
      height: 50,
      alignItems: 'center',
      justifyContent: 'center',
      backgroundColor: '#888',
      borderColor: '#555',
      borderWidth: 2,
      borderRadius: 5
    },
    themeButtonTitle: {
      fontSize: 24,
      fontWeight: 'bold',
      color: '#fff'
    },
    verificationView: {
      width: '100%',
      alignItems: 'center',
      marginTop: 50
    }
  })

export default PhoneAuthScreen;
</code>```

答:
```<code>firebase.auth().signInWithPhoneNumber(phoneNumber)
  .then(confirmResult => // save confirm result to use with the manual verification code)
  .catch(error => /error);
</code>```

No need to add appVerifier.
 Refer to the official documentation
https://rnfirebase.io/docs/v5.x.x/auth/phone-auth
Here.

Body:
I'm working on graduation project, trying to create signIn with phone number Interface with React Native,
I found some codes for SMS Verification here : https://www.instamobile.io/mobile-development/firebase-phone-authentication-react-native/ .... But it gives me an Error !! " Error: signInWithPhoneNumber failed: Seconde argument "ApplicationVerifier" must be an implementation of firebase.auth.ApplicationVerifier"
I tried to connect Xcode with the app by ULR Scheme But its still not working!

Here is my code Hope Can HeLp ME :

import React, { Component } from 'react';
import {
  StyleSheet,
  SafeAreaView,
  TouchableOpacity,
  View,
  Text,
  TextInput
} from 'react-native';

//import Firebase from '../components/Firebase'
import {Actions} from 'react-native-router-flux';
import * as firebase from 'firebase';

const Config = {
  apiKey: "AIzaSyAsT6g2R1lXZb8soYZB9MtbM**********",
    authDomain: "********application.firebaseapp.com",
    databaseURL: "https://********application.firebaseio.com",
    projectId: "********application",
    storageBucket: "********application.appspot.com",
    messagingSenderId: "*****102252",
    appId: "1:35406102252:web:8c19bfa513e6**********",
    measurementId: "G-V4S6YST***"
};

firebase.initializeApp(Config);

class PhoneAuthScreen extends Component {
  state = {
    phone: '',
    confirmResult: null,
    verificationCode: '',
    userId: '',

  }

  validatePhoneNumber = () => {
    var regexp = /^\+[0-9]?()[0-9](\s|\S)(\d[0-9]{8,16})$/
    return regexp.test(this.state.phone)
  }

  handleSendCode = () => {
    var appVerifier = window.recaptchaVerifier;

    // Request to send OTP
    if (this.validatePhoneNumber()) {
      firebase
        .auth()
        .signInWithPhoneNumber(this.state.phone, appVerifier)
        .then(confirmResult => {
          this.setState({ confirmResult })
        })
        .catch(error => {
          alert(error.message)

          console.log(error)
        })
    } else {
      alert('Invalid Phone Number')
    }

  this.setState({ confirmResult: null, verificationCode: '' })
}
 handleVerifyCode = () => {
 // Request for OTP verification
 const { confirmResult, verificationCode } = this.state
 if (verificationCode.length == 6) {
 confirmResult
 .confirm(verificationCode)
 .then(user => {
 this.setState({ userId: user.uid })
 alert(`Verified! ${user.uid}`)
 })
 .catch(error => {
 alert(error.message)
 console.log(error)
 })
 } else {
 alert('Please enter a 6 digit OTP code.')
 }
 }
 renderConfirmationCodeView = () => {
 return (
 <View style={styles.verificationView}>
 <TextInput
 style={styles.textInput}
 placeholder='Verification code'
 placeholderTextColor='#eee'
 value={this.state.verificationCode}
 keyboardType='numeric'
 onChangeText={verificationCode => {
 this.setState({ verificationCode })
 }}
 maxLength={6}
 />
 <TouchableOpacity
 style={[styles.themeButton, { marginTop: 20 }]}
 onPress={this.handleVerifyCode}>
 <Text style={styles.themeButtonTitle}>Verify Code</Text>
 </TouchableOpacity>
 </View>
 )
 }

 render() {
  return (
  <SafeAreaView style={[styles.container, { backgroundColor: '#333' }]}>
  <View style={styles.page}>
  <TextInput
  style={styles.textInput}
  placeholder='Phone Number with country code'
  placeholderTextColor='#eee'
  keyboardType='phone-pad'
  value={this.state.phone}
  onChangeText={phone => {
  this.setState({ phone })
  }}
  maxLength={15}
  editable={this.state.confirmResult ? false : true}
  />

  <TouchableOpacity
  style={[styles.themeButton, { marginTop: 20 }]}
  onPress={
  this.state.confirmResult
  ? this.changePhoneNumber
  : this.handleSendCode
  }>
  <Text style={styles.themeButtonTitle}>
  {this.state.confirmResult ? 'Change Phone Number' : 'Send Code'}
  </Text>
  </TouchableOpacity>

  {this.state.confirmResult ? this.renderConfirmationCodeView() : null}
  </View>
  </SafeAreaView>
  )
};
}

  const styles = StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: '#aaa'
    },
    page: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center'
    },
    textInput: {
      marginTop: 20,
      width: '90%',
      height: 40,
      borderColor: '#555',
      borderWidth: 2,
      borderRadius: 5,
      paddingLeft: 10,
      color: '#fff',
      fontSize: 16
    },
    themeButton: {
      width: '90%',
      height: 50,
      alignItems: 'center',
      justifyContent: 'center',
      backgroundColor: '#888',
      borderColor: '#555',
      borderWidth: 2,
      borderRadius: 5
    },
    themeButtonTitle: {
      fontSize: 24,
      fontWeight: 'bold',
      color: '#fff'
    },
    verificationView: {
      width: '100%',
      alignItems: 'center',
      marginTop: 50
    }
  })

export default PhoneAuthScreen;

Body:
firebase.auth().signInWithPhoneNumber(phoneNumber)
  .then(confirmResult => // save confirm result to use with the manual verification code)
  .catch(error => /error);

No need to add appVerifier.
 Refer to the official documentation
https://rnfirebase.io/docs/v5.x.x/auth/phone-auth
Here.


问:
Unmet dependencies installing R 3.6.2 on Ubuntu 18.14 LTS
I use 18.04.4 LTS (Bionic Beaver)

I wanted to upgrade my R version from 3.4.4 to 3.6.2, but now I have no R at all.

here are my actions:

1 step:

```<code>sudo apt update
sudo apt-get upgrade
sudo apt-get dist-upgrade
</code>```

2 step:

```<code>sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9
</code>```

3 step:

```<code>sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/'
</code>```

return:

```<code>Hit:1 http://ua.archive.ubuntu.com/ubuntu bionic InRelease
Hit:2 http://ua.archive.ubuntu.com/ubuntu bionic-updates InRelease
Hit:3 http://ua.archive.ubuntu.com/ubuntu bionic-backports InRelease
Hit:4 http://cran.rstudio.com/bin/linux/ubuntu bionic-cran35/ InRelease
Hit:5 http://ppa.launchpad.net/ondrej/php/ubuntu bionic InRelease
Hit:6 http://security.ubuntu.com/ubuntu bionic-security InRelease
Hit:7 https://cloud.r-project.org/bin/linux/ubuntu xenial-cran35/ InRelease
Hit:8 https://cloud.r-project.org/bin/linux/ubuntu disco-cran35/ InRelease
Hit:9 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/ InRelease
Reading package lists... Done
</code>```

4 step:

```<code>sudo apt update
sudo apt install r-base
</code>```

return:

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
  r-base : Depends: r-base-core (>= 3.6.2-1xenial) but it is not going to be installed
      Depends: r-recommended (= 3.6.2-1xenial) but it is not going to be installed
      Recommends: r-base-html but it is not going to be installed
 E: Unable to correct problems, you have held broken packages.
</code>```

then I try:

```<code>R --version
</code>```

return:

```<code>Command 'R' not found, but can be installed with:
sudo apt install r-base-core
</code>```

I try:

```<code> sudo apt install r-base-core

 The following packages have unmet dependencies:
  r-base-core : Depends: libreadline6 (>= 6.0) but it is not
  installable
           Recommends: r-recommended but it is not going to be
  installed
           Recommends: r-base-dev but it is not going to be
  installed
  E: Unable to correct problems, you have held broken packages.
</code>```

答: I took a look at the etc/apt/sources.list file and realised that I had the same repository repeated. I deleted two lines and the problem was solved. </p>

Body:
I use 18.04.4 LTS (Bionic Beaver)

I wanted to upgrade my R version from 3.4.4 to 3.6.2, but now I have no R at all.

here are my actions:

1 step:

sudo apt update
sudo apt-get upgrade
sudo apt-get dist-upgrade

2 step:

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9

3 step:

sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/'

return:

Hit:1 http://ua.archive.ubuntu.com/ubuntu bionic InRelease
Hit:2 http://ua.archive.ubuntu.com/ubuntu bionic-updates InRelease
Hit:3 http://ua.archive.ubuntu.com/ubuntu bionic-backports InRelease
Hit:4 http://cran.rstudio.com/bin/linux/ubuntu bionic-cran35/ InRelease
Hit:5 http://ppa.launchpad.net/ondrej/php/ubuntu bionic InRelease
Hit:6 http://security.ubuntu.com/ubuntu bionic-security InRelease
Hit:7 https://cloud.r-project.org/bin/linux/ubuntu xenial-cran35/ InRelease
Hit:8 https://cloud.r-project.org/bin/linux/ubuntu disco-cran35/ InRelease
Hit:9 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/ InRelease
Reading package lists... Done

4 step:

sudo apt update
sudo apt install r-base

return:

Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
  r-base : Depends: r-base-core (>= 3.6.2-1xenial) but it is not going to be installed
      Depends: r-recommended (= 3.6.2-1xenial) but it is not going to be installed
      Recommends: r-base-html but it is not going to be installed
 E: Unable to correct problems, you have held broken packages.

then I try:

R --version

return:

Command 'R' not found, but can be installed with:
sudo apt install r-base-core

I try:

 sudo apt install r-base-core

 The following packages have unmet dependencies:
  r-base-core : Depends: libreadline6 (>= 6.0) but it is not
  installable
           Recommends: r-recommended but it is not going to be
  installed
           Recommends: r-base-dev but it is not going to be
  installed
  E: Unable to correct problems, you have held broken packages.


问:
Java 11 On Windows 7 32 bits
I developed an Java application with Jdk 11 embedded. I packaged my application with launch4j and InnoSetup.

I would like to run this application on 32-bit Windows 7.

Is it possible to run it on 32 with an embedded Java 64?

Thank you in advance.

答:
The people from AdoptOpenJDK took the burden of making builds for different architecture and as far as I can see there is a build for JDK 11 32bit version.

Check this download page.

Title: Java 11 On Windows 7 32 bits


问:
502 when running SQS test using localstack
I'm trying to run some tests with SQS using localstack. However, I keep getting a 502. This works for a co-worker, but it doesn't work on my local machine, on our pipeline, or on docker. The error is the same everywhere, so I'm sending the docker version, since it's probably easier to show what's installed.

Basically I'm creating a docker image that installs java, python, and executes the gradle build from the /repo folder, executing integration tests.

```<code>FROM openjdk:11.0.2-jdk-oraclelinux7

RUN ["yum", "install", "-y", "python", "python-pip"]
RUN ["pip", "install", "--upgrade", "pip"]
RUN ["pip", "install", "virtualenv"]

VOLUME ["/repo"]

ARG sourceDir

COPY ["${sourceDir}", "/repo"]
WORKDIR "/repo"

ENTRYPOINT ["/repo/gradlew", "clean", "integrationTest"]
</code>```

My test code looks like this:

```<code>@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(LocalstackTestRunner.class)
public class TimeoutQueueTest {

    private AmazonSQS client;
    private static final String QUEUE_NAME = "my queue";

   @LocalServerPort
    private int port;

   @ClassRule
    public static final SpringClassRule springClassRule = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

   @Before
    public void setup() {
        Map<String, String> attributeMap = new HashMap<>();
        attributeMap.put("DelaySeconds", "0");
        attributeMap.put("MaximumMessageSize", "262144");
        attributeMap.put("MessageRetentionPeriod", "1209600");
        attributeMap.put("ReceiveMessageWaitTimeSeconds", "20");
        attributeMap.put("VisibilityTimeout", "30");

        client = TestUtils.getClientSQS();
        CreateQueueRequest createQueueRequest = new CreateQueueRequest(QUEUE_NAME).withAttributes(attributeMap);
        //FAILS IN THE LINE BELOW!!!!!!!!!!!!!!!!!!
        String standardQueueUrl = client.createQueue(createQueueRequest).getQueueUrl();

        RestAssured.port = port;
    }

(...)
}
</code>```

It fails with:

```<code> com.amazonaws.services.sqs.model.AmazonSQSException: null (Service: AmazonSQS; Status Code: 502; Error Code: 502 Bad Gateway; Request ID: null)

at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1660)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1324)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1074)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:745)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:719)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:701)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:669)
at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:651)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:515)
at com.amazonaws.services.sqs.AmazonSQSClient.doInvoke(AmazonSQSClient.java:2147)
at com.amazonaws.services.sqs.AmazonSQSClient.invoke(AmazonSQSClient.java:2116)
at com.amazonaws.services.sqs.AmazonSQSClient.invoke(AmazonSQSClient.java:2105)
at com.amazonaws.services.sqs.AmazonSQSClient.executeCreateQueue(AmazonSQSClient.java:756)
at com.amazonaws.services.sqs.AmazonSQSClient.createQueue(AmazonSQSClient.java:728)
at uk.co.sainsburys.giftcardservice.TimeoutQueueTest.setup(TimeoutQueueTest.java:76)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.RunPrepareTestInstanceCallbacks.evaluate(RunPrepareTestInstanceCallbacks.java:64)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.springframework.test.context.junit4.statements.SpringFailOnTimeout.evaluate(SpringFailOnTimeout.java:87)
at org.springframework.test.context.junit4.statements.ProfileValueChecker.evaluate(ProfileValueChecker.java:103)
at com.github.tomakehurst.wiremock.junit.WireMockRule$1.evaluate(WireMockRule.java:73)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.springframework.test.context.junit4.statements.ProfileValueChecker.evaluate(ProfileValueChecker.java:103)
at org.springframework.test.context.junit4.rules.SpringClassRule$TestContextManagerCacheEvictor.evaluate(SpringClassRule.java:190)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at cloud.localstack.LocalstackTestRunner.run(LocalstackTestRunner.java:25)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
</code>```

Any ideas? What am I missing? The code seems to work, since it's working for my co-worker (saw it with my own eyes). He doesn't remember having done anything different than me in terms of setup.

We're both using python 2.7.10, btw (if it matters).

答:
Try not to make assumption that AWS services are healthy at all times. In the backend of AWS services, they also have containers, where their containers can be shut down, rotated, restarted, and all their container supporting services may also be shut down, rotated or restarted. In this case, you will need a health check to ensure that sqs is ready to be pushed or listened to. The thread below may point you to how to properly listen with a health check:

Spring Boot Health Check - SQS Consumer

Body:
I'm trying to run some tests with SQS using localstack. However, I keep getting a 502. This works for a co-worker, but it doesn't work on my local machine, on our pipeline, or on docker. The error is the same everywhere, so I'm sending the docker version, since it's probably easier to show what's installed.

Basically I'm creating a docker image that installs java, python, and executes the gradle build from the /repo folder, executing integration tests.

FROM openjdk:11.0.2-jdk-oraclelinux7

RUN ["yum", "install", "-y", "python", "python-pip"]
RUN ["pip", "install", "--upgrade", "pip"]
RUN ["pip", "install", "virtualenv"]

VOLUME ["/repo"]

ARG sourceDir

COPY ["${sourceDir}", "/repo"]
WORKDIR "/repo"

ENTRYPOINT ["/repo/gradlew", "clean", "integrationTest"]

My test code looks like this:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(LocalstackTestRunner.class)
public class TimeoutQueueTest {

    private AmazonSQS client;
    private static final String QUEUE_NAME = "my queue";

   @LocalServerPort
    private int port;

   @ClassRule
    public static final SpringClassRule springClassRule = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

   @Before
    public void setup() {
        Map<String, String> attributeMap = new HashMap<>();
        attributeMap.put("DelaySeconds", "0");
        attributeMap.put("MaximumMessageSize", "262144");
        attributeMap.put("MessageRetentionPeriod", "1209600");
        attributeMap.put("ReceiveMessageWaitTimeSeconds", "20");
        attributeMap.put("VisibilityTimeout", "30");

        client = TestUtils.getClientSQS();
        CreateQueueRequest createQueueRequest = new CreateQueueRequest(QUEUE_NAME).withAttributes(attributeMap);
        //FAILS IN THE LINE BELOW!!!!!!!!!!!!!!!!!!
        String standardQueueUrl = client.createQueue(createQueueRequest).getQueueUrl();

        RestAssured.port = port;
    }

(...)
}

It fails with:

 com.amazonaws.services.sqs.model.AmazonSQSException: null (Service: AmazonSQS; Status Code: 502; Error Code: 502 Bad Gateway; Request ID: null)

at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1660)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1324)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1074)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:745)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:719)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:701)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:669)
at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:651)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:515)
at com.amazonaws.services.sqs.AmazonSQSClient.doInvoke(AmazonSQSClient.java:2147)
at com.amazonaws.services.sqs.AmazonSQSClient.invoke(AmazonSQSClient.java:2116)
at com.amazonaws.services.sqs.AmazonSQSClient.invoke(AmazonSQSClient.java:2105)
at com.amazonaws.services.sqs.AmazonSQSClient.executeCreateQueue(AmazonSQSClient.java:756)
at com.amazonaws.services.sqs.AmazonSQSClient.createQueue(AmazonSQSClient.java:728)
at uk.co.sainsburys.giftcardservice.TimeoutQueueTest.setup(TimeoutQueueTest.java:76)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.RunPrepareTestInstanceCallbacks.evaluate(RunPrepareTestInstanceCallbacks.java:64)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.springframework.test.context.junit4.statements.SpringFailOnTimeout.evaluate(SpringFailOnTimeout.java:87)
at org.springframework.test.context.junit4.statements.ProfileValueChecker.evaluate(ProfileValueChecker.java:103)
at com.github.tomakehurst.wiremock.junit.WireMockRule$1.evaluate(WireMockRule.java:73)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.springframework.test.context.junit4.statements.ProfileValueChecker.evaluate(ProfileValueChecker.java:103)
at org.springframework.test.context.junit4.rules.SpringClassRule$TestContextManagerCacheEvictor.evaluate(SpringClassRule.java:190)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at cloud.localstack.LocalstackTestRunner.run(LocalstackTestRunner.java:25)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Any ideas? What am I missing? The code seems to work, since it's working for my co-worker (saw it with my own eyes). He doesn't remember having done anything different than me in terms of setup.

We're both using python 2.7.10, btw (if it matters).


问:
Is there a way to print a pointer with %x argument
I have tried to make a program with the parameter %d in a pointer but it does not work, I changed  to %p, but that is for the address, I want to print the value.
This is the error

```
gcc null_Pointer.c -o null_Pointer
null_Pointer.c: In function ‘main’:
null_Pointer.c:7:35: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
    7 |    printf("The value of ptr is : %x\n", ptr  );
      |                                  ~^     ~~~
      |                                   |     |
      |                                   |     int *
      |                                   unsigned int
      |                                  %ls
```

this  is the  code

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

int main () {

   int  *ptr = NULL;

   printf("The value of ptr is : %x\n", ptr  );

   return 0;
}
</code>```

答:
The format string defines both: what kind (type) of value is expected and how it will be printed, then the corresponding argument needs to correspond.

If you chose %p the expected value must be of pointer type and will be printed in hexadecimal format. From the man:

p The void * pointer argument is printed in hexadecimal

If you want to print the value a pointer points to, then:

your pointer must point to something

you must dereference the pointer with operator *

use any suitable format character

In your case, %d can be used to print an int in decimal format. From the man:

dor i  The int (or appropriate variant) argument is converted to signed
               decimal (d and i)

To met the three criteria you can write something like:

```<code>int a = 666; // define an int variable
int *ptr;    // define a pointer to an int (actually not initialized)
ptr = &a;    // make the pointer points to the int named a, or, make the pointer takes the value of the address of variable a
print("%d\n",*ptr); // print as decimal the value pointed by ptr
</code>```

If you want to print the value pointed by ptr in hexadecimal, then use %x.

Body:
I have tried to make a program with the parameter %d in a pointer but it does not work, I changed  to %p, but that is for the address, I want to print the value.
This is the error

gcc null_Pointer.c -o null_Pointer
null_Pointer.c: In function ‘main’:
null_Pointer.c:7:35: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
    7 |    printf("The value of ptr is : %x\n", ptr  );
      |                                  ~^     ~~~
      |                                   |     |
      |                                   |     int *
      |                                   unsigned int
      |                                  %ls

this  is the  code

#include <stdio.h>

int main () {

   int  *ptr = NULL;

   printf("The value of ptr is : %x\n", ptr  );

   return 0;
}

Body:
The format string defines both: what kind (type) of value is expected and how it will be printed, then the corresponding argument needs to correspond.

If you chose %p the expected value must be of pointer type and will be printed in hexadecimal format. From the man:

p The void * pointer argument is printed in hexadecimal

If you want to print the value a pointer points to, then:

your pointer must point to something

you must dereference the pointer with operator *

use any suitable format character

In your case, %d can be used to print an int in decimal format. From the man:

dor i  The int (or appropriate variant) argument is converted to signed
               decimal (d and i)

To met the three criteria you can write something like:

int a = 666; // define an int variable
int *ptr;    // define a pointer to an int (actually not initialized)
ptr = &a;    // make the pointer points to the int named a, or, make the pointer takes the value of the address of variable a
print("%d\n",*ptr); // print as decimal the value pointed by ptr

If you want to print the value pointed by ptr in hexadecimal, then use %x.


问:
problem with sending and displaying info about validation results
I have user registration form that calls another file which calls an object that performs validation.

I would like to create this form to be sticky and display info about validation errors next to respective fields.

How can I resend data to the page with the form?

答:
You could use client-side JavaScript validation (and back that up with server-side PHP validation too) but if you set the forms' POST target to be the same page that generates the form (so $_SERVER['REQUEST_URI']) you could call the validation object/class in a statement like:</p>

```<code>if (isset($_POST['submit'])) {
    // Validation code
}

// Generate form along with any output from validation script
</code>```

Body:
You could use client-side JavaScript validation (and back that up with server-side PHP validation too) but if you set the forms' POST target to be the same page that generates the form (so $_SERVER['REQUEST_URI']) you could call the validation object/class in a statement like:

if (isset($_POST['submit'])) {
    // Validation code
}

// Generate form along with any output from validation script


问:
Is there any way to Read BeautifulSoup output with pandas to read Tables?
I have tried this Way

```<code>data = web_soup.findAll("table", {"id": "product-review-table"})```
print(pd.read_html(data))
```

Error Returned:
TypeError: Cannot read object of type 'ResultSet

data contain a complete table. I want to read only specific table from Url, By passing url to pd.read_html() it will get all tables but to save execution time i just want to read a specific table. How may i do it ?

答:
Short Answer:

```<code>pd.read_html(str(data))
</code>```

Longer answer:

The input to read_html() can be a string.

From the docs:

```<code>pandas.read_html(io, ..):
...
io : str or file-like
    A URL, a file-like object, or a raw string containing HTML...

...
</code>```

The output of findAll (or find_all) is a ResultSet object.

The string representation of the ResultSet object can be obtained using str(ResultSetObject).

```<code>data = web_soup.findAll("table", {"id": "product-review-table"})
print(pd.read_html(str(data)))
</code>```

Body:
I have tried this Way

data = web_soup.findAll("table", {"id": "product-review-table"})```
print(pd.read_html(data))

Error Returned:
TypeError: Cannot read object of type 'ResultSet

data contain a complete table. I want to read only specific table from Url, By passing url to pd.read_html() it will get all tables but to save execution time i just want to read a specific table. How may i do it ?

Body:
Short Answer:

pd.read_html(str(data))

Longer answer:

The input to read_html() can be a string.

From the docs:

pandas.read_html(io, ..):
...
io : str or file-like
    A URL, a file-like object, or a raw string containing HTML...

...

The output of findAll (or find_all) is a ResultSet object.

The string representation of the ResultSet object can be obtained using str(ResultSetObject).

data = web_soup.findAll("table", {"id": "product-review-table"})
print(pd.read_html(str(data)))


问:
Required bean of type 'java.security.KeyPair' not found
I am trying following the spring documentation for OAUth2 Boot to implement a AuthorizationServer, and get stuck on this items:

1.8.1 Configuring Authorization Server to Use JWKs
and
1.8.2 Add a JWK Set URI Endpoint

Based on the info describe there, I add this code to my AuthorizationServerConfigurerAdapter:

```<code>@EnableAuthorizationServer
@Configuration
public class JwkSetConfiguration extends AuthorizationServerConfigurerAdapter {

    AuthenticationManager authenticationManager;
    KeyPair keyPair;

    public JwkSetConfiguration(AuthenticationConfiguration authenticationConfiguration,
            KeyPair keyPair) throws Exception {

        this.authenticationManager = authenticationConfiguration.getAuthenticationManager();
        this.keyPair = keyPair;
    }

    // ... client configuration, etc.

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        // @formatter:off
        endpoints
            .authenticationManager(this.authenticationManager)
            .accessTokenConverter(accessTokenConverter())
            .tokenStore(tokenStore());
        // @formatter:on
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setKeyPair(this.keyPair);
        return converter;
    }
}
</code>```

and add this 2 classes to my project:

```<code>@FrameworkEndpoint
class JwkSetEndpoint {
    KeyPair keyPair;

    public JwkSetEndpoint(KeyPair keyPair) {
        this.keyPair = keyPair;
    }

    @GetMapping("/.well-known/jwks.json")
    @ResponseBody
    public Map<String, Object> getKey() {
        RSAPublicKey publicKey = (RSAPublicKey) this.keyPair.getPublic();
        RSAKey key = new RSAKey.Builder(publicKey).build();
        return new JWKSet(key).toJSONObject();
    }
}
</code>```

and

```<code>@Configuration
class JwkSetEndpointConfiguration extends AuthorizationServerSecurityConfiguration {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http
            .requestMatchers()
                .mvcMatchers("/.well-known/jwks.json")
                .and()
            .authorizeRequests()
                .mvcMatchers("/.well-known/jwks.json").permitAll();
    }
}
</code>```

everything is compiled without errors, but when I try execute the application, I got this message:

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 1 of constructor in oauth.server.Server required a bean of type 'java.security.KeyPair' that could not be found.

The injection point has the following annotations:
        - @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'java.security.KeyPair' in your configuration.
</code>```

How I can define this 'java.security.KeyPair' bean required to run the application?

ps.: the full code for my AuthorizationServerConfigurerAdapter is:

```<code>@Import(AuthorizationServerEndpointsConfiguration.class)
@Configuration
public class Server extends AuthorizationServerConfigurerAdapter {
    private AuthenticationManager authenticationManager;

    private KeyPair keyPair;

    public Server(AuthenticationConfiguration authenticationConfiguration, KeyPair keyPair) throws Exception {
        this.authenticationManager = authenticationConfiguration.getAuthenticationManager();
        this.keyPair = keyPair;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
            .inMemory()
                .withClient("first-client")
                .secret(passwordEncoder().encode("noonewilleverguess"))
                .scopes("resource:read")
                .authorizedGrantTypes("authorization_code")
                .redirectUris("http://localhost:8080/oauth/login/client-app");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
            .authenticationManager(this.authenticationManager)
            .accessTokenConverter(accessTokenConverter())
            .tokenStore(tokenStore());
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setKeyPair(this.keyPair);
        return converter;
    }
}
</code>```

UPDATE

pom.xml

```<code><dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth</groupId>
        <artifactId>spring-security-oauth2</artifactId>
        <version>2.4.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth.boot</groupId>
        <artifactId>spring-security-oauth2-autoconfigure</artifactId>
        <version>2.2.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-jwt</artifactId>
        <version>1.1.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>com.nimbusds</groupId>
        <artifactId>nimbus-jose-jwt</artifactId>
        <version>8.6</version>
    </dependency>
</dependencies>
</code>```

答:
I managed to solve this issue adding this bean to my class Server:

```<code>@Autowired
private KeyPair keyPair;

@Bean
public KeyPair keyPairBean() throws NoSuchAlgorithmException {
  KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
  gen.initialize(2048);
  KeyPair keyPair = gen.generateKeyPair();
  return keyPair;
}
</code>```

Body:
I am trying following the spring documentation for OAUth2 Boot to implement a AuthorizationServer, and get stuck on this items:

1.8.1 Configuring Authorization Server to Use JWKs
and
1.8.2 Add a JWK Set URI Endpoint

Based on the info describe there, I add this code to my AuthorizationServerConfigurerAdapter:

@EnableAuthorizationServer
@Configuration
public class JwkSetConfiguration extends AuthorizationServerConfigurerAdapter {

    AuthenticationManager authenticationManager;
    KeyPair keyPair;

    public JwkSetConfiguration(AuthenticationConfiguration authenticationConfiguration,
            KeyPair keyPair) throws Exception {

        this.authenticationManager = authenticationConfiguration.getAuthenticationManager();
        this.keyPair = keyPair;
    }

    // ... client configuration, etc.

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        // @formatter:off
        endpoints
            .authenticationManager(this.authenticationManager)
            .accessTokenConverter(accessTokenConverter())
            .tokenStore(tokenStore());
        // @formatter:on
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setKeyPair(this.keyPair);
        return converter;
    }
}

and add this 2 classes to my project:

@FrameworkEndpoint
class JwkSetEndpoint {
    KeyPair keyPair;

    public JwkSetEndpoint(KeyPair keyPair) {
        this.keyPair = keyPair;
    }

    @GetMapping("/.well-known/jwks.json")
    @ResponseBody
    public Map<String, Object> getKey() {
        RSAPublicKey publicKey = (RSAPublicKey) this.keyPair.getPublic();
        RSAKey key = new RSAKey.Builder(publicKey).build();
        return new JWKSet(key).toJSONObject();
    }
}

and

@Configuration
class JwkSetEndpointConfiguration extends AuthorizationServerSecurityConfiguration {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http
            .requestMatchers()
                .mvcMatchers("/.well-known/jwks.json")
                .and()
            .authorizeRequests()
                .mvcMatchers("/.well-known/jwks.json").permitAll();
    }
}

everything is compiled without errors, but when I try execute the application, I got this message:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 1 of constructor in oauth.server.Server required a bean of type 'java.security.KeyPair' that could not be found.

The injection point has the following annotations:
        - @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'java.security.KeyPair' in your configuration.

How I can define this 'java.security.KeyPair' bean required to run the application?

ps.: the full code for my AuthorizationServerConfigurerAdapter is:

@Import(AuthorizationServerEndpointsConfiguration.class)
@Configuration
public class Server extends AuthorizationServerConfigurerAdapter {
    private AuthenticationManager authenticationManager;

    private KeyPair keyPair;

    public Server(AuthenticationConfiguration authenticationConfiguration, KeyPair keyPair) throws Exception {
        this.authenticationManager = authenticationConfiguration.getAuthenticationManager();
        this.keyPair = keyPair;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
            .inMemory()
                .withClient("first-client")
                .secret(passwordEncoder().encode("noonewilleverguess"))
                .scopes("resource:read")
                .authorizedGrantTypes("authorization_code")
                .redirectUris("http://localhost:8080/oauth/login/client-app");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
            .authenticationManager(this.authenticationManager)
            .accessTokenConverter(accessTokenConverter())
            .tokenStore(tokenStore());
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setKeyPair(this.keyPair);
        return converter;
    }
}

UPDATE

pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth</groupId>
        <artifactId>spring-security-oauth2</artifactId>
        <version>2.4.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth.boot</groupId>
        <artifactId>spring-security-oauth2-autoconfigure</artifactId>
        <version>2.2.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-jwt</artifactId>
        <version>1.1.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>com.nimbusds</groupId>
        <artifactId>nimbus-jose-jwt</artifactId>
        <version>8.6</version>
    </dependency>
</dependencies>

Body:
I managed to solve this issue adding this bean to my class Server:

@Autowired
private KeyPair keyPair;

@Bean
public KeyPair keyPairBean() throws NoSuchAlgorithmException {
  KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
  gen.initialize(2048);
  KeyPair keyPair = gen.generateKeyPair();
  return keyPair;
}


问:
How to load a path in QtVideoWigdet
I have a question in pyqt5. I want to make a Videoplayer. now I'm stuck that how can I gave them complete path it not to click on the button and go to path and select the video I just want that it this one file path. Please have a look to my code. I making this for both raspberry pi and window

```<code>from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_VideoWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(733, 505)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.Video_Widget = QVideoWidget(self.centralwidget)
        self.Video_Widget.setGeometry(QtCore.QRect(0, 0, 711, 361))
        self.Video_Widget.setObjectName("Video_Widget")
        self.horizontalScrollBar = QtWidgets.QScrollBar(self.centralwidget)
        self.horizontalScrollBar.setGeometry(QtCore.QRect(0, 380, 721, 16))
        self.horizontalScrollBar.setOrientation(QtCore.Qt.Horizontal)
        self.horizontalScrollBar.setObjectName("horizontalScrollBar")
        self.play = QtWidgets.QPushButton(self.centralwidget)
        self.play.setGeometry(QtCore.QRect(10, 410, 75, 23))
        self.play.setObjectName("play")
        self.select = QtWidgets.QPushButton(self.centralwidget)
        self.select.setGeometry(QtCore.QRect(550, 410, 75, 23))
        self.select.setObjectName("select")

        self.play.clicked.connect(self.load_video)

        MainWindow.setCentralWidget(self.centralwidget)

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

    def load_video(self):
        filepath = 'F:/Fun/Songs/12.mp4'
        self.Video_Widget.load(filepath)
        self.horizontalScrollBar.setMediaObject(self.Video_Widget.mediaObject())
        self.Video_Widget.play()

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.play.setText(_translate("MainWindow", "play"))
        self.select.setText(_translate("MainWindow", "Select"))
from PyQt5.QtMultimediaWidgets import QVideoWidget

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

I used this code too which is present in official documentation.

```<code> def load_video(self):
    player = QMediaPlayer()
    playlist = QMediaPlaylist(player)
    playlist.addMedia(QUrl('F:/Fun/Songs/12.mp4'))
    player.setVideoOutput(self.Video_Widget)
    self.Video_Widget.show()
    playlist.setCurrentIndex(1)
    player.play()
</code>```

while using this code which is in official documentation. this error occurred.

答:
As the error and the docs point out, a QMediaContent must be passed to the addMedia method. To build a QMediaContent you can use a QUrl:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_VideoWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(733, 505)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.Video_Widget = QVideoWidget(self.centralwidget)
        self.Video_Widget.setGeometry(QtCore.QRect(0, 0, 711, 361))
        self.Video_Widget.setObjectName("Video_Widget")
        self.horizontalScrollBar = QtWidgets.QScrollBar(self.centralwidget)
        self.horizontalScrollBar.setGeometry(QtCore.QRect(0, 380, 721, 16))
        self.horizontalScrollBar.setOrientation(QtCore.Qt.Horizontal)
        self.horizontalScrollBar.setObjectName("horizontalScrollBar")
        self.play = QtWidgets.QPushButton(self.centralwidget)
        self.play.setGeometry(QtCore.QRect(10, 410, 75, 23))
        self.play.setObjectName("play")
        self.select = QtWidgets.QPushButton(self.centralwidget)
        self.select.setGeometry(QtCore.QRect(550, 410, 75, 23))
        self.select.setObjectName("select")
        MainWindow.setCentralWidget(self.centralwidget)

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

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.play.setText(_translate("MainWindow", "play"))
        self.select.setText(_translate("MainWindow", "Select"))

from PyQt5.QtMultimediaWidgets import QVideoWidget
from PyQt5 import QtMultimedia

class VideoWindow(QtWidgets.QMainWindow, Ui_VideoWindow):
    def __init__(self, parent=None):
        super(VideoWindow, self).__init__(parent)
        self.setupUi(self)
        self.player = QtMultimedia.QMediaPlayer(self)
        self.player.setVideoOutput(self.Video_Widget)
        self.play.clicked.connect(self.player.play)
        self.playlist = QtMultimedia.QMediaPlaylist(self.player)
        self.player.setPlaylist(self.playlist)
        self.playlist.addMedia(
            QtMultimedia.QMediaContent(QtCore.QUrl.fromLocalFile("F:/Fun/Songs/12.mp4"))
        )
        self.playlist.setCurrentIndex(0)

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = VideoWindow()
    w.show()
    sys.exit(app.exec_())
```

Title: How to load a path in QtVideoWigdet

Body:
I have a question in pyqt5. I want to make a Videoplayer. now I'm stuck that how can I gave them complete path it not to click on the button and go to path and select the video I just want that it this one file path. Please have a look to my code. I making this for both raspberry pi and window

from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_VideoWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(733, 505)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.Video_Widget = QVideoWidget(self.centralwidget)
        self.Video_Widget.setGeometry(QtCore.QRect(0, 0, 711, 361))
        self.Video_Widget.setObjectName("Video_Widget")
        self.horizontalScrollBar = QtWidgets.QScrollBar(self.centralwidget)
        self.horizontalScrollBar.setGeometry(QtCore.QRect(0, 380, 721, 16))
        self.horizontalScrollBar.setOrientation(QtCore.Qt.Horizontal)
        self.horizontalScrollBar.setObjectName("horizontalScrollBar")
        self.play = QtWidgets.QPushButton(self.centralwidget)
        self.play.setGeometry(QtCore.QRect(10, 410, 75, 23))
        self.play.setObjectName("play")
        self.select = QtWidgets.QPushButton(self.centralwidget)
        self.select.setGeometry(QtCore.QRect(550, 410, 75, 23))
        self.select.setObjectName("select")

        self.play.clicked.connect(self.load_video)

        MainWindow.setCentralWidget(self.centralwidget)

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

    def load_video(self):
        filepath = 'F:/Fun/Songs/12.mp4'
        self.Video_Widget.load(filepath)
        self.horizontalScrollBar.setMediaObject(self.Video_Widget.mediaObject())
        self.Video_Widget.play()

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.play.setText(_translate("MainWindow", "play"))
        self.select.setText(_translate("MainWindow", "Select"))
from PyQt5.QtMultimediaWidgets import QVideoWidget

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_VideoWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

I used this code too which is present in official documentation.

 def load_video(self):
    player = QMediaPlayer()
    playlist = QMediaPlaylist(player)
    playlist.addMedia(QUrl('F:/Fun/Songs/12.mp4'))
    player.setVideoOutput(self.Video_Widget)
    self.Video_Widget.show()
    playlist.setCurrentIndex(1)
    player.play()

while using this code which is in official documentation. this error occurred.


问:
$lookup on ObjectId's in an array does not work
i have the same case as in this question: $lookup on ObjectId's in an array (i can't comment on the question since i don't have enough reputation... sorry for the duplication..) - but
the query doesn't work for me and i get an empty array in the end of it.

i want to get a list of companies with a field of its positions, but the positions field is always empty
on the following code. (i get the company fields, and with the $unwind - even the company fields are not returned).

what am i doing wrong?

mongoose version: 5.7.14
mongodb version:  4.2.3

i also tried a lot of combinations of aggregation and populate and none of them succeeded.

```<code>const schema = new Schema(
  {
    email: {
      type: String,
      required: true,
      unique: true
    },
    name: {
      type: String,
      required: true,
      unique: true
    },
    positionsIds: [{
      type: Schema.Types.ObjectId,
      ref: 'Position',
      require: false
  }
);

module.exports = mongoose.model('Company', schema);

-----------------------------

const schema = new Schema(
  {
    title: {
      type: String,
      required: true
    },
    requirements: [{
      years: { type: Number, required: false },
      skill: { type: String, required: false },
    }],
    companyId: {
      type: Schema.Types.ObjectId,
      ref: 'Company',
      required: true
    },
  }
);

module.exports = mongoose.model('Position', schema );

---------------------------

    let companies = await Company.aggregate([
      {
        $lookup:
        {
          from: 'Position',
          localField: '_id',
          foreignField: 'companyId',
          as: 'positions'
        }
      },
      // {
      //     $unwind: '$positions' // - mess the query even more and return an empty array
      // },
      ]);

</code>```

答:
Mongoose creates MongoDB collections based on convention. Position as model name gets translated into plural form positions so your query should look like:

```<code>{
    $lookup: {
        from: 'positions',
        localField: '_id',
        foreignField: 'companyId',
        as: 'positions'
    }
}
</code>```

The first argument is the singular name of the collection your model is for. ** Mongoose automatically looks for the plural, lowercased version of your model name. ** Thus, for the example above, the model Tank is for the tanks collection in the database.

Body:
i have the same case as in this question: $lookup on ObjectId's in an array (i can't comment on the question since i don't have enough reputation... sorry for the duplication..) - but
the query doesn't work for me and i get an empty array in the end of it.

i want to get a list of companies with a field of its positions, but the positions field is always empty
on the following code. (i get the company fields, and with the $unwind - even the company fields are not returned).

what am i doing wrong?

mongoose version: 5.7.14
mongodb version:  4.2.3

i also tried a lot of combinations of aggregation and populate and none of them succeeded.

const schema = new Schema(
  {
    email: {
      type: String,
      required: true,
      unique: true
    },
    name: {
      type: String,
      required: true,
      unique: true
    },
    positionsIds: [{
      type: Schema.Types.ObjectId,
      ref: 'Position',
      require: false
  }
);

module.exports = mongoose.model('Company', schema);

-----------------------------

const schema = new Schema(
  {
    title: {
      type: String,
      required: true
    },
    requirements: [{
      years: { type: Number, required: false },
      skill: { type: String, required: false },
    }],
    companyId: {
      type: Schema.Types.ObjectId,
      ref: 'Company',
      required: true
    },
  }
);

module.exports = mongoose.model('Position', schema );

---------------------------

    let companies = await Company.aggregate([
      {
        $lookup:
        {
          from: 'Position',
          localField: '_id',
          foreignField: 'companyId',
          as: 'positions'
        }
      },
      // {
      //     $unwind: '$positions' // - mess the query even more and return an empty array
      // },
      ]);

Body:
Mongoose creates MongoDB collections based on convention. Position as model name gets translated into plural form positions so your query should look like:

{
    $lookup: {
        from: 'positions',
        localField: '_id',
        foreignField: 'companyId',
        as: 'positions'
    }
}

The first argument is the singular name of the collection your model is for. ** Mongoose automatically looks for the plural, lowercased version of your model name. ** Thus, for the example above, the model Tank is for the tanks collection in the database.