问:
deploy web site on IIS 7 with and without www prefix
I want to deploy website on IIS 7 with www and also without www prefix. Do I need to create twoo web sites in IIS. e.g. www.something.com and something.com or is there another option how can I do it only with one web site in IIS.

thanks

答:
The www prefix is just a DNS record, typically used as either an A record, or a CNAME record. The A record will cause DNS lookups to use the directly specified IP address. A CNAME (canonical name) will cause the DNS query to start over, using the value specified as the canonical name.

E.g.:

```<code>www.something.com A 65.42.3.152
</code>```

... will resolve DNS queries directly to the IP address.

```<code>www.something.com CNAME something.com
something.com A 65.42.3.152
</code>```

... will cause the DNS query to start again with something.com as the argument.

You will need to add both as bindings for your website, as IIS will try and resolve the host header value to match a site.

Obviously, if you add both www and the non-www version you do risk duplicate content when the site is being crawled. You can resolve this a variety of ways, you can either redirect to one or the other (e.g., redirect www.something.com to something.com) using URL rewriting (and a 301 response code), or you can specify a canonical tag:

```<code><link rel="canonical" href="http://something.com" />
</code>```

... etc. The downside to having the non-www as the website's main address is that any cookies will be for something.com domain, which means if you intend do any other subdomains (e.g. CDNs, perhaps static.something.com) you'll be transmitting cookies for all requests to anything.something.com as well.

Body:
The www prefix is just a DNS record, typically used as either an A record, or a CNAME record. The A record will cause DNS lookups to use the directly specified IP address. A CNAME (canonical name) will cause the DNS query to start over, using the value specified as the canonical name.

E.g.:

www.something.com A 65.42.3.152

... will resolve DNS queries directly to the IP address.

www.something.com CNAME something.com
something.com A 65.42.3.152

... will cause the DNS query to start again with something.com as the argument.

You will need to add both as bindings for your website, as IIS will try and resolve the host header value to match a site.

Obviously, if you add both www and the non-www version you do risk duplicate content when the site is being crawled. You can resolve this a variety of ways, you can either redirect to one or the other (e.g., redirect www.something.com to something.com) using URL rewriting (and a 301 response code), or you can specify a canonical tag:

<link rel="canonical" href="http://something.com" />

... etc. The downside to having the non-www as the website's main address is that any cookies will be for something.com domain, which means if you intend do any other subdomains (e.g. CDNs, perhaps static.something.com) you'll be transmitting cookies for all requests to anything.something.com as well.


来源: stackexchange

问:
How to store a printed value to variable and a new printed value to another variable to use them to compare and find the largest PYTHON
#So basically the following code pulls livestock data from an import called finnhub, and basically, it pulls live values connected to a JSON file using an API. [ The API has no problem the with the code, the first part is pretty much an example of the following or next code which i built] The problem is on the second part, if i could print out a value and instead of it going to to the terminal it gets stored in a variable]

```<code>import finnhub
import os
import sys
import time
finnhub_client = finnhub.Client(api_key="c82bn52ad3icth8l2dtg")
ticker = input("Type in your stock ticker here: ")
print("|c| means Current Price|,\n |d| means diffrence/change of price|,\n |dp| means Percent Change|,\n |h| highest price of the day(All time high)|,\n |l| means lowest price of the day|,\n |o| means open price of the day|, \n |pc| means Previous Close price|.")
price = finnhub_client.quote(ticker)
print(price["h"])
</code>```

#The h is the highest peak of price the following stock which you chose, has reached in the day,
#so i was trying to look for a way to store the printed output from print(price["h"]) to a variable without it printing to the terminal, then later on after a given amount of seconds a new code prints the same  (price["h"]) to a new variable, then in comparison there would be an old variable and new variable  both consisting  of different values, so if the old variable > than the new variable, it was supposed to print the new variable value.

#So something like this but it didn't work.

```<code>from hashlib import new
import finnhub
import os
import sys
import time
finnhub_client = finnhub.Client(api_key="c82bn52ad3icth8l2dtg")
ticker = input("Type in your stock ticker here: ")
Tkekr = ticker

def Stockalert(Tkekr):
    print("|c| means Current Price|,\n |d| means diffrence/change of price|,\n |dp| means Percent Change|,\n |h| highest price of the day(All time high)|,\n |l| means lowest price of the day|,\n |o| means open price of the day|, \n |pc| means Previous Close price|.")
    price = finnhub_client.quote(ticker)
#I'm trying to store the output of the first given high peak, then use it to compare it with another value printed after 30sec of another high peak,
#and if it is higher it will, autmoatically send a notification saying it has crossed it's highest peak
   # print(price["h"])
    old_stdout = print(price["h"])
    time.sleep(60)
    new_stdout = print(price["h"])

    if old_stdout < new_stdout:

        print(sys.stdout)

print(Stockalert(Tkekr))
</code>```

#The initial aim was for the code to print out h and store the value in a variable then after 60 seconds or the given time, it prints out another value in a new variable, then the if command/loop comes in and compares the old variable and the new variable, so if the new variable > old variable it would return the new variable to me, with the value it has stored. So if the new value within the variable is higher than the old value it would print  a message saying the highest peak of the day is now "with the new value inserted here".
So far this is what i have written and gotten.

答:
Looks like you'll just need to break it onto two lines of code, like this:

```<code>old_stdout = float(price["h"])
print(old_stdout)
time.sleep(60)
new_stdout = float(price["h"])
print(new_stdout)
</code>```

This should ensure that you store string versions of each output in the nominated variables. Now, I'm not familiar with the finnhub API, and I am assuming that the type-casting will be enough to make a copy that won't change when the underlying price["h"] variable changes. If you find this doesn't work and the number changes to continue to match the variable's current state, you may need to add a .copy() method after the float type-cast to decouple your stored values from the underlying variable.

EDIT: Initially missed the less-than comparison. Changed the suggested type-cast from string to float, though this may then require other formatting for the print lines.

ContentLicense: CC BY-SA 4.0

Body:
#So basically the following code pulls livestock data from an import called finnhub, and basically, it pulls live values connected to a JSON file using an API. [ The API has no problem the with the code, the first part is pretty much an example of the following or next code which i built] The problem is on the second part, if i could print out a value and instead of it going to to the terminal it gets stored in a variable]

import finnhub
import os
import sys
import time
finnhub_client = finnhub.Client(api_key="c82bn52ad3icth8l2dtg")
ticker = input("Type in your stock ticker here: ")
print("|c| means Current Price|,\n |d| means diffrence/change of price|,\n |dp| means Percent Change|,\n |h| highest price of the day(All time high)|,\n |l| means lowest price of the day|,\n |o| means open price of the day|, \n |pc| means Previous Close price|.")
price = finnhub_client.quote(ticker)
print(price["h"])

#The h is the highest peak of price the following stock which you chose, has reached in the day,
#so i was trying to look for a way to store the printed output from print(price["h"]) to a variable without it printing to the terminal, then later on after a given amount of seconds a new code prints the same  (price["h"]) to a new variable, then in comparison there would be an old variable and new variable  both consisting  of different values, so if the old variable > than the new variable, it was supposed to print the new variable value.

#So something like this but it didn't work.

from hashlib import new
import finnhub
import os
import sys
import time
finnhub_client = finnhub.Client(api_key="c82bn52ad3icth8l2dtg")
ticker = input("Type in your stock ticker here: ")
Tkekr = ticker

def Stockalert(Tkekr):
    print("|c| means Current Price|,\n |d| means diffrence/change of price|,\n |dp| means Percent Change|,\n |h| highest price of the day(All time high)|,\n |l| means lowest price of the day|,\n |o| means open price of the day|, \n |pc| means Previous Close price|.")
    price = finnhub_client.quote(ticker)
#I'm trying to store the output of the first given high peak, then use it to compare it with another value printed after 30sec of another high peak,
#and if it is higher it will, autmoatically send a notification saying it has crossed it's highest peak
   # print(price["h"])
    old_stdout = print(price["h"])
    time.sleep(60)
    new_stdout = print(price["h"])

    if old_stdout < new_stdout:

        print(sys.stdout)

print(Stockalert(Tkekr))

#The initial aim was for the code to print out h and store the value in a variable then after 60 seconds or the given time, it prints out another value in a new variable, then the if command/loop comes in and compares the old variable and the new variable, so if the new variable > old variable it would return the new variable to me, with the value it has stored. So if the new value within the variable is higher than the old value it would print  a message saying the highest peak of the day is now "with the new value inserted here".
So far this is what i have written and gotten.

Body:
Looks like you'll just need to break it onto two lines of code, like this:

old_stdout = float(price["h"])
print(old_stdout)
time.sleep(60)
new_stdout = float(price["h"])
print(new_stdout)

This should ensure that you store string versions of each output in the nominated variables. Now, I'm not familiar with the finnhub API, and I am assuming that the type-casting will be enough to make a copy that won't change when the underlying price["h"] variable changes. If you find this doesn't work and the number changes to continue to match the variable's current state, you may need to add a .copy() method after the float type-cast to decouple your stored values from the underlying variable.

EDIT: Initially missed the less-than comparison. Changed the suggested type-cast from string to float, though this may then require other formatting for the print lines.


问:
Python script to run Django commands
I want to run a python scripts which should do:

Create a django project: django-admin startproject foobar

Create a app in the project: python manage.py barfoo

Add an entry of newly created app barfoo in the setting's INSTALLED_APP.

How can I achieve this?

答:
There seems to be a pythonic way to do #1 and #2

https://docs.djangoproject.com/en/dev/ref/django-admin/#running-management-commands-from-your-code

```<code>from django.core import management
management.call_command('flush', verbosity=0, interactive=False)
management.call_command('loaddata', 'test_data', verbosity=0)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python script to run Django commands

Body:
There seems to be a pythonic way to do #1 and #2

https://docs.djangoproject.com/en/dev/ref/django-admin/#running-management-commands-from-your-code

from django.core import management
management.call_command('flush', verbosity=0, interactive=False)
management.call_command('loaddata', 'test_data', verbosity=0)


问:
Schema registry failed because _schema replication factor
I want to share here a study case about the schema registry service that failed when registry service is part of Kafka machine

we have 7 Kafka brokers machines in our cluster , on each machine we have schema registry service

on one of the Kafka broker we found the following error

```<code>WARN The replication factor of the schema topic _schemas is less than the desired one of 3. If this is a production environment, it's crucial to add more brokers and increase the replication factor of the topic. (io.confluent.kafka.schemaregistry.storage.KafkaStore)
[2022-02-10 15:09:59,958] ERROR Server died unexpectedly:  (io.confluent.kafka.schemaregistry.rest.SchemaRegistryMain)
java.lang.IllegalArgumentException: Unable to subscribe to the Kafka topic _schemas backing this data store. Topic may not exist.
</code>```

so from log above seems that schema failed because replication factor isn't 3 as expected?

so we run the Kafka described and we get the following:

```<code>kafka-topics -zookeeper kafka01:2181 --describe --topic _schemas

Topic:_schemas  PartitionCount:1    ReplicationFactor:1 Configs:cleanup.policy=compact
    Topic: _schemas Partition: 0    Leader: 3   Replicas: 3 Isr: 3
</code>```

from above we indeed see that topic- _schema is with replication factor 1

based on that details we are thinking to perform the following steps:

STEP 1

in order to increase the replication factor we need to create the following json file:

example of json template:

```<code>{"version":1,
  "partitions":[
     {"topic":"signals","partition":0,"replicas":[0,1,2]},
     {"topic":"signals","partition":1,"replicas":[0,1,2]},
     {"topic":"signals","partition":2,"replicas":[0,1,2]}
]}
</code>```

but in our case and regarding to our _schema topic json should be like this:

```<code>more increase-replication-factor.json

{
 "version":1,
 "partitions":[
{"topic":"_schemas","partition":0,"replicas":[2,3,1]}
 ]
}
</code>```

STEP 2

Then we should run the following:

```<code>kafka-reassign-partitions --zookeeper kafka01:2181 --reassignment-json-file increase-replication-factor.json  --execute
</code>```

I will appreciate to get your opinion about STEP1,STEP2 , in order to solve the problem about schema registry service

References - How to change the number of replicas of a Kafka topic?

答:
If you already have schemas in that topic, then sure, those steps will work. (Note: --zookeeper flag is replaced by --bootstrap-server in latest versions of Kafka (v3.0+) )

Otherwise, on a fresh installation, you could simply delete the topic, and edit the schema-registry.properties to set kafkastore.topic.replication.factor=3 (which is the default, by the way), then restart the registry so the topic gets recreated.

Also, you really don't need more than 2 or 3 Registry servers, at most.

Body:
I want to share here a study case about the schema registry service that failed when registry service is part of Kafka machine

we have 7 Kafka brokers machines in our cluster , on each machine we have schema registry service

on one of the Kafka broker we found the following error

WARN The replication factor of the schema topic _schemas is less than the desired one of 3. If this is a production environment, it's crucial to add more brokers and increase the replication factor of the topic. (io.confluent.kafka.schemaregistry.storage.KafkaStore)
[2022-02-10 15:09:59,958] ERROR Server died unexpectedly:  (io.confluent.kafka.schemaregistry.rest.SchemaRegistryMain)
java.lang.IllegalArgumentException: Unable to subscribe to the Kafka topic _schemas backing this data store. Topic may not exist.

so from log above seems that schema failed because replication factor isn't 3 as expected?

so we run the Kafka described and we get the following:

kafka-topics -zookeeper kafka01:2181 --describe --topic _schemas

Topic:_schemas  PartitionCount:1    ReplicationFactor:1 Configs:cleanup.policy=compact
    Topic: _schemas Partition: 0    Leader: 3   Replicas: 3 Isr: 3

from above we indeed see that topic- _schema is with replication factor 1

based on that details we are thinking to perform the following steps:

STEP 1

in order to increase the replication factor we need to create the following json file:

example of json template:

{"version":1,
  "partitions":[
     {"topic":"signals","partition":0,"replicas":[0,1,2]},
     {"topic":"signals","partition":1,"replicas":[0,1,2]},
     {"topic":"signals","partition":2,"replicas":[0,1,2]}
]}

but in our case and regarding to our _schema topic json should be like this:

more increase-replication-factor.json

{
 "version":1,
 "partitions":[
{"topic":"_schemas","partition":0,"replicas":[2,3,1]}
 ]
}

STEP 2

Then we should run the following:

kafka-reassign-partitions --zookeeper kafka01:2181 --reassignment-json-file increase-replication-factor.json  --execute

I will appreciate to get your opinion about STEP1,STEP2 , in order to solve the problem about schema registry service

References - How to change the number of replicas of a Kafka topic?


问:
AWS CLI JMESPath Query help using query option in cli
I have the following cli command

aws ecs list-services --cluster ecs-cluster-1
```
<p>Giving this JSON</p>
<pre class="lang-json prettyprint-override"><code>{
    "serviceArns": [
        "arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app4",
        "arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app3",
        "arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app1",
        "arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app4"
    ]
}
</code>```

How do I get app1 ARN back by matching name of the app (app1) using --query option?

Expected Output

```<code>arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app1
</code>```

Please note that this JSON array is not ordered.

答:
You can either use contains or ends_with for the filtering part.

Then you want to stop the project and get the first item of the array in order to have only the application ARN you are interested in.

Stopping a projection is covered in the pipe expression tutorial of the documentation.

So, given the expression

serviceArns[?ends_with(@,'app1')]|[0]
```
<p>You end up with the expected</p>
<pre class="lang-json prettyprint-override"><code>"arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app1"
</code>```

In the AWS command line interface, this will then be:

aws ecs list-service \
  --cluster ecs-cluster-1 \
  --query "serviceArns[?ends_with(@,'app1')]|[0]"
```

Body:
I have the following cli command

aws ecs list-services --cluster ecs-cluster-1

Giving this JSON

{
    "serviceArns": [
        "arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app4",
        "arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app3",
        "arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app1",
        "arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app4"
    ]
}

How do I get app1 ARN back by matching name of the app (app1) using --query option?

Expected Output

arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app1

Please note that this JSON array is not ordered.

Body:
You can either use contains or ends_with for the filtering part.

Then you want to stop the project and get the first item of the array in order to have only the application ARN you are interested in.

Stopping a projection is covered in the pipe expression tutorial of the documentation.

So, given the expression

serviceArns[?ends_with(@,'app1')]|[0]

You end up with the expected

"arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app1"

In the AWS command line interface, this will then be:

aws ecs list-service \
  --cluster ecs-cluster-1 \
  --query "serviceArns[?ends_with(@,'app1')]|[0]"


问:
If I change one button with CSS, the other is also changed
I'm having a problem editing buttons using css.

In particular, I notice that if I modify the "Cancel changes" button, the "Delete article parts" button present in a different div is also modified.

Can someone help me?

.button[type=submit],[type=button] {
    width: 30%;
    background-color: rgb(24, 73, 32);
    color: white;
    padding: 14px 20px;
    margin: 8px 0;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

button[type=submit]:hover {
    background-color: #45a049;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "button">
   <button type = "submit" class = "full"> Save changes </button>
   <input type = "button" value = "Cancel changes"
   onclick = "clearResult (document.getElementById ('id'). value)" />
</div>

<div class = "buttons">
   <form action = "creaFrammento.html">
       <input type = "submit" value = "Add article part" />
   </form>

   <input type = "button" value = "Delete article parts" onclick = "confirmation ()" />
</div></code>```

答: If you use.button it is an element selector which means the CSS applies to whole buttons in your HTML page. To prevent that you can use a class selector or id selector. but when we using javaScript we need this id selector so the recommended thing is to use a class selector.</p>

Body:
I'm having a problem editing buttons using css.

In particular, I notice that if I modify the "Cancel changes" button, the "Delete article parts" button present in a different div is also modified.

Can someone help me?

.button[type=submit],[type=button] {
    width: 30%;
    background-color: rgb(24, 73, 32);
    color: white;
    padding: 14px 20px;
    margin: 8px 0;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

button[type=submit]:hover {
    background-color: #45a049;
}

   <button type = "submit" class = "full"> Save changes </button>
   <input type = "button" value = "Cancel changes"
   onclick = "clearResult (document.getElementById ('id'). value)" />

   <form action = "creaFrammento.html">
       <input type = "submit" value = "Add article part" />
   </form>

   <input type = "button" value = "Delete article parts" onclick = "confirmation ()" />


问:
Display Prisma model using model name
I need to create a function that shows a Prisma model using the name of the model as a parameter. Every time the model name can change and TypeScript should automatically check if that Prisma model exists.

/*
file schema.prisma models:

model User {
  id          Int      @id @default(autoincrement())
  name        String
  password    String
  job         String   @default("")
  location    String   @default("")
  phone       String   @default("")
  email       String
}

model Participant {
  id         Int       @id @default(autoincrement())
  userID     Int
  groupID    Int
}

*/

import { PrismaClient } from "@prisma/client";

function loadModel(modelName: /* string */) {
  const prisma = new PrismaClient();
  const Model = prisma[modelName]
}

loadModel("user")```

Following code will return a error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'PrismaClient<PrismaClientOptions, never, RejectOnNotFound | RejectPerOperation | undefined>'. No index signature with a parameter of type 'string' was found on type 'PrismaClient<PrismaClientOptions, never, RejectOnNotFound | RejectPerOperation | undefined>'.

After that error I tried to add to modelName parameter : keyof PrismaClient it worked, but when I tried adding something like Model.create({...}) - it returned following error: Property 'create' does not exist on type '(<V extends "beforeExit">(eventType: V, callback: (event: V extends "query" ? QueryEvent : V extends "beforeExit" ? () => Promise<void> : LogEvent) => void) => void) | ... 11 more ... | MessageDelegate<...>'. Property 'create' does not exist on type '<V extends "beforeExit">(eventType: V, callback: (event: V extends "query" ? QueryEvent : V extends "beforeExit" ? () => Promise<void> : LogEvent) => void) => void'.

How could I fix this problem?

答:
There is an open feature request for this to be natively supported in Prisma, if you want to add to it:
https://github.com/prisma/prisma/issues/5273</p>

Title: Display Prisma model using model name

Body:
I need to create a function that shows a Prisma model using the name of the model as a parameter. Every time the model name can change and TypeScript should automatically check if that Prisma model exists.

/*
file schema.prisma models:

model User {
  id          Int      @id @default(autoincrement())
  name        String
  password    String
  job         String   @default("")
  location    String   @default("")
  phone       String   @default("")
  email       String
}

model Participant {
  id         Int       @id @default(autoincrement())
  userID     Int
  groupID    Int
}

*/

import { PrismaClient } from "@prisma/client";

function loadModel(modelName: /* string */) {
  const prisma = new PrismaClient();
  const Model = prisma[modelName]
}

loadModel("user")

Following code will return a error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'PrismaClient<PrismaClientOptions, never, RejectOnNotFound | RejectPerOperation | undefined>'. No index signature with a parameter of type 'string' was found on type 'PrismaClient<PrismaClientOptions, never, RejectOnNotFound | RejectPerOperation | undefined>'.

After that error I tried to add to modelName parameter : keyof PrismaClient it worked, but when I tried adding something like Model.create({...}) - it returned following error: Property 'create' does not exist on type '(<V extends "beforeExit">(eventType: V, callback: (event: V extends "query" ? QueryEvent : V extends "beforeExit" ? () => Promise<void> : LogEvent) => void) => void) | ... 11 more ... | MessageDelegate<...>'. Property 'create' does not exist on type '<V extends "beforeExit">(eventType: V, callback: (event: V extends "query" ? QueryEvent : V extends "beforeExit" ? () => Promise<void> : LogEvent) => void) => void'.

How could I fix this problem?


问:
truffle init truffle : File C:\Users\PC-Name\AppData\Roaming\npm\truffle.ps1 cannot be loaded because running scripts is disabled on this system

`PS H:\BlockChain\dev\VS Code\ethereum\web> truffle init truffle : File C:\Users\PC-NAME\AppData\Roaming\npm\truffle.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.`

答:
Run this command in windows power shell
   >> 'Set-ExecutionPol[enter image description here][1]icy RemoteSigned -Scope CurrentUser'


问:
Spigot with Guice gives NoClassDefFoundError on internal.Messages$FormatOptions
I've been playing around with Guice and stumbled upon this error that doesn't seem to make a lot of sense to me. It seems like whenever an error occurs during injection, Guice fails to properly log the injection error due to a failed message formatting. This could be a bug within Guice, I am not entirely sure.

The jar is being built using the maven-shade-plugin, which includes the necessary dependencies in the jar itself. Looking at the jar's contents, it definitely does contain the class that the NoClassDefFoundError is referring to. The injection itself works completely fine, as long as it does not run into any classes it cannot inject properly.

What makes this stranger is the fact that the code where the exception occurs is in the exact same file as the class that is missing. The following screenshot is taken using IntelliJ's built-in decompiler:

Contents of jar at com.google.inject.internal through winrar:

Stacktrace:

```<code>[23:32:10 WARN]: AsyncLogger error handling event seq=231, value='org.apache.logging.log4j.core.async.RingBufferLogEvent@64c2c9e5': java.lang.NoClassDefFoundError: java.lang.NoClassDefFoundError: com/google/inject/internal/Messages$FormatOptions
[23:32:10 WARN]:        at Dodgeball.jar//com.google.inject.internal.Messages.redBold(Messages.java:306)
[23:32:10 WARN]:        at Dodgeball.jar//com.google.inject.spi.ErrorDetail.lambda$format$0(ErrorDetail.java:61)
[23:32:10 WARN]:        at java.base/java.util.Optional.map(Optional.java:260)
[23:32:10 WARN]:        at Dodgeball.jar//com.google.inject.spi.ErrorDetail.format(ErrorDetail.java:61)
[23:32:10 WARN]:        at Dodgeball.jar//com.google.inject.internal.Messages.formatMessages(Messages.java:90)
[23:32:10 WARN]:        at Dodgeball.jar//com.google.inject.ProvisionException.getMessage(ProvisionException.java:60)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.impl.ThrowableProxy.<init>(ThrowableProxy.java:106)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.impl.ThrowableProxy.<init>(ThrowableProxy.java:94)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.async.RingBufferLogEvent.getThrownProxy(RingBufferLogEvent.java:326)
[23:32:10 WARN]:        at io.papermc.paper.logging.DelegateLogEvent.getThrownProxy(DelegateLogEvent.java:103)
[23:32:10 WARN]:        at io.papermc.paper.logging.ExtraClassInfoLogEvent.getThrownProxy(ExtraClassInfoLogEvent.java:21)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.pattern.ExtendedThrowablePatternConverter.format(ExtendedThrowablePatternConverter.java:63)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.pattern.PatternFormatter.format(PatternFormatter.java:38)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.layout.PatternLayout$PatternSelectorSerializer.toSerializable(PatternLayout.java:475)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.layout.PatternLayout.toText(PatternLayout.java:244)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.layout.PatternLayout.encode(PatternLayout.java:229)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.layout.PatternLayout.encode(PatternLayout.java:59)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender.directEncodeEvent(AbstractOutputStreamAppender.java:197)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender.tryAppend(AbstractOutputStreamAppender.java:190)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender.append(AbstractOutputStreamAppender.java:181)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.appender.RollingRandomAccessFileAppender.append(RollingRandomAccessFileAppender.java:251)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.tryCallAppender(AppenderControl.java:156)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.callAppender0(AppenderControl.java:129)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.callAppenderPreventRecursion(AppenderControl.java:120)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.callAppender(AppenderControl.java:84)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.appender.rewrite.RewriteAppender.append(RewriteAppender.java:84)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.tryCallAppender(AppenderControl.java:156)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.callAppender0(AppenderControl.java:129)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.callAppenderPreventRecursion(AppenderControl.java:120)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.callAppender(AppenderControl.java:84)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.appender.rewrite.RewriteAppender.append(RewriteAppender.java:84)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.tryCallAppender(AppenderControl.java:156)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.callAppender0(AppenderControl.java:129)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.callAppenderPreventRecursion(AppenderControl.java:120)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.callAppender(AppenderControl.java:84)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.LoggerConfig.callAppenders(LoggerConfig.java:540)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.LoggerConfig.processLogEvent(LoggerConfig.java:498)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:481)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:469)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AwaitCompletionReliabilityStrategy.log(AwaitCompletionReliabilityStrategy.java:98)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.async.AsyncLogger.actualAsyncLog(AsyncLogger.java:488)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.async.RingBufferLogEvent.execute(RingBufferLogEvent.java:154)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.async.RingBufferLogEventHandler.onEvent(RingBufferLogEventHandler.java:46)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.async.RingBufferLogEventHandler.onEvent(RingBufferLogEventHandler.java:29)
[23:32:10 WARN]:        at com.lmax.disruptor.BatchEventProcessor.processEvents(BatchEventProcessor.java:168)
[23:32:10 WARN]:        at com.lmax.disruptor.BatchEventProcessor.run(BatchEventProcessor.java:125)
[23:32:10 WARN]:        at java.base/java.lang.Thread.run(Thread.java:831)
</code>```

Main Pom.xml (note that Valve is what contains guice):

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mpolder</groupId>
    <artifactId>Dodgeball</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>16</maven.compiler.source>
        <maven.compiler.target>16</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.3.0-SNAPSHOT</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <finalName>Cameo-Dodgeball</finalName>
                            <relocations>
                                <relocation>
                                    <pattern>com.mpolder.valve</pattern>
                                    <shadedPattern>com.mpolder.dodgeball.valve</shadedPattern>
                                </relocation>
                            </relocations>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <pluginRepositories>
        <pluginRepository>
            <id>maven-snapshots</id>
            <url>https://repository.apache.org/content/repositories/snapshots/</url>
        </pluginRepository>
    </pluginRepositories>

    <repositories>
        <repository>
            <id>spigot-repo</id>
            <url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
        </repository>
        <repository>
            <id>sk89q-repo</id>
            <url>https://maven.enginehub.org/repo/</url>
        </repository>
    </repositories>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.jetbrains/annotations -->
        <dependency>
            <groupId>org.jetbrains</groupId>
            <artifactId>annotations</artifactId>
            <version>22.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
        <dependency>
            <groupId>org.spigotmc</groupId>
            <artifactId>spigot-api</artifactId>
            <version>1.16.5-R0.1-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.mpolder</groupId>
            <artifactId>Valve</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.sk89q.worldguard</groupId>
            <artifactId>worldguard-bukkit</artifactId>
            <version>7.0.7-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>
</code>```

Valve pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mpolder</groupId>
    <artifactId>Valve</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>16</maven.compiler.source>
        <maven.compiler.target>16</maven.compiler.target>
    </properties>

    <repositories>
        <repository>
            <id>spigot-repo</id>
            <url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
        </repository>
    </repositories>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.jetbrains/annotations -->
        <dependency>
            <groupId>org.jetbrains</groupId>
            <artifactId>annotations</artifactId>
            <version>22.0.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.reflections/reflections -->
        <dependency>
            <groupId>org.reflections</groupId>
            <artifactId>reflections</artifactId>
            <version>0.9.12</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.27</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.jdbi/jdbi3-core -->
        <dependency>
            <groupId>org.jdbi</groupId>
            <artifactId>jdbi3-core</artifactId>
            <version>3.23.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.jdbi/jdbi3-core -->
        <dependency>
            <groupId>org.jdbi</groupId>
            <artifactId>jdbi3-sqlobject</artifactId>
            <version>3.23.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
            <version>5.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.spigotmc</groupId>
            <artifactId>spigot-api</artifactId>
            <version>1.16.5-R0.1-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>
</code>```

答:
So, this will probably not be the solution anyone was hoping for (including me)

As it turns out, the library I was using called spigot (an extension on bukkit), has its own implementation of a classloader. This classloader just does not seem to function properly whatsoever, and fails to load the subclass even though the class is in the classpath.

The only way I could think of, once finding the cause of the problem, was to manually load in the class using Google Guava. This has fixed the issue, although in a very dirty way. It only needs to run once though, so I have stowed it away deep inside a method which name calls bukkit out on this bug.

If you'd like to know how I fixed it, prepare for a wild ride:

```<code>    List<String> toLoad = Arrays.asList(
            "com.google.inject.internal.Messages$FormatOptions",
            "com.google.inject.internal.util.LineNumbers",
            "com.google.inject.internal.util.LineNumbers$LineNumberReader",
            "com.google.inject.internal.PackageNameCompressor",
            "com.google.inject.internal.ErrorFormatter"
    );

    try {
        Set<ClassPath.ClassInfo> cp = ClassPath.from(ValvePlugin.class.getClassLoader()).getAllClasses();
        for (ClassPath.ClassInfo x : cp) {
            if (toLoad.contains(x.getName())) {
                x.load();
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
</code>```

This code manually scans all the classes in the entire classpath (I couldn't find a quick way to scan only one package while also including subclasses) and loads in any names present in the list.

Body:
I've been playing around with Guice and stumbled upon this error that doesn't seem to make a lot of sense to me. It seems like whenever an error occurs during injection, Guice fails to properly log the injection error due to a failed message formatting. This could be a bug within Guice, I am not entirely sure.

The jar is being built using the maven-shade-plugin, which includes the necessary dependencies in the jar itself. Looking at the jar's contents, it definitely does contain the class that the NoClassDefFoundError is referring to. The injection itself works completely fine, as long as it does not run into any classes it cannot inject properly.

What makes this stranger is the fact that the code where the exception occurs is in the exact same file as the class that is missing. The following screenshot is taken using IntelliJ's built-in decompiler:

Contents of jar at com.google.inject.internal through winrar:

Stacktrace:

[23:32:10 WARN]: AsyncLogger error handling event seq=231, value='org.apache.logging.log4j.core.async.RingBufferLogEvent@64c2c9e5': java.lang.NoClassDefFoundError: java.lang.NoClassDefFoundError: com/google/inject/internal/Messages$FormatOptions
[23:32:10 WARN]:        at Dodgeball.jar//com.google.inject.internal.Messages.redBold(Messages.java:306)
[23:32:10 WARN]:        at Dodgeball.jar//com.google.inject.spi.ErrorDetail.lambda$format$0(ErrorDetail.java:61)
[23:32:10 WARN]:        at java.base/java.util.Optional.map(Optional.java:260)
[23:32:10 WARN]:        at Dodgeball.jar//com.google.inject.spi.ErrorDetail.format(ErrorDetail.java:61)
[23:32:10 WARN]:        at Dodgeball.jar//com.google.inject.internal.Messages.formatMessages(Messages.java:90)
[23:32:10 WARN]:        at Dodgeball.jar//com.google.inject.ProvisionException.getMessage(ProvisionException.java:60)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.impl.ThrowableProxy.<init>(ThrowableProxy.java:106)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.impl.ThrowableProxy.<init>(ThrowableProxy.java:94)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.async.RingBufferLogEvent.getThrownProxy(RingBufferLogEvent.java:326)
[23:32:10 WARN]:        at io.papermc.paper.logging.DelegateLogEvent.getThrownProxy(DelegateLogEvent.java:103)
[23:32:10 WARN]:        at io.papermc.paper.logging.ExtraClassInfoLogEvent.getThrownProxy(ExtraClassInfoLogEvent.java:21)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.pattern.ExtendedThrowablePatternConverter.format(ExtendedThrowablePatternConverter.java:63)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.pattern.PatternFormatter.format(PatternFormatter.java:38)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.layout.PatternLayout$PatternSelectorSerializer.toSerializable(PatternLayout.java:475)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.layout.PatternLayout.toText(PatternLayout.java:244)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.layout.PatternLayout.encode(PatternLayout.java:229)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.layout.PatternLayout.encode(PatternLayout.java:59)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender.directEncodeEvent(AbstractOutputStreamAppender.java:197)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender.tryAppend(AbstractOutputStreamAppender.java:190)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender.append(AbstractOutputStreamAppender.java:181)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.appender.RollingRandomAccessFileAppender.append(RollingRandomAccessFileAppender.java:251)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.tryCallAppender(AppenderControl.java:156)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.callAppender0(AppenderControl.java:129)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.callAppenderPreventRecursion(AppenderControl.java:120)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.callAppender(AppenderControl.java:84)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.appender.rewrite.RewriteAppender.append(RewriteAppender.java:84)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.tryCallAppender(AppenderControl.java:156)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.callAppender0(AppenderControl.java:129)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.callAppenderPreventRecursion(AppenderControl.java:120)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.callAppender(AppenderControl.java:84)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.appender.rewrite.RewriteAppender.append(RewriteAppender.java:84)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.tryCallAppender(AppenderControl.java:156)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.callAppender0(AppenderControl.java:129)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.callAppenderPreventRecursion(AppenderControl.java:120)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AppenderControl.callAppender(AppenderControl.java:84)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.LoggerConfig.callAppenders(LoggerConfig.java:540)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.LoggerConfig.processLogEvent(LoggerConfig.java:498)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:481)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:469)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.config.AwaitCompletionReliabilityStrategy.log(AwaitCompletionReliabilityStrategy.java:98)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.async.AsyncLogger.actualAsyncLog(AsyncLogger.java:488)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.async.RingBufferLogEvent.execute(RingBufferLogEvent.java:154)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.async.RingBufferLogEventHandler.onEvent(RingBufferLogEventHandler.java:46)
[23:32:10 WARN]:        at org.apache.logging.log4j.core.async.RingBufferLogEventHandler.onEvent(RingBufferLogEventHandler.java:29)
[23:32:10 WARN]:        at com.lmax.disruptor.BatchEventProcessor.processEvents(BatchEventProcessor.java:168)
[23:32:10 WARN]:        at com.lmax.disruptor.BatchEventProcessor.run(BatchEventProcessor.java:125)
[23:32:10 WARN]:        at java.base/java.lang.Thread.run(Thread.java:831)

Main Pom.xml (note that Valve is what contains guice):

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mpolder</groupId>
    <artifactId>Dodgeball</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>16</maven.compiler.source>
        <maven.compiler.target>16</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.3.0-SNAPSHOT</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <finalName>Cameo-Dodgeball</finalName>
                            <relocations>
                                <relocation>
                                    <pattern>com.mpolder.valve</pattern>
                                    <shadedPattern>com.mpolder.dodgeball.valve</shadedPattern>
                                </relocation>
                            </relocations>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <pluginRepositories>
        <pluginRepository>
            <id>maven-snapshots</id>
            <url>https://repository.apache.org/content/repositories/snapshots/</url>
        </pluginRepository>
    </pluginRepositories>

    <repositories>
        <repository>
            <id>spigot-repo</id>
            <url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
        </repository>
        <repository>
            <id>sk89q-repo</id>
            <url>https://maven.enginehub.org/repo/</url>
        </repository>
    </repositories>

    <dependencies>

        <dependency>
            <groupId>org.jetbrains</groupId>
            <artifactId>annotations</artifactId>
            <version>22.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
        <dependency>
            <groupId>org.spigotmc</groupId>
            <artifactId>spigot-api</artifactId>
            <version>1.16.5-R0.1-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.mpolder</groupId>
            <artifactId>Valve</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.sk89q.worldguard</groupId>
            <artifactId>worldguard-bukkit</artifactId>
            <version>7.0.7-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>

Valve pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mpolder</groupId>
    <artifactId>Valve</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>16</maven.compiler.source>
        <maven.compiler.target>16</maven.compiler.target>
    </properties>

    <repositories>
        <repository>
            <id>spigot-repo</id>
            <url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
        </repository>
    </repositories>

    <dependencies>

        <dependency>
            <groupId>org.jetbrains</groupId>
            <artifactId>annotations</artifactId>
            <version>22.0.0</version>
        </dependency>

        <dependency>
            <groupId>org.reflections</groupId>
            <artifactId>reflections</artifactId>
            <version>0.9.12</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.27</version>
        </dependency>

        <dependency>
            <groupId>org.jdbi</groupId>
            <artifactId>jdbi3-core</artifactId>
            <version>3.23.0</version>
        </dependency>

        <dependency>
            <groupId>org.jdbi</groupId>
            <artifactId>jdbi3-sqlobject</artifactId>
            <version>3.23.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
            <version>5.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.spigotmc</groupId>
            <artifactId>spigot-api</artifactId>
            <version>1.16.5-R0.1-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>

Body:
So, this will probably not be the solution anyone was hoping for (including me)

As it turns out, the library I was using called spigot (an extension on bukkit), has its own implementation of a classloader. This classloader just does not seem to function properly whatsoever, and fails to load the subclass even though the class is in the classpath.

The only way I could think of, once finding the cause of the problem, was to manually load in the class using Google Guava. This has fixed the issue, although in a very dirty way. It only needs to run once though, so I have stowed it away deep inside a method which name calls bukkit out on this bug.

If you'd like to know how I fixed it, prepare for a wild ride:

    List<String> toLoad = Arrays.asList(
            "com.google.inject.internal.Messages$FormatOptions",
            "com.google.inject.internal.util.LineNumbers",
            "com.google.inject.internal.util.LineNumbers$LineNumberReader",
            "com.google.inject.internal.PackageNameCompressor",
            "com.google.inject.internal.ErrorFormatter"
    );

    try {
        Set<ClassPath.ClassInfo> cp = ClassPath.from(ValvePlugin.class.getClassLoader()).getAllClasses();
        for (ClassPath.ClassInfo x : cp) {
            if (toLoad.contains(x.getName())) {
                x.load();
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

This code manually scans all the classes in the entire classpath (I couldn't find a quick way to scan only one package while also including subclasses) and loads in any names present in the list.


问:
Can you have permanent IP address with AWS Glue so that it can be whitelisted in Snowflake?
The scenario is this: Our snowflake will only be accessible by whitelisted IP addresses. If we plan to use AWS Glue what IP address can we use so that it will allow us to connect to snowflake? I need a way to identify that this AWS Glue job with IP address (endpoint) so that it can be identified in Snowflake.  I want to use an AWS Glue because it is a serverless orchestration tool.

Thanks,
D.

答: To add onto @amsh's answer, the the NAT gateway should be created in the Public subnet but assigned in the route table of private subnet.


问:
Iterating over list creates endless loop and extends list even though it should not
I iterate over a Sublist (A). A has a defined lenght. Then, i extend another list (B) with the values of (A). For some reason, the first sublist (A) gets extended by the value i extend the other list (B) by.

I have absolutly no idea why this would happen and I'd be very thankfull for help regarding this issue.

```<code>combinations_list = [[[[1, 0], [], -3], [[0, 2], [], -3], [[2, 1], [], -3], [[0, 3], [], -3]]]

for A in combinations_list:
    B = []

    for i in range(len(A)):
        for element in A[i][0]:

            if B == []:
                B.extend(A[i])

            else:
                if element in B[0]:
                    for e in A[i][0]: #Endless loop, A[i][0] gets extended by value of e
                        B[0].extend([e])

</code>```

答: After you do B.extend(A[i]), B[0] references the same list instance as A[0][0].  So ,when you get to B[0].extend([e]), you're actually adding to A[0][0] as well.  The loop for e in A[i][0]: for the first i will never end because you are adding to A[0][0] at every iteration.

Body:
I iterate over a Sublist (A). A has a defined lenght. Then, i extend another list (B) with the values of (A). For some reason, the first sublist (A) gets extended by the value i extend the other list (B) by.

I have absolutly no idea why this would happen and I'd be very thankfull for help regarding this issue.

combinations_list = [[[[1, 0], [], -3], [[0, 2], [], -3], [[2, 1], [], -3], [[0, 3], [], -3]]]

for A in combinations_list:
    B = []

    for i in range(len(A)):
        for element in A[i][0]:

            if B == []:
                B.extend(A[i])

            else:
                if element in B[0]:
                    for e in A[i][0]: #Endless loop, A[i][0] gets extended by value of e
                        B[0].extend([e])


问:
Does anyone can fix my learning C# code of randomNumn and writeOut?
I have a problem of my C# code. Here is an code that I tried:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Console_test
{
    class Program
    {
        static void Main(string[] args)
        {
          Console.WriteLine(writeOut(5,4));
          Console.ReadLine();
        }

        static int randomNum()
        {
            return 4;
        }

        static int writeOut(int num1, int num2)
        {
            int total = num1 + num2;
          Console.WriteLine(total);
        }
    }
}
</code>```

I have a one error, can anyone fix my code? I'm not good with C#.
Error says not all code paths returns a value.

答:
```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Console_test
{
    class Program
    {
        static void Main(string[] args)
        {
          Console.WriteLine(writeOut(5,4));
          Console.ReadLine();
        }

        static int randomNum()
        {
            return 4;
        }

        static int writeOut(int num1, int num2)
        {
            return num1 + num2;

        }
    }
}
</code>```

Body:
I have a problem of my C# code. Here is an code that I tried:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Console_test
{
    class Program
    {
        static void Main(string[] args)
        {
          Console.WriteLine(writeOut(5,4));
          Console.ReadLine();
        }

        static int randomNum()
        {
            return 4;
        }

        static int writeOut(int num1, int num2)
        {
            int total = num1 + num2;
          Console.WriteLine(total);
        }
    }
}

I have a one error, can anyone fix my code? I'm not good with C#.
Error says not all code paths returns a value.


问:
How to iterate over a list of list using 'in' operator
I have a list of lists (path_list; actually this is a path object) and another list (y_path).

Now, I want to remove and filter those two lists based on another list remove_all_list.

The remove function (not in) is working fine. But, when I am using the in function I am getting an empty list.

Code is given below

```<code>remove_all_list = ["Image_034_S_0735_Img_Na__Ma_F_", "Image_033_S_0733_Img_Na__Ma_F_"]

X_test = path_list.copy()
y_test = y_path.copy()

for remove_item in remove_all_list:
    path_list = [[item for item in sub_list if remove_item not in item.name] for sub_list in path_list]
    y_path = [item for item in y_path if remove_item not in item.name]
    X_test = [[item for item in sub_list if remove_item in item.name] for sub_list in X_test]
    y_test = [item for item in y_test if remove_item in item.name]

X_train_val = [x for x in path_list if x] # Removing empty list
X_test_all = [x for x in X_test if x] # Removing empty list
</code>```

The shape I am getting from the loop

```<code>print(np.shape(y_path), np.shape(X_train_val), np.shape(y_test), np.shape(X_test_all))

(2,) (2, 2) (0,) (0,)
</code>```

But, the expected shape is (2,) (2, 2) (2,) (2, 2). Any ideas are appreciated.

Reproducible data

```<code>import numpy as np
from pathlib import Path
path_list = [
    [Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0724_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_033_S_0724_Img_Na__Ma_F_.png')],

    [Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0733_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_033_S_0733_Img_Na__Ma_F_.png')],

    [Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0734_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_034_S_0734_Img_Na__Ma_F_.png')],

    [Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0735_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_034_S_0735_Img_Na__Ma_F_.png')]
  ]
y_path = [
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0724_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0733_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0734_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0735_Img_Na__Ma_F_.png'),
  ]

</code>```

答:
I believe this accomplished what you want.  It's more sensible to filter through the pathlist as the outer loop, then decide line by line whether it's a winner or a loser, sorting into two piles:

```<code>
from pprint import pprint
from pathlib import Path

path_list = [
    [Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0724_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_033_S_0724_Img_Na__Ma_F_.png')],

    [Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0733_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_033_S_0733_Img_Na__Ma_F_.png')],

    [Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0734_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_034_S_0734_Img_Na__Ma_F_.png')],

    [Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0735_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_034_S_0735_Img_Na__Ma_F_.png')]
  ]
y_path = [
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0724_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0733_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0734_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0735_Img_Na__Ma_F_.png'),
  ]

remove_all_list = ["Image_034_S_0735_Img_Na__Ma_F_", "Image_033_S_0733_Img_Na__Ma_F_"]

X_keep = []
X_test = []
for sub_list in path_list:
    if any(all(remove in item.name for item in sub_list) for remove in remove_all_list):
        X_test.append( sub_list )
    else:
        X_keep.append( sub_list )

y_keep = []
y_test = []
for item in y_path:
    if any(remove in item.name for remove in remove_all_list):
        y_test.append( item )
    else:
        y_keep.append( item )

print("PL")
pprint(X_keep)
print("X")
pprint(X_test)
print("yk")
pprint(y_keep)
print("y")
pprint(y_test)
</code>```

Output:

```<code>PL
[[WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0724_Img_Na__Ma_F_.png'),
  WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_033_S_0724_Img_Na__Ma_F_.png')],
 [WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0734_Img_Na__Ma_F_.png'),
  WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_034_S_0734_Img_Na__Ma_F_.png')]]
X
[[WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0733_Img_Na__Ma_F_.png'),
  WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_033_S_0733_Img_Na__Ma_F_.png')],
 [WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0735_Img_Na__Ma_F_.png'),
  WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_034_S_0735_Img_Na__Ma_F_.png')]]
yk
[WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0724_Img_Na__Ma_F_.png'),
 WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0734_Img_Na__Ma_F_.png')]
y
[WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0733_Img_Na__Ma_F_.png'),
 WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0735_Img_Na__Ma_F_.png')]
</code>```

Body:
I have a list of lists (path_list; actually this is a path object) and another list (y_path).

Now, I want to remove and filter those two lists based on another list remove_all_list.

The remove function (not in) is working fine. But, when I am using the in function I am getting an empty list.

Code is given below

remove_all_list = ["Image_034_S_0735_Img_Na__Ma_F_", "Image_033_S_0733_Img_Na__Ma_F_"]

X_test = path_list.copy()
y_test = y_path.copy()

for remove_item in remove_all_list:
    path_list = [[item for item in sub_list if remove_item not in item.name] for sub_list in path_list]
    y_path = [item for item in y_path if remove_item not in item.name]
    X_test = [[item for item in sub_list if remove_item in item.name] for sub_list in X_test]
    y_test = [item for item in y_test if remove_item in item.name]

X_train_val = [x for x in path_list if x] # Removing empty list
X_test_all = [x for x in X_test if x] # Removing empty list

The shape I am getting from the loop

print(np.shape(y_path), np.shape(X_train_val), np.shape(y_test), np.shape(X_test_all))

(2,) (2, 2) (0,) (0,)

But, the expected shape is (2,) (2, 2) (2,) (2, 2). Any ideas are appreciated.

Reproducible data

import numpy as np
from pathlib import Path
path_list = [
    [Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0724_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_033_S_0724_Img_Na__Ma_F_.png')],

    [Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0733_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_033_S_0733_Img_Na__Ma_F_.png')],

    [Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0734_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_034_S_0734_Img_Na__Ma_F_.png')],

    [Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0735_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_034_S_0735_Img_Na__Ma_F_.png')]
  ]
y_path = [
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0724_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0733_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0734_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0735_Img_Na__Ma_F_.png'),
  ]

Body:
I believe this accomplished what you want.  It's more sensible to filter through the pathlist as the outer loop, then decide line by line whether it's a winner or a loser, sorting into two piles:

from pprint import pprint
from pathlib import Path

path_list = [
    [Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0724_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_033_S_0724_Img_Na__Ma_F_.png')],

    [Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0733_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_033_S_0733_Img_Na__Ma_F_.png')],

    [Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0734_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_034_S_0734_Img_Na__Ma_F_.png')],

    [Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0735_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_034_S_0735_Img_Na__Ma_F_.png')]
  ]
y_path = [
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0724_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0733_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0734_Img_Na__Ma_F_.png'),
    Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0735_Img_Na__Ma_F_.png'),
  ]

remove_all_list = ["Image_034_S_0735_Img_Na__Ma_F_", "Image_033_S_0733_Img_Na__Ma_F_"]

X_keep = []
X_test = []
for sub_list in path_list:
    if any(all(remove in item.name for item in sub_list) for remove in remove_all_list):
        X_test.append( sub_list )
    else:
        X_keep.append( sub_list )

y_keep = []
y_test = []
for item in y_path:
    if any(remove in item.name for remove in remove_all_list):
        y_test.append( item )
    else:
        y_keep.append( item )

print("PL")
pprint(X_keep)
print("X")
pprint(X_test)
print("yk")
pprint(y_keep)
print("y")
pprint(y_test)

Output:

PL
[[WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0724_Img_Na__Ma_F_.png'),
  WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_033_S_0724_Img_Na__Ma_F_.png')],
 [WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0734_Img_Na__Ma_F_.png'),
  WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_034_S_0734_Img_Na__Ma_F_.png')]]
X
[[WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0733_Img_Na__Ma_F_.png'),
  WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_033_S_0733_Img_Na__Ma_F_.png')],
 [WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0735_Img_Na__Ma_F_.png'),
  WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_034_S_0735_Img_Na__Ma_F_.png')]]
yk
[WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0724_Img_Na__Ma_F_.png'),
 WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0734_Img_Na__Ma_F_.png')]
y
[WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0733_Img_Na__Ma_F_.png'),
 WindowsPath('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0735_Img_Na__Ma_F_.png')]


问:
Passport.authenticate loops forever
I am using Passport.js to connect my Node application to the Google+ API using a GoogleStrategy.
I call the auth/api route from my frontend (localhost:3000) to my server (localhost:5150).
My code gets to the route successfully and calls the passport.authenticate("google", { scope: ["email"] }) method but no action is performed. My frontend just waits endlessly for the Google callback but it never comes.

Why would this be happening?

My code:

```<code>export const authenticateUsingGoogle = (req, res) => {
  console.log(`authenticating using google`);
    passport.authenticate("google", { scope: ["email", "openid", "profile "] });
  console.log(`authenticated using google`);
};
</code>```

I have seen two similar questions being asked on Stackoverflow but they have no answers:

passport.authenticate() loads forever

Passport.authenticate() gets stucks

答:
passport.authenticate method returns a middleware for express. You need to use it as an argument for your express router.

Example:

app.post('/login/password',
  passport.authenticate("google", { scope: ["email", "openid", "profile "] }),
  function(req, res) {
    // Your actual code.
  });
```

You can find more information here.

Title: Passport.authenticate loops forever

Body:
I am using Passport.js to connect my Node application to the Google+ API using a GoogleStrategy.
I call the auth/api route from my frontend (localhost:3000) to my server (localhost:5150).
My code gets to the route successfully and calls the passport.authenticate("google", { scope: ["email"] }) method but no action is performed. My frontend just waits endlessly for the Google callback but it never comes.

Why would this be happening?

My code:

export const authenticateUsingGoogle = (req, res) => {
  console.log(`authenticating using google`);
    passport.authenticate("google", { scope: ["email", "openid", "profile "] });
  console.log(`authenticated using google`);
};

I have seen two similar questions being asked on Stackoverflow but they have no answers:

passport.authenticate() loads forever

Passport.authenticate() gets stucks

Body:
passport.authenticate method returns a middleware for express. You need to use it as an argument for your express router.

Example:

app.post('/login/password',
  passport.authenticate("google", { scope: ["email", "openid", "profile "] }),
  function(req, res) {
    // Your actual code.
  });

You can find more information here.


问:
Adding constructor to third party class/struct definition
A third party library has structs defined as

```<code>typedef struct _Example
{
  int member;
} Example;
</code>```

As a side question, just out of interest, why that definition? Why not struct Example { ... }?

Anyhow, I want to serialize the information with boost::serialization, and for that need a constructor. Is it safe to just change my version of the 3rd party header file by adding a constructor to the struct definition? Or alternatively, to just copy that definition to my own code base, rename it, add a constructor, and reinterpret_cast to it?

I assume it would be because as I understand functions and constructors shouldn't change the underlying byte layout of the class/struct, is this correct?

Thanks

答:
The typedef struct ... is derives from C and not C++ to use shorthands for structs. Is it possible that the 3rd party library is written in C?

I wouldn't suggest using reinterpret_casts like you are trying. I suggest you create a small wrapper class to encapsulate the Example struct. This is safer and can spare you a lot of debugging pain.

HTH

Body:
A third party library has structs defined as

typedef struct _Example
{
  int member;
} Example;

As a side question, just out of interest, why that definition? Why not struct Example { ... }?

Anyhow, I want to serialize the information with boost::serialization, and for that need a constructor. Is it safe to just change my version of the 3rd party header file by adding a constructor to the struct definition? Or alternatively, to just copy that definition to my own code base, rename it, add a constructor, and reinterpret_cast to it?

I assume it would be because as I understand functions and constructors shouldn't change the underlying byte layout of the class/struct, is this correct?

Thanks


问:
pcl::PointCloud in shared memory
I'm looking for a way to share a pcl::PointCloud between two processes without using files on the disk.
In particular, I'm interested in using boost shared memory libraries to achieve my scope.

I've just tried the following instruction for the sender:

```<code>void * pSharedMemory = ... ; // from wherever
pcl::PointCloud<pcl::PointXYZ>::Ptr ptr = ... ; // from wherever
memcpy ( pSharedMemory , static_cast<void const*>(ptr.get()) , sizeof(pcl::PointCloud<pcl::PointXYZ>) ) ;
</code>```

and the following for the receiver:

```<code>template <typename T> nothing ( T* ) { }

void * pSharedMemory = ... ; // from wherever
pcl::PointCloud<pcl::PointXYZ>::Ptr ptr ( static_cast<pcl::PointCloud<pcl::PointXYZ>*>(pSharedMemory) , &nothing<pcl::PointCloud<pcl::PointXYZ> > ) ; // sets the destructor to do nothing
</code>```

The sender seems to work because I'm able to visualize the PointCloud from the memory, but on the client side the object is correctly created and populated, but I get a segmentation fault when I try to access the points attribute that should contain the points of the clouds. All the other properties (like width, height, ...) are filled with the correct value.

How can I fix this problem and access the points structure? Or is there another way to achieve my scope??

答:
The problem is when pointers are used internally e.g. in the vector implementations:

```<code>using   VectorType = std::vector< PointT, Eigen::aligned_allocator< PointT > >;

using   CloudVectorType = std::vector< PointCloud< PointT >, Eigen::aligned_allocator< PointCloud< PointT > > >;
</code>```

These pointers will only be valid in the "original" address space, and don't point inside the shared address space in the first place. Even if they did, the memory might be mapped on a different address in each process, so it would still be undefined behaviour to use them.

Since PCL doesn't let you override the allocator, this is a dead end, because even if you could make it use interprocess-allocators (using rich pointers like boost::interprocess::offset_ptr<> internally), these would not readily satisfy the extra alignment requirements that the Eigen allocators impose.

It is very possible to share complicated datastructures in shared memory, but the library must have been built with that in mind at least allowing you to choose/parameterize the container/allocator choices. PCL is not such a library at this time.

At this point you could consider serializing data between processes. This might be too costly for your use case, so in that case you might need to look at another library.

Title: pcl::PointCloud in shared memory

Body:
I'm looking for a way to share a pcl::PointCloud between two processes without using files on the disk.
In particular, I'm interested in using boost shared memory libraries to achieve my scope.

I've just tried the following instruction for the sender:

void * pSharedMemory = ... ; // from wherever
pcl::PointCloud<pcl::PointXYZ>::Ptr ptr = ... ; // from wherever
memcpy ( pSharedMemory , static_cast<void const*>(ptr.get()) , sizeof(pcl::PointCloud<pcl::PointXYZ>) ) ;

and the following for the receiver:

template <typename T> nothing ( T* ) { }

void * pSharedMemory = ... ; // from wherever
pcl::PointCloud<pcl::PointXYZ>::Ptr ptr ( static_cast<pcl::PointCloud<pcl::PointXYZ>*>(pSharedMemory) , &nothing<pcl::PointCloud<pcl::PointXYZ> > ) ; // sets the destructor to do nothing

The sender seems to work because I'm able to visualize the PointCloud from the memory, but on the client side the object is correctly created and populated, but I get a segmentation fault when I try to access the points attribute that should contain the points of the clouds. All the other properties (like width, height, ...) are filled with the correct value.

How can I fix this problem and access the points structure? Or is there another way to achieve my scope??

Body:
The problem is when pointers are used internally e.g. in the vector implementations:

using   VectorType = std::vector< PointT, Eigen::aligned_allocator< PointT > >;

using   CloudVectorType = std::vector< PointCloud< PointT >, Eigen::aligned_allocator< PointCloud< PointT > > >;

These pointers will only be valid in the "original" address space, and don't point inside the shared address space in the first place. Even if they did, the memory might be mapped on a different address in each process, so it would still be undefined behaviour to use them.

Since PCL doesn't let you override the allocator, this is a dead end, because even if you could make it use interprocess-allocators (using rich pointers like boost::interprocess::offset_ptr<> internally), these would not readily satisfy the extra alignment requirements that the Eigen allocators impose.

It is very possible to share complicated datastructures in shared memory, but the library must have been built with that in mind at least allowing you to choose/parameterize the container/allocator choices. PCL is not such a library at this time.

At this point you could consider serializing data between processes. This might be too costly for your use case, so in that case you might need to look at another library.


问:
How to find min/max aggregations with diffrerent filters in MongoDB?
Considering collection clothing of documents with this strucure

```<code>{
  "brand": <string>,
  "color": <string>,
  "size": <number>
}
</code>```

In a single aggregation grouing by brand I would like to find two values:

min size for all documents in a group where color="blue"

max size for all documents in a group where color="red"

In SQL it would be something like this:

```<code>SELECT MIN(CASE color WHEN "blue" THEN size ELSE NULL END),
       MAX(CASE color WHEN "red" THEN size ELSE NULL END),
       brand
  FROM clothing
 GROUP BY brand
</code>```

How to express this in MongoDB query?

答:
Query

$min,$max works on documents also, comparing fields in order

"blue" is smaller than "red" so we dont need any extra step
(if this was not the case you could say if blue => 1 else 0 to change the order, like assign a number to the possible strings, and have that number in the place of $color)

Test code here

aggregate(
[{"$group":
  {"_id":"$brand",
   "min-blue":{"$min":{"color":"$color", "size":"$size"}},
   "max-red":{"$max":{"color":"$color", "size":"$size"}}}}])
```

Body:
Considering collection clothing of documents with this strucure

{
  "brand": <string>,
  "color": <string>,
  "size": <number>
}

In a single aggregation grouing by brand I would like to find two values:

min size for all documents in a group where color="blue"

max size for all documents in a group where color="red"

In SQL it would be something like this:

SELECT MIN(CASE color WHEN "blue" THEN size ELSE NULL END),
       MAX(CASE color WHEN "red" THEN size ELSE NULL END),
       brand
  FROM clothing
 GROUP BY brand

How to express this in MongoDB query?


问:
How to call destructor of C++ class safely from a Python wrapper class using ctypes?
I built a C++ shared library, that exports functions for constructing, destructing and interacting with an implemented class. I want to write a wrapper class in Python, which loads the compiled .dll and wraps all the functions as a class using ctypes .

How do I wrap the destructor function of the C++ class safely so it will be called in any case (Normal Garbage Collection, Exceptions etc) ?

答:
As per Python's data model doc:

Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether...

...

Some objects contain references to “external” resources such as open files or windows. It is understood that these resources are freed when the object is garbage-collected, but since garbage collection is not guaranteed to happen, such objects also provide an explicit way to release the external resource, usually a close() method. Programs are strongly recommended to explicitly close such objects. The try…finally statement and the with statement provide convenient ways to do this.

So even if in most cases __del__ method of an object is being called by GC, it is not guaranteed. with statement (from PEP 343) on the other hand guarantees that if __enter__ method of the object succeeded, then __exit__ method will be called at the end of the statement, both in case of normal execution and in case of exception. (More detailed in this question)

An example could be as below, with the usage of "object-closing" context manager from PEP 343 examples, and a wrapper class with close method which calls native object's destructor:

```<code>class NativeObjectWrapper(object):
    def __init__(self):
        self.nativeObject = nativeLib.CreateInstance()
    def close(self):
        nativeLib.DestructorFunction(self.nativeObject)

class closing(object):
    def __init__(self, obj):
        self.obj = obj
    def __enter__(self):
        return self.obj
    def __exit__(self, *exc_info):
        try:
            close_it = self.obj.close
        except AttributeError:
            pass
        else:
            close_it()

#example of usage
with closing(NativeObjectWrapper()) as objectWrapper:
    ... #some usage of native wrapper
</code>```

Body:
As per Python's data model doc:

Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether...

...

Some objects contain references to “external” resources such as open files or windows. It is understood that these resources are freed when the object is garbage-collected, but since garbage collection is not guaranteed to happen, such objects also provide an explicit way to release the external resource, usually a close() method. Programs are strongly recommended to explicitly close such objects. The try…finally statement and the with statement provide convenient ways to do this.

So even if in most cases __del__ method of an object is being called by GC, it is not guaranteed. with statement (from PEP 343) on the other hand guarantees that if __enter__ method of the object succeeded, then __exit__ method will be called at the end of the statement, both in case of normal execution and in case of exception. (More detailed in this question)

An example could be as below, with the usage of "object-closing" context manager from PEP 343 examples, and a wrapper class with close method which calls native object's destructor:

class NativeObjectWrapper(object):
    def __init__(self):
        self.nativeObject = nativeLib.CreateInstance()
    def close(self):
        nativeLib.DestructorFunction(self.nativeObject)

class closing(object):
    def __init__(self, obj):
        self.obj = obj
    def __enter__(self):
        return self.obj
    def __exit__(self, *exc_info):
        try:
            close_it = self.obj.close
        except AttributeError:
            pass
        else:
            close_it()

#example of usage
with closing(NativeObjectWrapper()) as objectWrapper:
    ... #some usage of native wrapper


问:
PowerShell Script to Get a Directory Total Size
I need to get the size of a directory, recursively. I have to do this every month so I want to make a PowerShell script to do it.

How can I do it?

答:
To refine this answer by @JaredPar to be expanded and more performant:

```<code>function Get-DirectorySize() {
  param ([string]$root = $(Resolve-Path .))
  Get-ChildItem $root -Recurse -File |
    Measure-Object -Property Length -Sum |
    Select-Object -ExpandProperty Sum
}
</code>```

Or, to make it more convenient for use explore type data:

```<code>Update-TypeData -TypeName System.IO.DirectoryInfo -MemberType ScriptProperty -MemberName Size -Value {
  Get-ChildItem $this -Recurse -File |
    Measure-Object -Property Length -Sum |
    Select-Object -ExpandProperty Sum
}
</code>```

Then use by Get-ChildItem | Select-Object Name,Length,Size

ContentLicense: CC BY-SA 2.5

Body:
To refine this answer by @JaredPar to be expanded and more performant:

function Get-DirectorySize() {
  param ([string]$root = $(Resolve-Path .))
  Get-ChildItem $root -Recurse -File |
    Measure-Object -Property Length -Sum |
    Select-Object -ExpandProperty Sum
}

Or, to make it more convenient for use explore type data:

Update-TypeData -TypeName System.IO.DirectoryInfo -MemberType ScriptProperty -MemberName Size -Value {
  Get-ChildItem $this -Recurse -File |
    Measure-Object -Property Length -Sum |
    Select-Object -ExpandProperty Sum
}

Then use by Get-ChildItem | Select-Object Name,Length,Size


问:
not able to create the rule for the ingress controller
What am I going wrong in the below query?

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: nginx-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
  - http:
      paths:
      - path: /nginx
        backend:
          serviceName: nginx
          servicePort: 80
```
<p>The error I am getting:</p>
```error validating "ingress.yaml": error validating data: [ValidationError(Ingress.spec.rules[0].http.paths[0].backend): unknown field "serviceName" in io.k8s.api.networking.v1.IngressBackend, ValidationError(Ingress.spec.rules[0].http.paths[0].backend): unknown field "servicePort" in io.k8s.api.networking.v1.IngressBackend]; if you choose to ignore these errors, turn validation off with
--validate=false
```

答:
According to this documentation you need to change ServiceName and ServicePort.

Each HTTP rule contains (...) a list of paths (for example,  /testpath), each of which has an associated backend defined with a  service.name  and a  service.port.name  or  service.port.number. Both the host and path must match the content of an incoming request before the load balancer directs traffic to the referenced Service.

Here is your yaml file with corrections:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: nginx-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
  - http:
      paths:
      - path: /nginx
        backend:
          service:
            name: nginx
            port:
              number: 8080
```

Body:
What am I going wrong in the below query?

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: nginx-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
  - http:
      paths:
      - path: /nginx
        backend:
          serviceName: nginx
          servicePort: 80

The error I am getting:

error validating "ingress.yaml": error validating data: [ValidationError(Ingress.spec.rules[0].http.paths[0].backend): unknown field "serviceName" in io.k8s.api.networking.v1.IngressBackend, ValidationError(Ingress.spec.rules[0].http.paths[0].backend): unknown field "servicePort" in io.k8s.api.networking.v1.IngressBackend]; if you choose to ignore these errors, turn validation off with
--validate=false


问:
Kafka - Unbalanced consumer_offsets
I see in a Kafka installation the size of the different 50(in my case) partitions of __customer_offsets is very uneven, with half of them having size 0.

Is this normal, or is it an indication of something going wrong or suboptimal?

答:
It's normal.

The hashes of the consumer group name strings that your clients are using may cause "hotspots" in those partitions since those names are the keys of the offset records.

Title: Kafka - Unbalanced consumer_offsets