问:
Atomically exchange value on result of comparison
I have a very simple operation that needs to be done atomically:

```<code>if (a > b)
  b = a
</code>```

where a and b are ints

EDIT: and a is local.

Is there a fast way to do this in C#? I'd like to avoid locking manually if possible. I've looked at Interlocked.CompareExchange, but as I understand it, this only tests for equality.

Thanks!

答:
Henning is correct. I will provide the details as they pertain to C#. The pattern can be generalized with the following function.

```<code>public static T InterlockedOperation<T>(ref T location, T operand)
{
  T initial, computed;
  do
  {
    initial = location;
    computed = op(initial, operand); // where op is replaced with a specific implementation
  }
  while (Interlocked.CompareExchange(ref location, computed, initial) != initial);
  return computed;
}
</code>```

In your specific case we can define an InterlockedGreaterThanExchange function like this.

```<code>public static int InterlockedGreaterThanExchange(ref int location, int value)
{
  int initial, computed;
  do
  {
    initial = location;
    computed = value > initial ? value : initial;
  }
  while (Interlocked.CompareExchange(ref location, computed, initial) != initial);
  return computed;
}
</code>```

Body:
I have a very simple operation that needs to be done atomically:

if (a > b)
  b = a

where a and b are ints

EDIT: and a is local.

Is there a fast way to do this in C#? I'd like to avoid locking manually if possible. I've looked at Interlocked.CompareExchange, but as I understand it, this only tests for equality.

Thanks!

Body:
Henning is correct. I will provide the details as they pertain to C#. The pattern can be generalized with the following function.

public static T InterlockedOperation<T>(ref T location, T operand)
{
  T initial, computed;
  do
  {
    initial = location;
    computed = op(initial, operand); // where op is replaced with a specific implementation
  }
  while (Interlocked.CompareExchange(ref location, computed, initial) != initial);
  return computed;
}

In your specific case we can define an InterlockedGreaterThanExchange function like this.

public static int InterlockedGreaterThanExchange(ref int location, int value)
{
  int initial, computed;
  do
  {
    initial = location;
    computed = value > initial ? value : initial;
  }
  while (Interlocked.CompareExchange(ref location, computed, initial) != initial);
  return computed;
}


来源: stackexchange

问:
parsing jq returns null
I have a json output

```<code>{
    "7": [
        {
            "devices": [
                "/dev/sde"
            ],
            "name": "osd-block-dcc9b386-529c-451e-9d84-8ccc4091102b",
            "tags": {
                "ceph.crush_device_class": "None",
                "ceph.db_device": "/dev/nvme0n1p5",
                "ceph.wal_device": "/dev/nvme0n1p6",
            },
            "type": "block",
            "vg_name": "ceph-c4de9e90-853e-4569-b04f-8677ef9a8c7a"
        },
        {
            "path": "/dev/nvme0n1p5",
            "tags": {
                "PARTUUID": "69712eb4-be52-4618-ba46-e317d6d3d76e"
            },
            "type": "db"
        }
    ],
    "41": [
        {
            "devices": [
                "/dev/nvme1n1p13"
            ],
            "name": "osd-block-97bce07f-ae98-4fdb-83a9-9fa2f35cee60",
            "tags": {
                "ceph.crush_device_class": "None",
            },
            "type": "block",
            "vg_name": "ceph-c1d48671-2a33-4615-95e3-cc1b18783f0c"
        }
    ],
    "9": [
        {
            "devices": [
                "/dev/sdf"
            ],
            "name": "osd-block-35323eb8-17c1-460d-8cc5-565f549e6991",
            "tags": {
                "ceph.crush_device_class": "None",
                "ceph.db_device": "/dev/nvme0n1p7",
                "ceph.wal_device": "/dev/nvme0n1p8",
            },
            "type": "block",
            "vg_name": "ceph-9488e8b8-ec18-4860-93d3-6a1ad91c698c"
        },
        {
            "path": "/dev/nvme0n1p7",
            "tags": {
                "PARTUUID": "ef0e9588-2a20-4c2c-8b62-d73945e01322"
            },
            "type": "db"
        }
    ]
}
</code>```

Required output:

```<code>osd.7 /dev/sde /dev/nvme0n1p5 /dev/nvme0n1p6
osd.41 /dev/nvme1n1p13 n/a n/a
osd.9 /dev/sdf /dev/nvme0n1p7 /dev/nvme0n1p7
</code>```

Problems:
When I try parsing using jq .[][].devices, I get null values:

```<code>$ cat json | jq .[][].devices
[
  "/dev/sde"
]
null
[
  "/dev/nvme1n1p13"
]
null
[
  "/dev/sdf"
]
null
</code>```

I can solve it via jq .[][].devices[]?.

However, this trick doesn't help me when I do want to see where there's no value (to print n/a instead):

```<code>$ cat json | jq '.[][].tags | ."ceph.db_device"'
"/dev/nvme0n1p5"
null
"/dev/nvme0n1p3"
null
null
"/dev/nvme0n1p7"
null
</code>```

And finally, I try to create a table:

```<code>$ cat json | jq -r '["osd."+keys[]], [.[][].devices[]?], [.[][].tags."ceph.db_device" // ""] | @csv' | column -t -s,
"osd.7"           "osd.41"          "osd.9"
"/dev/sde"        "/dev/nvme0n1p13" "/dev/sdf"
"/dev/nvme0n1p5"  "/dev/nvme0n1p7"
</code>```

So the obvious problem is that the 3rd row doesn't match the correct values.

And the final problem is how do I transpose it from columns to rows, as detailed in the required output?

答:
Would this do what you want?

jq --raw-output '
  to_entries[] | [
    "osd." + .key,
    ( .value[0]
    | .devices[],
      ( .tags
      | ."ceph.db_device" // "n/a",
        ."ceph.wal_device" // "n/a"
      )
    )
  ]
  | @tsv
'
```
```osd.7   /dev/sde    /dev/nvme0n1p5  /dev/nvme0n1p6
osd.41  /dev/nvme1n1p13 n/a n/a
osd.9   /dev/sdf    /dev/nvme0n1p7  /dev/nvme0n1p8
```

Demo

ContentLicense: CC BY-SA 4.0

Title: parsing jq returns null

Body:
I have a json output

{
    "7": [
        {
            "devices": [
                "/dev/sde"
            ],
            "name": "osd-block-dcc9b386-529c-451e-9d84-8ccc4091102b",
            "tags": {
                "ceph.crush_device_class": "None",
                "ceph.db_device": "/dev/nvme0n1p5",
                "ceph.wal_device": "/dev/nvme0n1p6",
            },
            "type": "block",
            "vg_name": "ceph-c4de9e90-853e-4569-b04f-8677ef9a8c7a"
        },
        {
            "path": "/dev/nvme0n1p5",
            "tags": {
                "PARTUUID": "69712eb4-be52-4618-ba46-e317d6d3d76e"
            },
            "type": "db"
        }
    ],
    "41": [
        {
            "devices": [
                "/dev/nvme1n1p13"
            ],
            "name": "osd-block-97bce07f-ae98-4fdb-83a9-9fa2f35cee60",
            "tags": {
                "ceph.crush_device_class": "None",
            },
            "type": "block",
            "vg_name": "ceph-c1d48671-2a33-4615-95e3-cc1b18783f0c"
        }
    ],
    "9": [
        {
            "devices": [
                "/dev/sdf"
            ],
            "name": "osd-block-35323eb8-17c1-460d-8cc5-565f549e6991",
            "tags": {
                "ceph.crush_device_class": "None",
                "ceph.db_device": "/dev/nvme0n1p7",
                "ceph.wal_device": "/dev/nvme0n1p8",
            },
            "type": "block",
            "vg_name": "ceph-9488e8b8-ec18-4860-93d3-6a1ad91c698c"
        },
        {
            "path": "/dev/nvme0n1p7",
            "tags": {
                "PARTUUID": "ef0e9588-2a20-4c2c-8b62-d73945e01322"
            },
            "type": "db"
        }
    ]
}

Required output:

osd.7 /dev/sde /dev/nvme0n1p5 /dev/nvme0n1p6
osd.41 /dev/nvme1n1p13 n/a n/a
osd.9 /dev/sdf /dev/nvme0n1p7 /dev/nvme0n1p7

Problems:
When I try parsing using jq .[][].devices, I get null values:

$ cat json | jq .[][].devices
[
  "/dev/sde"
]
null
[
  "/dev/nvme1n1p13"
]
null
[
  "/dev/sdf"
]
null

I can solve it via jq .[][].devices[]?.

However, this trick doesn't help me when I do want to see where there's no value (to print n/a instead):

$ cat json | jq '.[][].tags | ."ceph.db_device"'
"/dev/nvme0n1p5"
null
"/dev/nvme0n1p3"
null
null
"/dev/nvme0n1p7"
null

And finally, I try to create a table:

$ cat json | jq -r '["osd."+keys[]], [.[][].devices[]?], [.[][].tags."ceph.db_device" // ""] | @csv' | column -t -s,
"osd.7"           "osd.41"          "osd.9"
"/dev/sde"        "/dev/nvme0n1p13" "/dev/sdf"
"/dev/nvme0n1p5"  "/dev/nvme0n1p7"

So the obvious problem is that the 3rd row doesn't match the correct values.

And the final problem is how do I transpose it from columns to rows, as detailed in the required output?

Body:
Would this do what you want?

jq --raw-output '
  to_entries[] | [
    "osd." + .key,
    ( .value[0]
    | .devices[],
      ( .tags
      | ."ceph.db_device" // "n/a",
        ."ceph.wal_device" // "n/a"
      )
    )
  ]
  | @tsv
'

osd.7   /dev/sde    /dev/nvme0n1p5  /dev/nvme0n1p6
osd.41  /dev/nvme1n1p13 n/a n/a
osd.9   /dev/sdf    /dev/nvme0n1p7  /dev/nvme0n1p8

Demo


问:
How to prevent Jetpack Compose ExposedDropdownMenuBox from showing menu when scrolling
I'm trying to use Jetpack Compose's ExposedDropdownMenuBox but I can't prevent it from showing the menu when scrolling.

For example, here's the code to replicate this problem:

```<code>class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                Surface(color = MaterialTheme.colors.background) {
                    Column(
                        modifier = Modifier
                            .padding(horizontal = 8.dp)
                            .verticalScroll(rememberScrollState()),
                        verticalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        repeat(20){
                            ExposedDropdownMenuSample()
                        }
                    }
                }
            }
        }
    }
}
</code>```

ExposedDropdownMenuSample was taken from the official samples.

This is a GIF showing the problem.

How can I prevent this from happening?

This code is using compose version 1.1.0-rc01.

答:
I found a slightly less hacky workaround:

You get the info whether a scrolling is in progress from the scroll-state of the Column.

```<code>val scrollState = rememberScrollState()
val isScrolling = scrollState.isScrollInProgress

Column(
  modifier = Modifier
    .padding(horizontal = 8.dp)
    .verticalScroll(scrollState),
    ...
) ...

</code>```

In the ExposedDropdownMenuBox you can then change the listener to

```<code>onExpandedChange = {
  expanded = !expanded && !isScrolling
},
</code>```

=> The dropdown is never opened while scrolling. It is also automatically closed as soon as you start scrolling in the main-column. However scrolling inside the dropdown is possible.
Of course you can also cahnge it to something like

```<code>expanded = if (isScrolling) expanded else !expanded
</code>```

To just leave everything like it is while scrolling

Body:
I'm trying to use Jetpack Compose's ExposedDropdownMenuBox but I can't prevent it from showing the menu when scrolling.

For example, here's the code to replicate this problem:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                Surface(color = MaterialTheme.colors.background) {
                    Column(
                        modifier = Modifier
                            .padding(horizontal = 8.dp)
                            .verticalScroll(rememberScrollState()),
                        verticalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        repeat(20){
                            ExposedDropdownMenuSample()
                        }
                    }
                }
            }
        }
    }
}

ExposedDropdownMenuSample was taken from the official samples.

This is a GIF showing the problem.

How can I prevent this from happening?

This code is using compose version 1.1.0-rc01.

Body:
I found a slightly less hacky workaround:

You get the info whether a scrolling is in progress from the scroll-state of the Column.

val scrollState = rememberScrollState()
val isScrolling = scrollState.isScrollInProgress

Column(
  modifier = Modifier
    .padding(horizontal = 8.dp)
    .verticalScroll(scrollState),
    ...
) ...

In the ExposedDropdownMenuBox you can then change the listener to

onExpandedChange = {
  expanded = !expanded && !isScrolling
},

=> The dropdown is never opened while scrolling. It is also automatically closed as soon as you start scrolling in the main-column. However scrolling inside the dropdown is possible.
Of course you can also cahnge it to something like

expanded = if (isScrolling) expanded else !expanded

To just leave everything like it is while scrolling


问:
Symfony 6 - lexik JWT - Authenticator does not support the request
I'm having some problems with lexik JWT bundle and Symfony 6.0, for swagger I use NelmioApiDocBundle.

The thing is, that every in swagger works before I decide to apply my Authorization Token (Bearer token), which is generated from lexik JWT. But once I get my token generated through /api/sign/in endpoint, and put it into the field, suddenly all endpoints stop working. Like the swagger has this loading animation, but no request comes (tested with xDebug, but also symfony profiler).

Funny thing is when I use Postman and apply the token there, I immediately get a correct response. So I'm not sure where or what's the problem, but when calling from Swagger, I can see docker debug messages saying:  PHP message: [debug] Authenticator does not support the request.

I will put my configuration below. Thanks in advance.

lexik_jwt_authentication.yaml:

```<code>lexik_jwt_authentication:
    secret_key: '%env(resolve:JWT_SECRET_KEY)%'
    public_key: '%env(resolve:JWT_PUBLIC_KEY)%'
    pass_phrase: '%env(JWT_PASSPHRASE)%'
    token_ttl: 8640000
    user_id_claim: id
    user_identity_field: email
</code>```

security.yaml

```<code>security:
    enable_authenticator_manager: true

    password_hashers:
        App\Entity\User:
            algorithm: bcrypt
            cost: 10

    providers:
        app_user_provider:
            entity:
                class: App\Entity\User
                property: email

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        login:
            pattern: ^/api/sign
            stateless: true
            provider: app_user_provider
            json_login:
                check_path: /api/sign/in
                username_path: email
                password_path: password
                success_handler: lexik_jwt_authentication.handler.authentication_success
                failure_handler: lexik_jwt_authentication.handler.authentication_failure

        api:
            provider: app_user_provider
            pattern: ^/api
            stateless: true
            jwt: ~

    access_control:
        - { path: ^/api/sign/, roles: PUBLIC_ACCESS }
        - { path: ^/api/(doc|doc.json), roles: PUBLIC_ACCESS }
        - { path: ^/api, roles: IS_AUTHENTICATED_FULLY }
</code>```

nelmio_api_doc.yaml

```<code>nelmio_api_doc:
    documentation:
        servers:
            - url: http://bp.project

        info:
            title: BP PROJECT
            description: This is an awesome app!
            version: 1.0.0
        components:
            securitySchemes:
                Bearer:
                    type: http
                    scheme: bearer
                    bearerFormat: JWT
        security:
            Bearer: [ ]
    areas: # to filter documented areas
        path_patterns: # an array of regexps
            - ^/api(?!/(doc|doc.json|docs.{_format}|{index}.{_format}|contexts/{shortName}.{_format})$) # Accepts routes under /api except ...

    models: { use_jms: false }
</code>```

答:
Found out api_platform swagger and nelmio are both interacting somehow, since I added this into api_platform.yaml and the header was available in nelmio too, which now works.

```<code>swagger:
    versions: [3]
    api_keys:
        apiKey:
            name: Authorization
            type: header
</code>```

Body:
I'm having some problems with lexik JWT bundle and Symfony 6.0, for swagger I use NelmioApiDocBundle.

The thing is, that every in swagger works before I decide to apply my Authorization Token (Bearer token), which is generated from lexik JWT. But once I get my token generated through /api/sign/in endpoint, and put it into the field, suddenly all endpoints stop working. Like the swagger has this loading animation, but no request comes (tested with xDebug, but also symfony profiler).

Funny thing is when I use Postman and apply the token there, I immediately get a correct response. So I'm not sure where or what's the problem, but when calling from Swagger, I can see docker debug messages saying:  PHP message: [debug] Authenticator does not support the request.

I will put my configuration below. Thanks in advance.

lexik_jwt_authentication.yaml:

lexik_jwt_authentication:
    secret_key: '%env(resolve:JWT_SECRET_KEY)%'
    public_key: '%env(resolve:JWT_PUBLIC_KEY)%'
    pass_phrase: '%env(JWT_PASSPHRASE)%'
    token_ttl: 8640000
    user_id_claim: id
    user_identity_field: email

security.yaml

security:
    enable_authenticator_manager: true

    password_hashers:
        App\Entity\User:
            algorithm: bcrypt
            cost: 10

    providers:
        app_user_provider:
            entity:
                class: App\Entity\User
                property: email

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        login:
            pattern: ^/api/sign
            stateless: true
            provider: app_user_provider
            json_login:
                check_path: /api/sign/in
                username_path: email
                password_path: password
                success_handler: lexik_jwt_authentication.handler.authentication_success
                failure_handler: lexik_jwt_authentication.handler.authentication_failure

        api:
            provider: app_user_provider
            pattern: ^/api
            stateless: true
            jwt: ~

    access_control:
        - { path: ^/api/sign/, roles: PUBLIC_ACCESS }
        - { path: ^/api/(doc|doc.json), roles: PUBLIC_ACCESS }
        - { path: ^/api, roles: IS_AUTHENTICATED_FULLY }

nelmio_api_doc.yaml

nelmio_api_doc:
    documentation:
        servers:
            - url: http://bp.project

        info:
            title: BP PROJECT
            description: This is an awesome app!
            version: 1.0.0
        components:
            securitySchemes:
                Bearer:
                    type: http
                    scheme: bearer
                    bearerFormat: JWT
        security:
            Bearer: [ ]
    areas: # to filter documented areas
        path_patterns: # an array of regexps
            - ^/api(?!/(doc|doc.json|docs.{_format}|{index}.{_format}|contexts/{shortName}.{_format})$) # Accepts routes under /api except ...

    models: { use_jms: false }

Body:
Found out api_platform swagger and nelmio are both interacting somehow, since I added this into api_platform.yaml and the header was available in nelmio too, which now works.

swagger:
    versions: [3]
    api_keys:
        apiKey:
            name: Authorization
            type: header


问:
White area at the bottom of my webpage when i try to create a responsive design
I'm trying to make my webpage responsive to fit on an ipad and mobile, as i adjust my media query, i noticed this white area at the bottom, the body element when highlighted, it doesnt reach that area, so i dont know where it came from, anyhelp would be appreaciated. thanksenter image description here

enter image description here

body{
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    max-width: 100%;
}

.content {
    max-width: 100%;
    margin-left: 0px;
    margin-right: 0px;
    margin-top: 0px;

}

div.logo {
    width: 100%;
    height: 200px;
    background-color: rgb(147, 235, 238);
}

div.navi {

    background-color: rgb(228, 226, 217);
    width: 100%;
    height: 50px;
    margin-top: 15px;
    text-align: center;
    font-size: 19px;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    padding-top: 1px;
    margin-bottom: 1px;
}

p {
    color: rgb(97, 87, 226);
}

.para2{
    color: black;
}
p.nav {
    position: relative;
    bottom: 5px;
    border-style: solid;

}

a:link {
    text-decoration: none;
    color: rgb(97, 87, 226);
}

img {
    margin-left: 20px;
    width: 400px;

}

/* inner body styling */

div.inner-body {
    background-image: url(image/book2.png);
    margin-bottom: 20px;
    margin-right: 0px;
    max-width: 100%;
    border-style: solid;
    margin-top: 20px;
    height: 1200px;
  position: relative;
}

.header {

    width: 700px;
    position: relative;
    left:1000px;
    left: 338px;
    font-size: 30px;

}

.para {

    width: 800px;
    position: relative;
    left:345px;
    top:74px;
    background-color: rgb(206, 200, 180);
    font-size: 25px;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    border-radius: 20px;
    padding: 5px;
}

form {
    padding: 20px;
    border-radius: 20px;
    width: fit-content;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    position: relative;
    left:350px;
    top:100px;
    background-color: rgb(240, 239, 228);
}

.error {
    color: red;
    font-size: 15px;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
}
.error1 {
    color: red;
    font-size: 15px;
    font-family:Verdana, Geneva, Tahoma, sans-serif;
}
.navi2 {

    width: fit-content;
    width: 300px;
    height: 600px;
    position:absolute;
    bottom: 600px;
    background-color: cadetblue;
    font-size: 20px;
    border-radius: 20px;
    top:300px;
}

.user-links {
    position: relative;
    left:20px;
    bottom:30px;
}

.user-links:link{
    color: brown;
}

.userlogo {
    width: 200px;
    border-radius: 100px;
    position: relative;
    left: 30px;
    bottom: 100px;
}

.btn {
    width: 100px;
    border-radius: 5px;
    margin-top: 10px;
}

/* footer styling */

.emaillogo, .telelogo {
    width: 20px;
}
div.foot {

    background-color: brown;
}
footer{
    background-color: rgb(126, 226, 230);
    height: 200px;
}

.footimage {
    width: 400px;
    height: fit-content;
    margin: 0;
}
div.contact{
    width: fit-content;
    height: 200px;
    height: fit-content;
    position: relative;
    left: 400px;
    bottom: 185px;
    font-size: 12px;

}

.usefullinks {
    width: fit-content;
    font-size: 12px;
    position: relative;
    left:750px;
    bottom:280px;
height: fit-content;
}

.connect {
    width: fit-content;
    position: relative;
    left: 1000px ;
    bottom: 400px;
    font-size: 12px;
    height: fit-content;
}

.fb, .tw, .yt, .ln {
    width: 50px;
    border-radius: 10px;

}

/* Media Queries */

@media screen and (max-width:915px) {

    div.logo {
        width: 100%;
        height: 200px;
        background-color: rgb(147, 235, 238);
    }
    .content{
        width: 100%;
        margin: 10px;
        padding: 0;

    }

    div.inner-body {
        background-image: url(image/book2.png);

        border-style: solid;
      margin-top: 15px;
      margin-bottom: 15px;
        width: 100%;
      position: relative;

    }

    div.navi {
        width: 980px;
        font-size: 30px;

        padding-bottom: 90px;
    }
    .inner-body {
        width: 100%;

    }

    .header{
        left:50px;
    }

    .para{
        width: 700px;
        display: block;
        left: 25px;
        font-size: 35px;
        padding:30px;
        top:20px;
    }

    form {
        width: 600px;
        left: 60px;
        font-size: 20px;
    }

    .navi2 {

        display: none;
    }

    .usefullinks{
        display: inline-block;
    }

    .connect{
        display: none;
    }

    .contact {
        display: block;
    }
}

@media screen and (max-width:415px) {
    .content{
        width: 100%;
        margin: 0;
        padding: 0;
    }
    body {
        margin: 0;
    }
    .inner-body {
        width: 100%;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="log-it-reports.css">
    <script src="log-it-reports.js"></script>
    <title>Document</title>
</head>

<body>
    <div class= "content">
        <div class="logo">
        <img src="image/logo1.png" alt="Academy Logo" >
        </div>
        <div class="navi">
            <p id="nav">
                 Home |
                Academics |
                Services |
                Covid-19 |
                Students & Parents |
                Transcripts  |
                Staff |
                Career |
                Events |
                Student Account |
        </p>
        </div>
       <div class="inner-body">
           <div class = "header" >
            <h1>Steps For IT-Issues Logging:</h1>
           </div>

       <div class="para">
           <p class="para2">Please read the following instructions before submitting a report:</p>
           <ol>
               <li>Fill out all of the fields.</li>
               <li>Use a valid email.</li>
               <li>Select a problem type.</li>
               <li>Be as detailed as possible so that the IT staff could address the issue properly (100 characters minumum).</li>
               <li>Normally most issues get addressed within 2 hours, please be patient.</li>
           </ol>
       </div>
       <div class="form1">
        <form  method="GET" onsubmit=" return formValidations() " action="log-it-reports.html"><br>
          <div class="error1" id= "errorMsg"></div>
          <div>
          <label for="subject"><b>Subject:</label>
          <input id="subject" type="text" placeholder="Subject Title"  >
          </div><br>
          <div class="error" id= "errorMsg2"></div>
          <div>
          <label for="email"><b>Email:</label>
          <input id="email" type="email" placeholder="staff@wearview.com">
          </div><br>
          <div class="error" id= "errorMsg3"></div>
          <div>
            <select name="techtype" id="problemtypes">
                <option value="">Problem Type</option>
                <option value="Hardware">Hardware</option>
                <option value="Software">Software</option>
                <option value="Other">Other</option>
              </select>
          </div><br>
          <div class="error" id= "errorMsg4"></div>
          <div>
          <textarea id="description" placeholder="Description goes here" name="descript" rows="15" cols="50"></textarea>
          </div>

          <div>
            <button type="submit" class="btn">Submit</button>
            <input type="checkbox" id="notify" name="notify" value="">
            <label for="notify">Inform me by email when issue is resolved.</label>
        </div>
        </form>
       </div>
       <div class="navi2">
           <div class="userimage">
               <img class="userlogo" src="image/userlogo.png" alt="User Image">
           </div>
           <div class="user-links">
               <navi>
                Staff Name <br><br>
                Inbox <br><br>
                Notifications <br><br>
                Files <br><br>
                Settings <br><br>
                Help  <br><br>
                QR For Mobile <br><br>
                Log Out
               </navi>
           </div>
       </div>
    </div>
       <div class="foot">
           <footer id = "footy">
           <div>
            <img class="footimage" src="image/logo1.png" alt="Academy Logo"  width="400px">
           </div>
           <div class="contact">
               <h3>Contact Us</h3>
                <p><img class="emaillogo" src="image/email (2).png" alt="emaillogo"> :wearview_academy@wearview.com</p>
              <p><img class="telelogo" src="image/tele.png" alt="telelogo"> :+2499100000000</p>
           </div>
           <div class="usefullinks">
            <h3>Useful Links</h3>
            <ul>
                <li>Career</li>
                <li>Report A Website Issue</li>
                <li>About Us</li>
                <li>Covid-19</li>
                <li>Events</li>
            </ul>
           </div>
           <div class="connect">
            <h3>Connect With Us </h3><br>
                <img class="fb" src="image/fb.png" alt = "Facebook" />
                <img class="tw" src="image/tw.jpg" alt = "Twitter" />
                <img class="yt" src="image/you.png" alt = "Youtube" />
                <img class="ln" src="image/linkd.png" alt = "LinkedIn" />
           </div>
           </footer>
       </div>
    </div>
</body>
</html></code>```

答:
Because of the default browser stylesheet, the body has a margin set. You can remove it with the following CSS reset:

body {
    margin: 0;
}
```
<p>Also, your <code>.content</code> has a margin set to <code>10px</code>, which adds space to the bottom, remove it when you don't want it or only apply it to the top, right and left using:</p>
<pre class="lang-css prettyprint-override"><code>margin: 10px 10px 0 10px
</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="log-it-reports.css">

    <title>Document</title>

                 Home |
                Academics |
                Services |
                Covid-19 |
                Students & Parents |
                Transcripts |
                Staff |
                Career |
                Events |
                Student Account |

Steps For IT-Issues Logging:

Please read the following instructions before submitting a report:

Fill out all of the fields.

Use a valid email.

Select a problem type.

Be as detailed as possible so that the IT staff could address the issue properly (100 characters
                        minumum).

Normally most issues get addressed within 2 hours, please be patient.

                <form method="GET" onsubmit=" return formValidations() " action="log-it-reports.html">

                        Subject:
                        <input id="subject" type="text" placeholder="Subject Title">

                        Email:
                        <input id="email" type="email" placeholder="staff@wearview.com">

                        <select name="techtype" id="problemtypes">
                            <option value="">Problem Type</option>
                            <option value="Hardware">Hardware</option>
                            <option value="Software">Software</option>
                            <option value="Other">Other</option>
                        </select>

                        <textarea id="description" placeholder="Description goes here" name="descript" rows="15"
                            cols="50"></textarea>

                        <button type="submit" class="btn">Submit</button>
                        <input type="checkbox" id="notify" name="notify" value="">
                        Inform me by email when issue is resolved.

                </form>

                    <navi>
                        Staff Name

                        Inbox

                        Notifications

                        Files

                        Settings

                        Help

                        QR For Mobile

                        Log Out
                    </navi>

Contact Us

 :wearview_academy@wearview.com

 :+2499100000000

Useful Links

Career

Report A Website Issue

About Us

Covid-19

Events

Connect With Us

```

Note that I also removed the height of the footer in the example above, since it causes some spacing as well.

Body:
I'm trying to make my webpage responsive to fit on an ipad and mobile, as i adjust my media query, i noticed this white area at the bottom, the body element when highlighted, it doesnt reach that area, so i dont know where it came from, anyhelp would be appreaciated. thanksenter image description here

enter image description here

body{
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    max-width: 100%;
}

.content {
    max-width: 100%;
    margin-left: 0px;
    margin-right: 0px;
    margin-top: 0px;

}

div.logo {
    width: 100%;
    height: 200px;
    background-color: rgb(147, 235, 238);
}

div.navi {

    background-color: rgb(228, 226, 217);
    width: 100%;
    height: 50px;
    margin-top: 15px;
    text-align: center;
    font-size: 19px;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    padding-top: 1px;
    margin-bottom: 1px;
}

p {
    color: rgb(97, 87, 226);
}

.para2{
    color: black;
}
p.nav {
    position: relative;
    bottom: 5px;
    border-style: solid;

}

a:link {
    text-decoration: none;
    color: rgb(97, 87, 226);
}

img {
    margin-left: 20px;
    width: 400px;

}

/* inner body styling */

div.inner-body {
    background-image: url(image/book2.png);
    margin-bottom: 20px;
    margin-right: 0px;
    max-width: 100%;
    border-style: solid;
    margin-top: 20px;
    height: 1200px;
  position: relative;
}

.header {

    width: 700px;
    position: relative;
    left:1000px;
    left: 338px;
    font-size: 30px;

}

.para {

    width: 800px;
    position: relative;
    left:345px;
    top:74px;
    background-color: rgb(206, 200, 180);
    font-size: 25px;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    border-radius: 20px;
    padding: 5px;
}

form {
    padding: 20px;
    border-radius: 20px;
    width: fit-content;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    position: relative;
    left:350px;
    top:100px;
    background-color: rgb(240, 239, 228);
}

.error {
    color: red;
    font-size: 15px;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
}
.error1 {
    color: red;
    font-size: 15px;
    font-family:Verdana, Geneva, Tahoma, sans-serif;
}
.navi2 {

    width: fit-content;
    width: 300px;
    height: 600px;
    position:absolute;
    bottom: 600px;
    background-color: cadetblue;
    font-size: 20px;
    border-radius: 20px;
    top:300px;
}

.user-links {
    position: relative;
    left:20px;
    bottom:30px;
}

.user-links:link{
    color: brown;
}

.userlogo {
    width: 200px;
    border-radius: 100px;
    position: relative;
    left: 30px;
    bottom: 100px;
}

.btn {
    width: 100px;
    border-radius: 5px;
    margin-top: 10px;
}

/* footer styling */

.emaillogo, .telelogo {
    width: 20px;
}
div.foot {

    background-color: brown;
}
footer{
    background-color: rgb(126, 226, 230);
    height: 200px;
}

.footimage {
    width: 400px;
    height: fit-content;
    margin: 0;
}
div.contact{
    width: fit-content;
    height: 200px;
    height: fit-content;
    position: relative;
    left: 400px;
    bottom: 185px;
    font-size: 12px;

}

.usefullinks {
    width: fit-content;
    font-size: 12px;
    position: relative;
    left:750px;
    bottom:280px;
height: fit-content;
}

.connect {
    width: fit-content;
    position: relative;
    left: 1000px ;
    bottom: 400px;
    font-size: 12px;
    height: fit-content;
}

.fb, .tw, .yt, .ln {
    width: 50px;
    border-radius: 10px;

}

/* Media Queries */

@media screen and (max-width:915px) {

    div.logo {
        width: 100%;
        height: 200px;
        background-color: rgb(147, 235, 238);
    }
    .content{
        width: 100%;
        margin: 10px;
        padding: 0;

    }

    div.inner-body {
        background-image: url(image/book2.png);

        border-style: solid;
      margin-top: 15px;
      margin-bottom: 15px;
        width: 100%;
      position: relative;

    }

    div.navi {
        width: 980px;
        font-size: 30px;

        padding-bottom: 90px;
    }
    .inner-body {
        width: 100%;

    }

    .header{
        left:50px;
    }

    .para{
        width: 700px;
        display: block;
        left: 25px;
        font-size: 35px;
        padding:30px;
        top:20px;
    }

    form {
        width: 600px;
        left: 60px;
        font-size: 20px;
    }

    .navi2 {

        display: none;
    }

    .usefullinks{
        display: inline-block;
    }

    .connect{
        display: none;
    }

    .contact {
        display: block;
    }
}

@media screen and (max-width:415px) {
    .content{
        width: 100%;
        margin: 0;
        padding: 0;
    }
    body {
        margin: 0;
    }
    .inner-body {
        width: 100%;
    }
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="log-it-reports.css">

    <title>Document</title>

                 Home |
                Academics |
                Services |
                Covid-19 |
                Students & Parents |
                Transcripts  |
                Staff |
                Career |
                Events |
                Student Account |

Steps For IT-Issues Logging:

Please read the following instructions before submitting a report:

Fill out all of the fields.

Use a valid email.

Select a problem type.

Be as detailed as possible so that the IT staff could address the issue properly (100 characters minumum).

Normally most issues get addressed within 2 hours, please be patient.

        <form  method="GET" onsubmit=" return formValidations() " action="log-it-reports.html">

          Subject:
          <input id="subject" type="text" placeholder="Subject Title"  >

          Email:
          <input id="email" type="email" placeholder="staff@wearview.com">

            <select name="techtype" id="problemtypes">
                <option value="">Problem Type</option>
                <option value="Hardware">Hardware</option>
                <option value="Software">Software</option>
                <option value="Other">Other</option>
              </select>

          <textarea id="description" placeholder="Description goes here" name="descript" rows="15" cols="50"></textarea>

            <button type="submit" class="btn">Submit</button>
            <input type="checkbox" id="notify" name="notify" value="">
            Inform me by email when issue is resolved.

        </form>

               <navi>
                Staff Name

                Inbox

                Notifications

                Files

                Settings

                Help

                QR For Mobile

                Log Out
               </navi>

Contact Us

 :wearview_academy@wearview.com

 :+2499100000000

Useful Links

Career

Report A Website Issue

About Us

Covid-19

Events

Connect With Us

Body:
Because of the default browser stylesheet, the body has a margin set. You can remove it with the following CSS reset:

body {
    margin: 0;
}

Also, your .content has a margin set to 10px, which adds space to the bottom, remove it when you don't want it or only apply it to the top, right and left using:

margin: 10px 10px 0 10px

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="log-it-reports.css">
    <script src="log-it-reports.js"></script>
    <title>Document</title>

    <style>
        body {
            font-family: Verdana, Geneva, Tahoma, sans-serif;
            max-width: 100%;
            margin: 0
        }

        .content {
            max-width: 100%;
            margin-left: 0px;
            margin-right: 0px;
            margin-top: 0px;

        }

        div.logo {
            width: 100%;
            height: 200px;
            background-color: rgb(147, 235, 238);
        }

        div.navi {

            background-color: rgb(228, 226, 217);
            width: 100%;
            height: 50px;
            margin-top: 15px;
            text-align: center;
            font-size: 19px;
            font-family: Verdana, Geneva, Tahoma, sans-serif;
            padding-top: 1px;
            margin-bottom: 1px;
        }

        p {
            color: rgb(97, 87, 226);
        }

        .para2 {
            color: black;
        }

        p.nav {
            position: relative;
            bottom: 5px;
            border-style: solid;

        }

        a:link {
            text-decoration: none;
            color: rgb(97, 87, 226);
        }

        img {
            margin-left: 20px;
            width: 400px;

        }

        /* inner body styling */

        div.inner-body {
            background-image: url(image/book2.png);
            margin-bottom: 20px;
            margin-right: 0px;
            max-width: 100%;
            border-style: solid;
            margin-top: 20px;
            height: 1200px;
            position: relative;
        }

        .header {

            width: 700px;
            position: relative;
            left: 1000px;
            left: 338px;
            font-size: 30px;

        }

        .para {

            width: 800px;
            position: relative;
            left: 345px;
            top: 74px;
            background-color: rgb(206, 200, 180);
            font-size: 25px;
            font-family: Verdana, Geneva, Tahoma, sans-serif;
            border-radius: 20px;
            padding: 5px;
        }

        form {
            padding: 20px;
            border-radius: 20px;
            width: fit-content;
            font-family: Verdana, Geneva, Tahoma, sans-serif;
            position: relative;
            left: 350px;
            top: 100px;
            background-color: rgb(240, 239, 228);
        }

        .error {
            color: red;
            font-size: 15px;
            font-family: Verdana, Geneva, Tahoma, sans-serif;
        }

        .error1 {
            color: red;
            font-size: 15px;
            font-family: Verdana, Geneva, Tahoma, sans-serif;
        }

        .navi2 {

            width: fit-content;
            width: 300px;
            height: 600px;
            position: absolute;
            bottom: 600px;
            background-color: cadetblue;
            font-size: 20px;
            border-radius: 20px;
            top: 300px;
        }

        .user-links {
            position: relative;
            left: 20px;
            bottom: 30px;
        }

        .user-links:link {
            color: brown;
        }

        .userlogo {
            width: 200px;
            border-radius: 100px;
            position: relative;
            left: 30px;
            bottom: 100px;
        }

        .btn {
            width: 100px;
            border-radius: 5px;
            margin-top: 10px;
        }

        /* footer styling */

        .emaillogo,
        .telelogo {
            width: 20px;
        }

        div.foot {

            background-color: brown;
        }

        footer {
            background-color: rgb(126, 226, 230);
            /* height: 200px; */
        }

        .footimage {
            width: 400px;
            height: fit-content;
            margin: 0;
        }

        div.contact {
            width: fit-content;
            height: 200px;
            height: fit-content;
            position: relative;
            left: 400px;
            bottom: 185px;
            font-size: 12px;

        }

        .usefullinks {
            width: fit-content;
            font-size: 12px;
            position: relative;
            left: 750px;
            bottom: 280px;
            height: fit-content;
        }

        .connect {
            width: fit-content;
            position: relative;
            left: 1000px;
            bottom: 400px;
            font-size: 12px;
            height: fit-content;
        }

        .fb,
        .tw,
        .yt,
        .ln {
            width: 50px;
            border-radius: 10px;

        }

        /* Media Queries */

        @media screen and (max-width:915px) {

            div.logo {
                width: 100%;
                height: 200px;
                background-color: rgb(147, 235, 238);
            }

            .content {
                width: 100%;
                /* margin: 10px; */
                padding: 0;

            }

            div.inner-body {
                background-image: url(image/book2.png);

                border-style: solid;
                margin-top: 15px;
                margin-bottom: 15px;
                width: 100%;
                position: relative;

            }

            div.navi {
                width: 980px;
                font-size: 30px;

                padding-bottom: 90px;
            }

            .inner-body {
                width: 100%;

            }

            .header {
                left: 50px;
            }

            .para {
                width: 700px;
                display: block;
                left: 25px;
                font-size: 35px;
                padding: 30px;
                top: 20px;
            }

            form {
                width: 600px;
                left: 60px;
                font-size: 20px;
            }

            .navi2 {

                display: none;
            }

            .usefullinks {
                display: inline-block;
            }

            .connect {
                display: none;
            }

            .contact {
                display: block;
            }
        }

        @media screen and (max-width:415px) {
            .content {
                width: 100%;
                margin: 0;
                padding: 0;
            }

            body {
                margin: 0;
            }

            .inner-body {
                width: 100%;
            }
        }
    </style>
</head>

<body>
    <div class="content">
        <div class="logo">
            <img src="image/logo1.png" alt="Academy Logo">
        </div>
        <div class="navi">
            <p id="nav">
                <a href="homepage.html" title=" Home Page"> Home</a> |
                <a href="academics.html" title=" Academics Page">Academics</a> |
                <a href="services.html" title=" Services">Services</a> |
                <a href="covid-19.html" title=" Covid-19 Page">Covid-19</a> |
                <a href="students&parents.html" title=" Students&Parents Page">Students & Parents</a> |
                <a href="Transcripts.html" title="Transcripts Page">Transcripts</a> |
                <a href="staff.html" title="Staff Page">Staff</a> |
                <a href="career.html" title="Career Available">Career</a> |
                <a href="events" title="Events Page">Events</a> |
                <a href="studentaccount.html" title="Student Account">Student Account</a> |
            </p>
        </div>
        <div class="inner-body">
            <div class="header">
                <h1>Steps For IT-Issues Logging:</h1>
            </div>

            <div class="para">
                <p class="para2">Please read the following instructions before submitting a report:</p>
                <ol>
                    <li>Fill out all of the fields.</li>
                    <li>Use a valid email.</li>
                    <li>Select a problem type.</li>
                    <li>Be as detailed as possible so that the IT staff could address the issue properly (100 characters
                        minumum).</li>
                    <li>Normally most issues get addressed within 2 hours, please be patient.</li>
                </ol>
            </div>
            <div class="form1">
                <form method="GET" onsubmit=" return formValidations() " action="log-it-reports.html"><br>
                    <div class="error1" id="errorMsg"></div>
                    <div>
                        <label for="subject"><b>Subject:</label>
                        <input id="subject" type="text" placeholder="Subject Title">
                    </div><br>
                    <div class="error" id="errorMsg2"></div>
                    <div>
                        <label for="email"><b>Email:</label>
                        <input id="email" type="email" placeholder="staff@wearview.com">
                    </div><br>
                    <div class="error" id="errorMsg3"></div>
                    <div>
                        <select name="techtype" id="problemtypes">
                            <option value="">Problem Type</option>
                            <option value="Hardware">Hardware</option>
                            <option value="Software">Software</option>
                            <option value="Other">Other</option>
                        </select>
                    </div><br>
                    <div class="error" id="errorMsg4"></div>
                    <div>
                        <textarea id="description" placeholder="Description goes here" name="descript" rows="15"
                            cols="50"></textarea>
                    </div>

                    <div>
                        <button type="submit" class="btn">Submit</button>
                        <input type="checkbox" id="notify" name="notify" value="">
                        <label for="notify">Inform me by email when issue is resolved.</label>
                    </div>
                </form>
            </div>
            <div class="navi2">
                <div class="userimage">
                    <img class="userlogo" src="image/userlogo.png" alt="User Image">
                </div>
                <div class="user-links">
                    <navi>
                        <a class="staffname" href="staffname.html" title=" Staff Name">Staff Name</a> <br><br>
                        <a href="inbox.html" title=" User Inbox">Inbox</a> <br><br>
                        <a href="notifications.html" title="Notifications">Notifications</a> <br><br>
                        <a href="files.html" title="Files">Files</a> <br><br>
                        <a href="settings.html" title="Settings">Settings</a> <br><br>
                        <a href="help.html" title="Help">Help</a> <br><br>
                        <a href="qr-for-mobile.html" title="QR for Mobile">QR For Mobile</a> <br><br>
                        <a href="logout.html" title="Log Out">Log Out</a>
                    </navi>
                </div>
            </div>
        </div>
        <div class="foot">
            <footer id="footy">
                <div>
                    <img class="footimage" src="image/logo1.png" alt="Academy Logo" width="400px">
                </div>
                <div class="contact">
                    <h3>Contact Us</h3>
                    <p><img class="emaillogo" src="image/email (2).png" alt="emaillogo"> :wearview_academy@wearview.com
                    </p>
                    <p><img class="telelogo" src="image/tele.png" alt="telelogo"> :+2499100000000</p>
                </div>
                <div class="usefullinks">
                    <h3>Useful Links</h3>
                    <ul>
                        <li><a href="career.html" title=" Jobs Available">Career</a></li>
                        <li><a href="websiteerror.html" title=" Report A Website Issue">Report A Website Issue</a></li>
                        <li><a href="aboutus.html" title="About Us">About Us</a></li>
                        <li><a href="covid-19.html" title="Covid-19">Covid-19</a></li>
                        <li><a href="events" title=" FAQs Page">Events</a></li>
                    </ul>
                </div>
                <div class="connect">
                    <h3>Connect With Us </h3><br>
                    <a href="https://www.facebook.com" title="facebook"><img class="fb" src="image/fb.png"
                            alt="Facebook" /></a>
                    <a href="https://www.twitter.com" title="twitter"><img class="tw" src="image/tw.jpg"
                            alt="Twitter" /></a>
                    <a href="https://www.youtube.com" title="youtube"><img class="yt" src="image/you.png"
                            alt="Youtube" /></a>
                    <a href="https://www.linkedin.com" title="linkedin"><img class="ln" src="image/linkd.png"
                            alt="LinkedIn" /></a>
                </div>
            </footer>
        </div>
    </div>
</body>

</html>

Note that I also removed the height of the footer in the example above, since it causes some spacing as well.


问:
How to show JList from a blockingQueue?
I'm using multi threading with Java, I have a thread that will post a message into a queue, a blockingQueue which is thread safe, and I have another thread, implementing a GUI with swing.
Everytime I'm checking whether the queue is empty or not, if not, I poll the message and add it to DefaultListModel, but the problem the display is not updated.
I made sure that the message polled is not empty.
This is the code:
For the implementation of the JList

```<code>historyListModel = new DefaultListModel<String>();
        historyList = new JList<String>(historyListModel);
        historyList.setAutoscrolls(true);

        JScrollPane historyScroll = new JScrollPane(historyList);
        add(historyScroll, BorderLayout.CENTER);
</code>```

Adding message to the queue

```<code>private BlockingQueue<String> messageRes = new LinkedBlockingQueue<>();

DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

socket.receive(packet);
String msgReceived = new String(packet.getData(), 0, packet.getLength());

messageRes.add(msgReceived);
</code>```

The thread to update the display

```<code>private class update implements Runnable{

        @Override
        public void run() {
            while (true){

                if (!messageRes.isEmpty()){
                    historyListModel.addElement(messageRes.poll());

                }

            }

        }
    }
</code>```

Then this thread is called in the GUI main window

```<code>new Thread(new update()).start();
</code>```

In order to make some tests, I tried the following code and It worked

```<code>
private class update implements Runnable{

        @Override
        public void run() {
            while (true){

                Thread.sleep(1000)
                historyListModel.addElement("hello world);

            }

        }
    }
</code>```

The previous code allows me to update the display every 1 second.
I tried one more code in order to triangulate the error:

```<code>private class update implements Runnable{

        @Override
        public void run() {
            while (true){

                if (!messageRes.isEmpty()){
                    historyListModel.addElement(messageRes.poll());
                    historyListModel.addElement("hello world);

                }

            }

        }
    }
</code>```

No display was updated with the previous code.
Could anyone propose any explanation to what is happening ?

Thank you.

答:
Swing is not thread-safe and is single-threaded.  This means you should not be updating the UI from outside of the context of the Event Dispatching Thread nor should you be executing long-running/blocking calls within its context.

In your case, a SwingWorker would probably be the best solution, as you can poll the queue for new messages and publish them to the UI in a safe manner.

See...

Concurrency in Swing

Worker Threads and SwingWorker

for more details.

One thing I did note during my testing was this...

```<code>@Override
public void run() {
    while (true){
        if (!messageRes.isEmpty()){
            historyListModel.addElement(messageRes.poll());
        }
    }
}
</code>```

was probably causing the UI to be overloaded, as poll will either return the next element or null if there are none.  So it was a "wild loop".  Instead, you should probably be using take which will wait till a new value is available.

```<code>import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingWorker;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JList<String> messageList;
        private DefaultListModel<String> model;

        public TestPane() {
            model = new DefaultListModel<>();
            messageList = new JList<>(model);
            setLayout(new BorderLayout());
            add(new JScrollPane(messageList));

            Consumer consumer = new Consumer();
            Producer producer = new Producer();

            ConsumerWoker worker = new ConsumerWoker(consumer, model);
            worker.execute();

            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        while (true) {
                            consumer.add(producer.next());
                            Thread.sleep(500);
                        }
                    } catch (InterruptedException ex) {
                    }
                }
            });
            thread.start();
        }

    }

    public class Producer {

        private List<String> master = Arrays.asList(new String[]{
            "Malachy Keller",
            "Ruqayyah Galvan",
            "Harris Nunez",
            "Nojus Riggs",
            "Joan Mercer",
            "Lynda Solomon",
            "Raiden Fitzpatrick",
            "Sebastian Ahmed",
            "Jo Short",
            "Nabeel Howarth",
            "Maira Garrett",
            "Patrik Knights",
            "Mimi Mcgill",
            "Antonina Villanueva",
            "Kenya Hyde",
            "Aleksander Rigby",
            "Hasan Gilmore",
            "Jessica Mcculloch",
            "Seth Black",
            "Marjorie Brewer",
            "Elliot Gay",
            "Oluwatobiloba Bowman",
            "Domonic Saunders",
            "Braden Hale",
            "Muneeb Rankin",
            "Ruby Tapia",
            "Iris Hines",
            "Afsana Ponce",
            "Beverly Soto",
            "Presley Bloggs",
            "Leopold Goddard",
            "Missy Browne",
            "Deniz Woodcock",
            "Gwion Ferreira",
            "Stanley Mccall",
            "Jayda Christie",
            "Nikhil Plummer",
            "Stacy Crosby",
            "Cally Henry",
            "Lilliana Taylor",
            "Dolcie Navarro",
            "Merryn Reynolds",
            "Annalise Boyce",
            "Anaya Cisneros",
            "Aimie Piper",
            "Celine Pearson",
            "Clayton Battle",
            "Danielle Briggs",
            "Maddison Couch",
            "Jorden Keeling",
            "Iylah Holmes",
            "Bethaney Quintero",
            "Dominique Brett",
            "Rohit Benjamin",
            "Edgar Rodgers",
            "Petra Salgado",
            "Myrtle Deleon",
            "Letitia Sheridan",
            "Wasim Chester",
            "Leela Simpson",
            "Aine Rojas",
            "Ava Mclean",
            "Jerry Caldwell",
            "Fraser Prosser",
            "Callum Vang",
            "Yasmin Ochoa",
            "Gaia Daly",
            "Vanessa Mathews",
            "Scarlett Brook",
            "Rhiann Fox",
            "Nansi Cote",
            "Dwayne Rowley",
            "Junior Lucas",
            "Becky Rush",
            "Lori Guthrie",
            "Safa Reed",
            "Merlin Cartwright",
            "Misbah Trejo",
            "Khaleesi Ellison",
            "Lena Wood",
            "Bluebell Coffey",
            "Sherry Hutton",
            "Abi Delacruz",
            "Kwabena Bright",
            "Anastazja Kumar",
            "Bronwyn Huffman",
            "Atif Burke",
            "Arwen Kirby",
            "Bobbie Noble",
            "Blane Bauer",
            "Zander Sparrow",
            "Marius Wormald",
            "Rajan Perez",
            "Teejay Faulkner",
            "Imaani Rodriquez",
            "Safaa Middleton",
            "Rafael Livingston",
            "Oakley Swan",
            "Samiya Kim",
            "Glen Beasley"
        });

        private List<String> avaliableMessages;

        public Producer() {
            avaliableMessages = new ArrayList<>(100);
        }

        public String next() {
            if (avaliableMessages.isEmpty()) {
                avaliableMessages.addAll(master);
            }
            return avaliableMessages.remove(0);
        }
    }

    public class Consumer {

        private BlockingQueue<String> messages = new LinkedBlockingDeque<>();

        public void add(String message) {
            messages.add(message);
        }

        public String next() throws InterruptedException {
            return messages.take();
        }
    }

    public class ConsumerWoker extends SwingWorker<Void, String> {

        private AtomicBoolean keepRunning = new AtomicBoolean(true);

        private Consumer consumer;
        private DefaultListModel model;

        public ConsumerWoker(Consumer consumer, DefaultListModel model) {
            this.consumer = consumer;
            this.model = model;
        }

        public void stop() {
            keepRunning.set(false);
        }

        public Consumer getConsumer() {
            return consumer;
        }

        @Override
        protected Void doInBackground() throws Exception {
            while (keepRunning.get()) {
                String message = getConsumer().next();
                publish(message);
            }
            return null;
        }

        @Override
        protected void process(List<String> chunks) {
            for (String msg : chunks) {
                model.addElement(msg);
            }
        }

    }
}
</code>```

Title: How to show JList from a blockingQueue?

Body:
I'm using multi threading with Java, I have a thread that will post a message into a queue, a blockingQueue which is thread safe, and I have another thread, implementing a GUI with swing.
Everytime I'm checking whether the queue is empty or not, if not, I poll the message and add it to DefaultListModel, but the problem the display is not updated.
I made sure that the message polled is not empty.
This is the code:
For the implementation of the JList

historyListModel = new DefaultListModel<String>();
        historyList = new JList<String>(historyListModel);
        historyList.setAutoscrolls(true);

        JScrollPane historyScroll = new JScrollPane(historyList);
        add(historyScroll, BorderLayout.CENTER);

Adding message to the queue

private BlockingQueue<String> messageRes = new LinkedBlockingQueue<>();

DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

socket.receive(packet);
String msgReceived = new String(packet.getData(), 0, packet.getLength());

messageRes.add(msgReceived);

The thread to update the display

private class update implements Runnable{

        @Override
        public void run() {
            while (true){

                if (!messageRes.isEmpty()){
                    historyListModel.addElement(messageRes.poll());

                }

            }

        }
    }

Then this thread is called in the GUI main window

new Thread(new update()).start();

In order to make some tests, I tried the following code and It worked

private class update implements Runnable{

        @Override
        public void run() {
            while (true){

                Thread.sleep(1000)
                historyListModel.addElement("hello world);

            }

        }
    }

The previous code allows me to update the display every 1 second.
I tried one more code in order to triangulate the error:

private class update implements Runnable{

        @Override
        public void run() {
            while (true){

                if (!messageRes.isEmpty()){
                    historyListModel.addElement(messageRes.poll());
                    historyListModel.addElement("hello world);

                }

            }

        }
    }

No display was updated with the previous code.
Could anyone propose any explanation to what is happening ?

Thank you.

Body:
Swing is not thread-safe and is single-threaded.  This means you should not be updating the UI from outside of the context of the Event Dispatching Thread nor should you be executing long-running/blocking calls within its context.

In your case, a SwingWorker would probably be the best solution, as you can poll the queue for new messages and publish them to the UI in a safe manner.

See...

Concurrency in Swing

Worker Threads and SwingWorker

for more details.

One thing I did note during my testing was this...

@Override
public void run() {
    while (true){
        if (!messageRes.isEmpty()){
            historyListModel.addElement(messageRes.poll());
        }
    }
}

was probably causing the UI to be overloaded, as poll will either return the next element or null if there are none.  So it was a "wild loop".  Instead, you should probably be using take which will wait till a new value is available.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingWorker;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JList<String> messageList;
        private DefaultListModel<String> model;

        public TestPane() {
            model = new DefaultListModel<>();
            messageList = new JList<>(model);
            setLayout(new BorderLayout());
            add(new JScrollPane(messageList));

            Consumer consumer = new Consumer();
            Producer producer = new Producer();

            ConsumerWoker worker = new ConsumerWoker(consumer, model);
            worker.execute();

            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        while (true) {
                            consumer.add(producer.next());
                            Thread.sleep(500);
                        }
                    } catch (InterruptedException ex) {
                    }
                }
            });
            thread.start();
        }

    }

    public class Producer {

        private List<String> master = Arrays.asList(new String[]{
            "Malachy Keller",
            "Ruqayyah Galvan",
            "Harris Nunez",
            "Nojus Riggs",
            "Joan Mercer",
            "Lynda Solomon",
            "Raiden Fitzpatrick",
            "Sebastian Ahmed",
            "Jo Short",
            "Nabeel Howarth",
            "Maira Garrett",
            "Patrik Knights",
            "Mimi Mcgill",
            "Antonina Villanueva",
            "Kenya Hyde",
            "Aleksander Rigby",
            "Hasan Gilmore",
            "Jessica Mcculloch",
            "Seth Black",
            "Marjorie Brewer",
            "Elliot Gay",
            "Oluwatobiloba Bowman",
            "Domonic Saunders",
            "Braden Hale",
            "Muneeb Rankin",
            "Ruby Tapia",
            "Iris Hines",
            "Afsana Ponce",
            "Beverly Soto",
            "Presley Bloggs",
            "Leopold Goddard",
            "Missy Browne",
            "Deniz Woodcock",
            "Gwion Ferreira",
            "Stanley Mccall",
            "Jayda Christie",
            "Nikhil Plummer",
            "Stacy Crosby",
            "Cally Henry",
            "Lilliana Taylor",
            "Dolcie Navarro",
            "Merryn Reynolds",
            "Annalise Boyce",
            "Anaya Cisneros",
            "Aimie Piper",
            "Celine Pearson",
            "Clayton Battle",
            "Danielle Briggs",
            "Maddison Couch",
            "Jorden Keeling",
            "Iylah Holmes",
            "Bethaney Quintero",
            "Dominique Brett",
            "Rohit Benjamin",
            "Edgar Rodgers",
            "Petra Salgado",
            "Myrtle Deleon",
            "Letitia Sheridan",
            "Wasim Chester",
            "Leela Simpson",
            "Aine Rojas",
            "Ava Mclean",
            "Jerry Caldwell",
            "Fraser Prosser",
            "Callum Vang",
            "Yasmin Ochoa",
            "Gaia Daly",
            "Vanessa Mathews",
            "Scarlett Brook",
            "Rhiann Fox",
            "Nansi Cote",
            "Dwayne Rowley",
            "Junior Lucas",
            "Becky Rush",
            "Lori Guthrie",
            "Safa Reed",
            "Merlin Cartwright",
            "Misbah Trejo",
            "Khaleesi Ellison",
            "Lena Wood",
            "Bluebell Coffey",
            "Sherry Hutton",
            "Abi Delacruz",
            "Kwabena Bright",
            "Anastazja Kumar",
            "Bronwyn Huffman",
            "Atif Burke",
            "Arwen Kirby",
            "Bobbie Noble",
            "Blane Bauer",
            "Zander Sparrow",
            "Marius Wormald",
            "Rajan Perez",
            "Teejay Faulkner",
            "Imaani Rodriquez",
            "Safaa Middleton",
            "Rafael Livingston",
            "Oakley Swan",
            "Samiya Kim",
            "Glen Beasley"
        });

        private List<String> avaliableMessages;

        public Producer() {
            avaliableMessages = new ArrayList<>(100);
        }

        public String next() {
            if (avaliableMessages.isEmpty()) {
                avaliableMessages.addAll(master);
            }
            return avaliableMessages.remove(0);
        }
    }

    public class Consumer {

        private BlockingQueue<String> messages = new LinkedBlockingDeque<>();

        public void add(String message) {
            messages.add(message);
        }

        public String next() throws InterruptedException {
            return messages.take();
        }
    }

    public class ConsumerWoker extends SwingWorker<Void, String> {

        private AtomicBoolean keepRunning = new AtomicBoolean(true);

        private Consumer consumer;
        private DefaultListModel model;

        public ConsumerWoker(Consumer consumer, DefaultListModel model) {
            this.consumer = consumer;
            this.model = model;
        }

        public void stop() {
            keepRunning.set(false);
        }

        public Consumer getConsumer() {
            return consumer;
        }

        @Override
        protected Void doInBackground() throws Exception {
            while (keepRunning.get()) {
                String message = getConsumer().next();
                publish(message);
            }
            return null;
        }

        @Override
        protected void process(List<String> chunks) {
            for (String msg : chunks) {
                model.addElement(msg);
            }
        }

    }
}


问:
psycopg installation success, but cannot be imported in VSCode (import error)
I apologize if this has been asked before, but on the review page, I couldn't find a similar situation. I'm new to using psycopg2 and pip (as an installer in general). I attempted to install psycopg2 today (through VSCode terminal) but when I tried to import it, it said that the module didn't exist.

Error Image from VSCode

I've checked the library and it appears in there. I've made sure to try both versions (psycopg2 and psycopg2_binary). I had to update my pip to the newest version, but I've installed and reinstalled both of the psycopg2 versions with no change to the error message.

Proof of installation through VSCode terminal

I'm currently on Windows, but I'm not sure if that would make a difference.

Thanks for any help!

Edit: I was asked about the change in file between C: and Z: drive in the photos.
To remove any issue of this, I moved the .py file with psycopg2 on it into the directory and ran the queries again

Starter.py being in Python directory on C:
Starter.py being in C://Downloads

I included the downloads picture as this was where starter.py was originally, but also just incase there was issues with it being in the actual python directory folder.

答: After the latest VSCode update (Jan, 2022), the recommended python interpreter has been changed from the 64-bit version of the latest python version installed in your computer to the 64-bit version of the python pyenv installed in yoru computer. To resolve this importing problem, change the preference setting from this recommended one to the global one. Sometimes you can see it on the bottom left corner of the VSCode app when you open the file. Changing that preference allowed me to import the module correctly.</p>


问:
I have 2 lambda functions using BOTO 3. I want to combine both in one expression so the output of fun1 can be used by fun2 to generate a message
I'm a newbie at lambda and python, so i thought i'd ask here since i was able to find ton of help here in building 2 functions that needed to communicate between a commercial acct and a gov acct.

My 2 functions work as they should. I've tested them both separately. However, I'm trying to or need to combine both (currently reading about nested or helper functions) or grab the return/output of function 1(a presigned s3 url) to be used by function 2 to create a sqs message with the url to send over to the queue where another lambda will then grab and process it.

Here's my code:

Fn 1:

def s3_url_generator(bucket_name, object_name, expiration=7200):
    get_last_modified = lambda obj: int(obj['LastModified'].strftime('%s'))
    s3_client = boto3.client('s3')
    bucket_name = 'mybucket'
    object_name = s3_client.list_objects_v2(Bucket=bucket_name)['Contents']
    last_added = [obj['Key'] for obj in sorted(object_name, key=get_last_modified, reverse=True)][0]
    try:
        url = s3_client.generate_presigned_url('get_object', Params={'Bucket': bucket_name, 'Key': last_added},
                                               ExpiresIn=expiration)
    except ClientError as e:
        logging.error(e)
        return None

# The response contains the presigned URL

    return url
```
<p>Fn 2:</p>
<pre class="lang-py prettyprint-override"><code>def sqs_message_generator(queue_url, message_body):
    AWS_ACCESS_KEY_ID = ''
    AWS_SECRET_ACCESS_KEY = ''
    session = boto3.Session(aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
    sqs_config = Config(region_name='us-gov-west-1', signature_version='v4')
    sqs = session.client('sqs', config=sqs_config)
    queue_url = "http://my-sqs-url"
    message_body = {"some message"}
    send_message = sqs.send_message(QueueUrl=queue_url, MessageBody=json.dumps(message_body))
    return {'statusCode': send_message["ResponseMetadata"]["HTTPStatusCode"], 'body': json.dumps(send_message)}
</code>```

Any suggestions, pointers or help will certainly be appreciated! Thank you

答:
It sounds like you are after code like this:

url = s3_url_generator(bucket_name, object_name)
if url:
    result = sqs_message_generator(url, message_body)
    # check what was returned from result
```

The first line gives the url returned from s3 the name url. This is checked to see if there was the ClientError exception. If not, the url can be used in the next function. The return value from that function is given the name result.

Body:
I'm a newbie at lambda and python, so i thought i'd ask here since i was able to find ton of help here in building 2 functions that needed to communicate between a commercial acct and a gov acct.

My 2 functions work as they should. I've tested them both separately. However, I'm trying to or need to combine both (currently reading about nested or helper functions) or grab the return/output of function 1(a presigned s3 url) to be used by function 2 to create a sqs message with the url to send over to the queue where another lambda will then grab and process it.

Here's my code:

Fn 1:

def s3_url_generator(bucket_name, object_name, expiration=7200):
    get_last_modified = lambda obj: int(obj['LastModified'].strftime('%s'))
    s3_client = boto3.client('s3')
    bucket_name = 'mybucket'
    object_name = s3_client.list_objects_v2(Bucket=bucket_name)['Contents']
    last_added = [obj['Key'] for obj in sorted(object_name, key=get_last_modified, reverse=True)][0]
    try:
        url = s3_client.generate_presigned_url('get_object', Params={'Bucket': bucket_name, 'Key': last_added},
                                               ExpiresIn=expiration)
    except ClientError as e:
        logging.error(e)
        return None

# The response contains the presigned URL

    return url

Fn 2:

def sqs_message_generator(queue_url, message_body):
    AWS_ACCESS_KEY_ID = ''
    AWS_SECRET_ACCESS_KEY = ''
    session = boto3.Session(aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
    sqs_config = Config(region_name='us-gov-west-1', signature_version='v4')
    sqs = session.client('sqs', config=sqs_config)
    queue_url = "http://my-sqs-url"
    message_body = {"some message"}
    send_message = sqs.send_message(QueueUrl=queue_url, MessageBody=json.dumps(message_body))
    return {'statusCode': send_message["ResponseMetadata"]["HTTPStatusCode"], 'body': json.dumps(send_message)}

Any suggestions, pointers or help will certainly be appreciated! Thank you

Body:
It sounds like you are after code like this:

url = s3_url_generator(bucket_name, object_name)
if url:
    result = sqs_message_generator(url, message_body)
    # check what was returned from result

The first line gives the url returned from s3 the name url. This is checked to see if there was the ClientError exception. If not, the url can be used in the next function. The return value from that function is given the name result.


问:
Status bar color changed after Xcode 13 update
Before updating to xcode 13, the status bar's background color matched the color of the navigation bar. When I updated to xcode 13, the status bar is behaving strangely. It is showing different background colors in different view controllers. Some are black, some are gray, and some are transparent. I tried overriding the status bar style but it didn't work. There has been no change in the code whatsoever since the update. I want the status bar's background color to match that of the navigation bar.

答:
You did not give code example how you are setting status bar - are you using statusBarManager? Maybe you are using some code that became deprecated?

You can try set it with extension with statusBarManager in viewDidAppear:

```<code>extension UINavigationController {

    func setStatusBar(backgroundColor: UIColor) {
        let statusBarFrame: CGRect
        if #available(iOS 13.0, *) {
            statusBarFrame = view.window?.windowScene?.statusBarManager?.statusBarFrame ?? CGRect.zero
        } else {
            statusBarFrame = UIApplication.shared.statusBarFrame
        }
        let statusBarView = UIView(frame: statusBarFrame)
        statusBarView.backgroundColor = backgroundColor
        view.addSubview(statusBarView)
    }
}
</code>```

And then in your view call it like:

```<code>self.navigationController?.setStatusBar(backgroundColor: #COLOR)
self.navigationController?.navigationBar.setNeedsLayout()
</code>```

Body:
You did not give code example how you are setting status bar - are you using statusBarManager? Maybe you are using some code that became deprecated?

You can try set it with extension with statusBarManager in viewDidAppear:

extension UINavigationController {

    func setStatusBar(backgroundColor: UIColor) {
        let statusBarFrame: CGRect
        if #available(iOS 13.0, *) {
            statusBarFrame = view.window?.windowScene?.statusBarManager?.statusBarFrame ?? CGRect.zero
        } else {
            statusBarFrame = UIApplication.shared.statusBarFrame
        }
        let statusBarView = UIView(frame: statusBarFrame)
        statusBarView.backgroundColor = backgroundColor
        view.addSubview(statusBarView)
    }
}

And then in your view call it like:

self.navigationController?.setStatusBar(backgroundColor: #COLOR)
self.navigationController?.navigationBar.setNeedsLayout()


问:
How do I 'better' my paths to lsp server binaries whilst using nvim-lsp-install?
At the moment, every time I install a new LPS server using nvim-lsp-installer, I add an entry to my .zshenv, so that the bin folder of the server is available to $PATH:

```<code>PATH="$HOME/.local/share/nvim/lsp_servers/python/node_modules/.bin:$PATH"
</code>```

The nvim-lsp-installer documentation recommends setting up the path with the cmd option in each individual LSP configuration. The thing is that I have never seen that in any of my favorite dotfiles from my favorite fellow neovimers that use lsp-config.
Am I missing something? Is there a way to automate the process? Is there a way to add the bin folders to $PATH during server installation? Or am I doing it the "normal" way?

答:
You shouldn't need to modify your PATH manually when using nvim-lsp-installer. The minimal setup recommends the following (there's more in the README):

```<code>local lsp_installer = require("nvim-lsp-installer")

lsp_installer.on_server_ready(function (server)
   server:setup {}
end)
</code>```

By setting up the server via the above interface, nvim-lsp-installer will be able to modify the settings with the necessary properties before passing it onwards to lspconfig.

If you'd like to be able to run the language server executables from a shell, you'd probably be better off installing them manually into a location on your PATH rather than going through nvim-lsp-installer.

Body:
At the moment, every time I install a new LPS server using nvim-lsp-installer, I add an entry to my .zshenv, so that the bin folder of the server is available to $PATH:

PATH="$HOME/.local/share/nvim/lsp_servers/python/node_modules/.bin:$PATH"

The nvim-lsp-installer documentation recommends setting up the path with the cmd option in each individual LSP configuration. The thing is that I have never seen that in any of my favorite dotfiles from my favorite fellow neovimers that use lsp-config.
Am I missing something? Is there a way to automate the process? Is there a way to add the bin folders to $PATH during server installation? Or am I doing it the "normal" way?

Body:
You shouldn't need to modify your PATH manually when using nvim-lsp-installer. The minimal setup recommends the following (there's more in the README):

local lsp_installer = require("nvim-lsp-installer")

lsp_installer.on_server_ready(function (server)
   server:setup {}
end)

By setting up the server via the above interface, nvim-lsp-installer will be able to modify the settings with the necessary properties before passing it onwards to lspconfig.

If you'd like to be able to run the language server executables from a shell, you'd probably be better off installing them manually into a location on your PATH rather than going through nvim-lsp-installer.


问:
Flutter- User Complete profile after google sign in
I am new to flutter, I have a "complete profile" screen after the user signs up with google auth, but I want it to show to the user only once and don't show the screen again if the user has provided details already</p>

答:
I assume you will save the information that you gathered in the complete profile screen in a firestore document?
In that case, you will just have to check if there is a document in a 'user' collection with the UID that firestore auth provides, if so then display your normal hopme screen of your app, else display the complete profile screen. You can do this easily with a futurebuilder.</p>


问:
What is "valency", with regards to machine learning?
This term came up a few times in the Tensorflow Dev Summit, and it shows up in the Tensorflow Extended documentation, but without any sort of definition. After a fair amount of googling, I don't see reference to it in any Statistics-related setting. Searching the Tensorflow repositories produces a few hits, but they're similarly unhelpful. The term does seem to be used in Chemistry, Psychology, and Linguistics, but those definitions appear to be unrelated.</p>

答:
As discussed in this blog,

Valency indicates the number of values required per training example.
In the case of categorical features, single indicates that each
training example must have exactly one category for the feature.

More broadly speaking, it applies to features with multiple values (IMHO not that common for features in Machine Learning), e.g., lists and arrays. In that case, valency refers to the minimum or maximum number of values in these data types. For lists, one can compute the valency by applying np.min()/np.max() on the list lengths from all available feature examples.

After experimenting with both numerical and categorical features, it turns out that there only appears values (e.g., "single") in the "Valency" column when the value in the corresponding "Presence" column is "optional" (tfdv 1.6.0).


问:
Tekton pipeline input: source code from local as tar file
Due to restriction on access for corporate git repository, I want to provide the source code as input (tar or zip file) to tekton. Can anyone guide me on how to achieve it.</p>

答:
The details are going to depend on how you are providing the tar/zip to your pipeline.

But the gist is to remember that Pipeline tasks are really just containers. (Except with a bit of magic around things like arguments, sequencing, UI etc.) So asking "how do I provide source code" is essentially the same question as "how would I do this if I were doing this in a script inside a container".

If you already have the tar/zip in a PVC, then you can just mount two workspaces (one with your input tar/zip, and one where you are outputting your source files) and execute the tar (or zip) command from the one mount point to the other. (Just make sure to use a base image that has tar in it.)

If you don't already have the tar/zip, you might need to use scp or something like that first, but all of the principles look the same. Take a look at the YAML for the out of the box Tasks and you will see that they are actually quite simple under the covers.


问:
Maximum number of codepoints in a grapheme cluster
I am using the C++ ICU library. I wish to split a utf-8 string into approximately equal chunks. However, I want the chunks to be demarcated at grapheme cluster boundaries. I do not wish to convert my entire string into utf-16 to do this for both memory and speed efficiency. Instead, I want to translate a small number of utf-8 codepoints close to my estimated chunk boundaries into utf-16. I can then use ICU's BreakIterator to work out the exact boundaries.

Is there a hard upper limit of the number of codepoints that can make up a grapheme cluster? If so, what is it? I need to know this in order to determine the minimum codepoints that I need to translate from utf-8 to utf-16.

答:
Is there a hard upper limit of the number of codepoints that can make up a grapheme cluster?

No. There is no hard upper limit for how many code points a grapheme clusters - i.e. a user-perceived character - consists of.

You could for example repeatedly add ZERO WIDTH JOINER with a joined character.


问:
Split comma separated values based on another table
I would like to split comma separated values based on another table

I cannot normalize it since original table has over 8 million rows. It crushed my laptop when I tried it.

How can I put data into relevant columns and create a new column if data is not found.

For example:

TableA,

```<code>Type1        Type2
---------------------
 A            F
 B            G
 C            H
 D            I
 E           NULL
</code>```

TableB

```<code>ID     Country     AllTypes
---------------------------------
1       Italy      A, B, C
2       USA        D, E, A, F
4       Japan      I, O, Z
5       UK         NULL
</code>```

By using these two tables, I would like to get the output such as

```<code>ID     Country     AllTypes          Type1        Type2    UnCaptured
----------------------------------------------------------------------
1       Italy      A, B, C           A, B, C       NULL     NULL
2       USA        D, E, G, F        D, E          G, F     NULL
4       Japan      I, O, Z           NULL          I        O, Z
5       UK         NULL              NULL          NULL     NULL
</code>```

This is I have done so far

```<code>with TableA as (
  select 'A' as Type1, 'F' as Type2 union all
  select 'B', 'G' union all
  select 'C', 'H' union all
  select 'D', 'I' union all
  select 'E', NULL
),
TableB as (
  select 1 as ID, 'Italy' as Country, 'A, B, C' as Alltypes union all
  select 2, 'USA', 'D, E, A, F' union all
  select 4, 'Japan', 'I', 'O', 'Z' union all
  select 5, 'UK', NULL
)

select b.Id, b.Country, b.Alltypes,
    String_Agg(v.type1,',') Type1,
    String_Agg(v.type2,',') Type2
    **String_Agg(v.Type3,',') Uncaptured*** ------- This query

from tableb b
outer apply (
    select Trim(value) t,
        case when exists
          (select * from tablea a where a.type1=Trim(value))
        then Trim(value) end type1,
        case when exists
          (select * from tablea a where a.type2=Trim(value))
        then Trim(value) end Type2,
        Case when not exists                                  ------------This query
          ( (select * from tablea a where a.type1=Trim(value)) -------
             and                                               ------
             (select * from tablea a where a.type2=Trim(value))------
          ) then Trim(value) end Type3**                        -------------
    from String_Split(alltypes, ',')
)v
group by Id, Country, AllTypes
</code>```

Without highlighted queries(-----) which are for creating a new column (Uncaptured), it works ok like below.

```<code>Id  Country Alltypes    Type1   Type2
1   Italy   A, B, C     A,B,C   NULL
2   USA     D, E, A, F  D,E,A   F
4   Japan   I, O, Z     I       NULL
5   UK      NULL        NULL    NULL
</code>```

But if I add those highlighted queries, it shows error. I was also thinking of else but did not work as well.

Could someone help me please?

答:
How about</p>
```<code>outer apply (
    select Trim(value) t, a1.type1, a2.type2,
        CASE WHEN COALESCE(a1.type1, a2.type2) IS NULL THEN Trim(s.value) END unCaptured
    from String_Split(alltypes, ',') s
    left join tablea a1 where a1.type1=Trim(s.value)
    left join tablea a2 where a2.type2=Trim(s.value)
)v

</code>```

Body:
I would like to split comma separated values based on another table

I cannot normalize it since original table has over 8 million rows. It crushed my laptop when I tried it.

How can I put data into relevant columns and create a new column if data is not found.

For example:

TableA,

Type1        Type2
---------------------
 A            F
 B            G
 C            H
 D            I
 E           NULL

TableB

ID     Country     AllTypes
---------------------------------
1       Italy      A, B, C
2       USA        D, E, A, F
4       Japan      I, O, Z
5       UK         NULL

By using these two tables, I would like to get the output such as

ID     Country     AllTypes          Type1        Type2    UnCaptured
----------------------------------------------------------------------
1       Italy      A, B, C           A, B, C       NULL     NULL
2       USA        D, E, G, F        D, E          G, F     NULL
4       Japan      I, O, Z           NULL          I        O, Z
5       UK         NULL              NULL          NULL     NULL

This is I have done so far

with TableA as (
  select 'A' as Type1, 'F' as Type2 union all
  select 'B', 'G' union all
  select 'C', 'H' union all
  select 'D', 'I' union all
  select 'E', NULL
),
TableB as (
  select 1 as ID, 'Italy' as Country, 'A, B, C' as Alltypes union all
  select 2, 'USA', 'D, E, A, F' union all
  select 4, 'Japan', 'I', 'O', 'Z' union all
  select 5, 'UK', NULL
)

select b.Id, b.Country, b.Alltypes,
    String_Agg(v.type1,',') Type1,
    String_Agg(v.type2,',') Type2
    **String_Agg(v.Type3,',') Uncaptured*** ------- This query

from tableb b
outer apply (
    select Trim(value) t,
        case when exists
          (select * from tablea a where a.type1=Trim(value))
        then Trim(value) end type1,
        case when exists
          (select * from tablea a where a.type2=Trim(value))
        then Trim(value) end Type2,
        Case when not exists                                  ------------This query
          ( (select * from tablea a where a.type1=Trim(value)) -------
             and                                               ------
             (select * from tablea a where a.type2=Trim(value))------
          ) then Trim(value) end Type3**                        -------------
    from String_Split(alltypes, ',')
)v
group by Id, Country, AllTypes

Without highlighted queries(-----) which are for creating a new column (Uncaptured), it works ok like below.

Id  Country Alltypes    Type1   Type2
1   Italy   A, B, C     A,B,C   NULL
2   USA     D, E, A, F  D,E,A   F
4   Japan   I, O, Z     I       NULL
5   UK      NULL        NULL    NULL

But if I add those highlighted queries, it shows error. I was also thinking of else but did not work as well.

Could someone help me please?

Body:
How about

outer apply (
    select Trim(value) t, a1.type1, a2.type2,
        CASE WHEN COALESCE(a1.type1, a2.type2) IS NULL THEN Trim(s.value) END unCaptured
    from String_Split(alltypes, ',') s
    left join tablea a1 where a1.type1=Trim(s.value)
    left join tablea a2 where a2.type2=Trim(s.value)
)v


问:
Hide "foreach" results if there is only one result
I have post type with an "email" custom field.
When editing a post, I would like to know if other posts have the same email value.

So, I created the following function :

```<code>function samemailaddress($field){

$emailcurrentpost = get_field('email');
$referencecurrentpost = get_field('reference');

    echo '<table>';

global $post;
$tmp_post = $post;
$args = array(
        'post_type' => 'reservation',
        'posts_per_page' => '-1',);
$myposts = get_posts( $args );

    foreach( $myposts as $post ) : setup_postdata($post);

            $reference = get_field('reference');
            $email = get_field('email');

        if($email === $emailcurrentpost) {
            ?>
    <tr>
  <td><?php echo $reference; ?></td>
  </tr>

<?php   }

endforeach;
$post = $tmp_post;

echo '</table>';

 }
</code>```

If no other post has the same value, it will only display the current post. If the current post is the only result, then I'd like to hide the whole table.

Of course I could create a condition to hide the current post no matter the number of results, but i'd rather keep it (it allows me to compare the current post with other results)

答:
Why not prevent your existing post from coming back in the $myposts query...</p>
```<code>$args = array(
  'post_type' => 'reservation',
  'posts_per_page' => '-1',
  'exclude' => [$tmp_post->ID]
);
</code>```

Body:
I have post type with an "email" custom field.
When editing a post, I would like to know if other posts have the same email value.

So, I created the following function :

function samemailaddress($field){

$emailcurrentpost = get_field('email');
$referencecurrentpost = get_field('reference');

    echo '
';

global $post;
$tmp_post = $post;
$args = array(
        'post_type' => 'reservation',
        'posts_per_page' => '-1',);
$myposts = get_posts( $args );

    foreach( $myposts as $post ) : setup_postdata($post);

            $reference = get_field('reference');
            $email = get_field('email');

        if($email === $emailcurrentpost) {
            ?>

  <?php echo $reference; ?>

<?php   }

endforeach;
$post = $tmp_post;

echo '
';

 }

If no other post has the same value, it will only display the current post. If the current post is the only result, then I'd like to hide the whole table.

Of course I could create a condition to hide the current post no matter the number of results, but i'd rather keep it (it allows me to compare the current post with other results)

Body:
Why not prevent your existing post from coming back in the $myposts query...

$args = array(
  'post_type' => 'reservation',
  'posts_per_page' => '-1',
  'exclude' => [$tmp_post->ID]
);