问:
How to create a DOT file using Graphviz for multiple edges between two same nodes with different attributes
I want to create multiple edges between two same nodes in a dot file with different labels/attribute. Here is an example:

```<code>G = nx.Graph()
G.add_node("Tom")
G.nodes["Tom"]["Id"]=Tom
G.nodes["Tom"]["label"]="Thomas Fisher"
G.add_node("Calle")
G.nodes["Calle"]["Id"]="Calle"
G.nodes["Calle"]["label"]="Calle Man"
G.add_edge("Tom","Calle")
G.edges[("Tom","Calle")]["type"]="publication"
G.edges[("Tom","Calle")]["year"]="2008"
G.edges[("Tom","Calle")]["type"]="grant"
G.edges[("Tom","Calle")]["year"]="2014"

write_dot(G,'my_graph.dot')
</code>```

But the output dot file is like

```<code>Tom  [Id=Tom,
        label="Thomas Fisher"];

Calle [Id= Calle,
        label = "Calle Man"];

Tome -- Calle    [type="grant",
        year="2014"];
</code>```

I want this output in the dot file

```<code>Tom  [Id="Tom",
        label="Thomas Fisher"];

Calle [Id= "Calle",
        label = "Calle Man"];
Tome -- Calle    [type="publication",
        year=2008];

Tome -- Calle    [type="grant",
        year="2014"];
</code>```

Body:
I want to create multiple edges between two same nodes in a dot file with different labels/attribute. Here is an example:

G = nx.Graph()
G.add_node("Tom")
G.nodes["Tom"]["Id"]=Tom
G.nodes["Tom"]["label"]="Thomas Fisher"
G.add_node("Calle")
G.nodes["Calle"]["Id"]="Calle"
G.nodes["Calle"]["label"]="Calle Man"
G.add_edge("Tom","Calle")
G.edges[("Tom","Calle")]["type"]="publication"
G.edges[("Tom","Calle")]["year"]="2008"
G.edges[("Tom","Calle")]["type"]="grant"
G.edges[("Tom","Calle")]["year"]="2014"

write_dot(G,'my_graph.dot')

But the output dot file is like

Tom  [Id=Tom,
        label="Thomas Fisher"];

Calle [Id= Calle,
        label = "Calle Man"];

Tome -- Calle    [type="grant",
        year="2014"];

I want this output in the dot file

Tom  [Id="Tom",
        label="Thomas Fisher"];

Calle [Id= "Calle",
        label = "Calle Man"];
Tome -- Calle    [type="publication",
        year=2008];

Tome -- Calle    [type="grant",
        year="2014"];


来源: stackexchange

问:
I'm getting duplicate traces using Serilog's Application Insight's sink and Application Insights SDK
I'm getting duplicate traces when using Serilog's Application Insight's sink and Application Insights SDK.

The following is my Serilog's configuration in appsettings.json:

```<code>  "Serilog": {
    "Using": [
      "Serilog.Sinks.ApplicationInsights"
    ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "System": "Information",
        "Microsoft": "Information"
      }
    },
    "WriteTo": [
      {
        "Name": "ApplicationInsights",
        "Args": {
          "restrictedToMinimumLevel": "Information",
          "connectionString": "InstrumentationKey=9edfafc1-8526-461b-95b4-aee1f72291d7;IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/",
          "telemetryConverter": "Serilog.Sinks.ApplicationInsights.TelemetryConverters.EventTelemetryConverter, Serilog.Sinks.ApplicationInsights"
        }
      }
    ],
    "Enrich": [
      "WithMachineName",
      "WithProcessId",
      "FromLogContext"
    ]
  }
</code>```

Inside the Program.cs:

```<code>               .UseSerilog((hostingContext, services, loggerConfiguration) =>
                {
                    loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration);
                }, writeToProviders: true
                )
</code>```

Inside the Startup.cs:

```<code>                services.AddApplicationInsightsTelemetry(o =>
                {
                    o.EnableAdaptiveSampling = false;
                });
</code>```

Duplicate traces example. The Custom Event one is coming from Serilog, the other one from the SDK I guess

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

ContentLicense: CC BY-SA 4.0

Body:
I'm getting duplicate traces when using Serilog's Application Insight's sink and Application Insights SDK.

The following is my Serilog's configuration in appsettings.json:

  "Serilog": {
    "Using": [
      "Serilog.Sinks.ApplicationInsights"
    ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "System": "Information",
        "Microsoft": "Information"
      }
    },
    "WriteTo": [
      {
        "Name": "ApplicationInsights",
        "Args": {
          "restrictedToMinimumLevel": "Information",
          "connectionString": "InstrumentationKey=9edfafc1-8526-461b-95b4-aee1f72291d7;IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/",
          "telemetryConverter": "Serilog.Sinks.ApplicationInsights.TelemetryConverters.EventTelemetryConverter, Serilog.Sinks.ApplicationInsights"
        }
      }
    ],
    "Enrich": [
      "WithMachineName",
      "WithProcessId",
      "FromLogContext"
    ]
  }

Inside the Program.cs:

               .UseSerilog((hostingContext, services, loggerConfiguration) =>
                {
                    loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration);
                }, writeToProviders: true
                )

Inside the Startup.cs:

                services.AddApplicationInsightsTelemetry(o =>
                {
                    o.EnableAdaptiveSampling = false;
                });

Duplicate traces example. The Custom Event one is coming from Serilog, the other one from the SDK I guess


问:
Openssl pkcs12 -in client_cert.pfx -out ca.pem -cacerts -nokeys , which is the equivalent in NET 6 programmatically using X509Certificate2
Given a pfx file (and of course its password) containing a self-signed CA certificate together with a client certificate (signed with the CA) and its private key, is it possible to use the X509Certificate2 class (or another .NET 6 class) to programmatically get the equivalent of this openssl command:

```<code>openssl pkcs12 -in client_cert.pfx -out ca.pem -cacerts -nokeys
</code>```

The windows certificate store has no entries at all regarding these certificates, the only thing available is the pfx file containing the self-signed root ca certificate, the client certificate and the private key. The purpose is to extract the ca root certificate as X509Certificate2 object from the pfx file.

Body:
Given a pfx file (and of course its password) containing a self-signed CA certificate together with a client certificate (signed with the CA) and its private key, is it possible to use the X509Certificate2 class (or another .NET 6 class) to programmatically get the equivalent of this openssl command:

openssl pkcs12 -in client_cert.pfx -out ca.pem -cacerts -nokeys

The windows certificate store has no entries at all regarding these certificates, the only thing available is the pfx file containing the self-signed root ca certificate, the client certificate and the private key. The purpose is to extract the ca root certificate as X509Certificate2 object from the pfx file.


问:
Remove Address Bar of Webpage Accessed Through TWA
I'm currently working on a TWA and I need to redirect the user to another web app I created.  The problem is when the user redirects to the other web app, the page now has a address bar.  My goal is to confine the user within the app, but with the address bar present it's possible for users to open a chrome instance and break out of the app.  That being said, is it possible to keep address bar removed when redirecting out of the TWA?</p>


问:
submit button not responding to required drop down menu
javascript below does not inactivate the submit button in a web form when a drop down menu is required but not selected. The required popup warning shows up but the submit button is active and is replaced by a spinning gif.
Required text fields in the form (not show) work as they should and prevent the submit button from entering the form if not filled.

part of the form

```<code><label for="type">Start Time</label><br>
    <select name="TimeBegin" id="TimeBegin" required>
       <option value=""></option>
  <option value="9 A.M.">9 A.M.</option>
  <option value="9:30 A.M.">9:30 A.M.</option>
  <option value="10 A.M.">10 A.M.</option>
  <option value="10:30 A.M.">10:30 A.M.</option>

  <option value="11 A.M.">11 A.M.</option>
  <option value="11:30 A.M.">11:30 A.M.</option>
  <option value="12 A.M.">12 P.M.</option>
  <option value="12:30 P.M.">12:30 P.M.</option>
  <option value="1 P.M.">1 P.M.</option>
  <option value="1:30 P.M.">1:30 P.M.</option>
  <option value="2 P.M.">2 P.M.</option>
  <option value="2:30 P.M.">2:30 P.M.</option>

  <option value="3 P.M.">3 P.M.</option>
  <option value="3:30 P.M.">3:30 P.M.</option>
  <option value="4 P.M.">4 P.M.</option>
  <option value="4:30 P.M.">4:30 P.M.</option>
  <option value="5 P.M.">5 P.M.</option>
  <option value="5:30 P.M.">5:30 P.M.</option>
  <option value="6 P.M.">6 P.M.</option>
  <option value="6:30 P.M.">6:30 P.M.</option>
  <option value="7 P.M.">7 P.M.</option>
  <option value="7:30 P.M.">7:30 P.M.</option>
</select><br><br>
</code>```

and the javascript

```<code><div id="formsubmitbutton">
<input type="submit" name="submit" value="UPLOAD" onclick="ButtonClicked()">
</div>
    <div id="buttonreplacement" style="margin-left:30px; display:none;">
<img src="preloadgif.gif" alt="loading...">
</div>
</center>
   </form>

 </section>

      <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
    </script>
      <script>

ButtonClicked = function(){
     var validate = true;
   $('input:required').each(function(){
    if($(this).val().trim() === ''){
        validate = false;
    }
   });
   if(validate) {
        document.getElementById("formsubmitbutton").style.display = "none"; // to undisplay
    document.getElementById("buttonreplacement").style.display = ""; // to display
    return true;
   }
}
var FirstLoading = true;
function RestoreSubmitButton()
{
   if( FirstLoading )
   {
      FirstLoading = false;
      return;
   }
   document.getElementById("formsubmitbutton").style.display = ""; // to display
   document.getElementById("buttonreplacement").style.display = "none"; // to undisplay
}
// To disable restoring submit button, disable or delete next line.

  document.onfocus = RestoreSubmitButton;

      </script>
</code>```

Body:
javascript below does not inactivate the submit button in a web form when a drop down menu is required but not selected. The required popup warning shows up but the submit button is active and is replaced by a spinning gif.
Required text fields in the form (not show) work as they should and prevent the submit button from entering the form if not filled.

part of the form

Start Time

    <select name="TimeBegin" id="TimeBegin" required>
       <option value=""></option>
  <option value="9 A.M.">9 A.M.</option>
  <option value="9:30 A.M.">9:30 A.M.</option>
  <option value="10 A.M.">10 A.M.</option>
  <option value="10:30 A.M.">10:30 A.M.</option>

  <option value="11 A.M.">11 A.M.</option>
  <option value="11:30 A.M.">11:30 A.M.</option>
  <option value="12 A.M.">12 P.M.</option>
  <option value="12:30 P.M.">12:30 P.M.</option>
  <option value="1 P.M.">1 P.M.</option>
  <option value="1:30 P.M.">1:30 P.M.</option>
  <option value="2 P.M.">2 P.M.</option>
  <option value="2:30 P.M.">2:30 P.M.</option>

  <option value="3 P.M.">3 P.M.</option>
  <option value="3:30 P.M.">3:30 P.M.</option>
  <option value="4 P.M.">4 P.M.</option>
  <option value="4:30 P.M.">4:30 P.M.</option>
  <option value="5 P.M.">5 P.M.</option>
  <option value="5:30 P.M.">5:30 P.M.</option>
  <option value="6 P.M.">6 P.M.</option>
  <option value="6:30 P.M.">6:30 P.M.</option>
  <option value="7 P.M.">7 P.M.</option>
  <option value="7:30 P.M.">7:30 P.M.</option>
</select>

and the javascript

<input type="submit" name="submit" value="UPLOAD" onclick="ButtonClicked()">

   </form>


问:
Elementor Custom Query Filter (authors list in posts catigory)
I need to add Custom Query Filter in elemenore posts (archives) to get List authors that have written certain number of posts in category archive
((Authors List without duplicts in page))

I need to code Custom Query Filter

https://developers.elementor.com/docs/hooks/custom-query-filter/

https://developer.wordpress.org/reference/classes/wp_query/


问:
how do I charge all items in a cart array at the same time in stripe checkout?
I have been trying to figure this out for a full week now. using stripe, how do I present the user with all of the items that they put in their cart in my nextjs e-commerce store.I can get it to work with one item as long as I don't do anything to try and change that item. as soon as I do anything to try and change the item I don't get any errors but the localhost reloads on the button press and I see an empty cart page. I have tried at least 6 different tutorials and contacted the stripe developer support 3 times. nothing has worked so here is my current relevant front end code:

```<code>const stripePromise = loadStripe(
  process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY
);

function Checkout() {
  const [basket, addToBasket] = useAppContext();
  const {data: session} = useSession();
  const [id, setId] = useState([]);
  const [price, setprice] = useState([]);
  const [description, setdescription] = useState([]);
  const [title, settitle] = useState([]);

  const updateState = () => {
    setId(basket.id);
    setdescription(basket.description);
    setprice(basket.price);
    settitle(basket.title);
  }

  //send data to the api

    const postData = async () => {
      const response = await fetch("/api/checkout_sessions", {
        method: "POST",
        body: JSON.stringify(
          id,
          price,
          description,
          title,
        ),
      });
      return response.json();
    };

  React.useEffect(() => {
    // Check to see if this is a redirect back from Checkout
    const query = new URLSearchParams(window.location.search);
    if (query.get('success')) {
      console.log('Order placed! You will receive an email confirmation.');
    }

    if (query.get('canceled')) {
      console.log('Order canceled -- continue to shop around and checkout when youre ready.');
    }
  }, []);
  return (
   <form onSubmit={() => {
        updateState;
         postData;
            }} >
   <button
   type="submit"
   role="link"
   className="button"
   >
   proceed to checkout
 </button>
                    </form>
)}

</code>```

here is my current backend that is supposed to send my user to the cart to make their purchase. like I said at the start what happens is I have items in my basket and I press the checkout button but everything reloads and I stay at the cart page.

```<code>
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

export default async function handler(req, res) {
    const items = req.body.id
    const amount = req.body.price
    const description = req.body.description
    const title = req.body.title

// var priceVariable ='price_1MB8P4FqoomU2P4qrVmtxCvp';

  if (req.method === 'POST') {
    try {
      // Create Checkout Sessions from body params.
      const session = await stripe.checkout.sessions.create({
        // shipping_options: ["shr_1MBn0HFqoomU2P4qZk4vqOQ3"],
        shipping_address_collection: {
          allowed_countries: ["US", "CA", "GB"],
        },
       line_items:[{
        price: items,
        quantity: 1,
          price_data: {
            currency: 'usd',
            unit_amount: amount,
            product_data: {
              description: description,
              name: title,
            }},
       }],
        mode: 'payment',
        success_url: `${req.headers.origin}/?success=true`,
        cancel_url: `${req.headers.origin}/?canceled=true`,
      });
      res.redirect(303, session.url);
    } catch (err) {
      res.status(err.statusCode || 500).json(err.message);
    }
  } else {
    res.setHeader('Allow', 'POST');
    res.status(405).end('Method Not Allowed');
  }
}
</code>```

thanks for the help y'all

Body:
I have been trying to figure this out for a full week now. using stripe, how do I present the user with all of the items that they put in their cart in my nextjs e-commerce store.I can get it to work with one item as long as I don't do anything to try and change that item. as soon as I do anything to try and change the item I don't get any errors but the localhost reloads on the button press and I see an empty cart page. I have tried at least 6 different tutorials and contacted the stripe developer support 3 times. nothing has worked so here is my current relevant front end code:

const stripePromise = loadStripe(
  process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY
);

function Checkout() {
  const [basket, addToBasket] = useAppContext();
  const {data: session} = useSession();
  const [id, setId] = useState([]);
  const [price, setprice] = useState([]);
  const [description, setdescription] = useState([]);
  const [title, settitle] = useState([]);

  const updateState = () => {
    setId(basket.id);
    setdescription(basket.description);
    setprice(basket.price);
    settitle(basket.title);
  }

  //send data to the api

    const postData = async () => {
      const response = await fetch("/api/checkout_sessions", {
        method: "POST",
        body: JSON.stringify(
          id,
          price,
          description,
          title,
        ),
      });
      return response.json();
    };

  React.useEffect(() => {
    // Check to see if this is a redirect back from Checkout
    const query = new URLSearchParams(window.location.search);
    if (query.get('success')) {
      console.log('Order placed! You will receive an email confirmation.');
    }

    if (query.get('canceled')) {
      console.log('Order canceled -- continue to shop around and checkout when youre ready.');
    }
  }, []);
  return (
   <form onSubmit={() => {
        updateState;
         postData;
            }} >
   <button
   type="submit"
   role="link"
   className="button"
   >
   proceed to checkout
 </button>
                    </form>
)}

here is my current backend that is supposed to send my user to the cart to make their purchase. like I said at the start what happens is I have items in my basket and I press the checkout button but everything reloads and I stay at the cart page.

const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

export default async function handler(req, res) {
    const items = req.body.id
    const amount = req.body.price
    const description = req.body.description
    const title = req.body.title

// var priceVariable ='price_1MB8P4FqoomU2P4qrVmtxCvp';

  if (req.method === 'POST') {
    try {
      // Create Checkout Sessions from body params.
      const session = await stripe.checkout.sessions.create({
        // shipping_options: ["shr_1MBn0HFqoomU2P4qZk4vqOQ3"],
        shipping_address_collection: {
          allowed_countries: ["US", "CA", "GB"],
        },
       line_items:[{
        price: items,
        quantity: 1,
          price_data: {
            currency: 'usd',
            unit_amount: amount,
            product_data: {
              description: description,
              name: title,
            }},
       }],
        mode: 'payment',
        success_url: `${req.headers.origin}/?success=true`,
        cancel_url: `${req.headers.origin}/?canceled=true`,
      });
      res.redirect(303, session.url);
    } catch (err) {
      res.status(err.statusCode || 500).json(err.message);
    }
  } else {
    res.setHeader('Allow', 'POST');
    res.status(405).end('Method Not Allowed');
  }
}

thanks for the help y'all


问:
Cannot append function into an array because of attribute 'split'
My task here is first split a given string into two parts, the year and month. For example, if the input is ex1_b("2000,12"), the function should return 2000-Dec.

And then I want to keep the new format of the data and insert into an array. Then after I will try to insert it inside a DataFrame. But I have problems with appending the results of the function.

The function itself is working, and outputs correctly, but when I try to append the results inside an array, it gives out the following error

AttributeError                            Traceback (most recent call last)
Cell In[460], line 4
      1 new_format = []
      3 for i in range (0, len(date)):
----> 4     new_format.append(ex1_b(date[i]))
      6 print(new_format)

Cell In[459], line 15, in ex1_b(date)
     11 f_date = date_val[date_val.columns[0]]
     12 # f_date = date_val[date_val.columns[0]]
     13 # s_value = date_val.iloc[:,1].values
---> 15 years =  int(date.split(",")[0]) # even if I change to str() no change
     16 months = int(date.split(",")[1])
     17 # matrix_b.to_csv("matrix-B.csv", index=False)
     18 # input = [int(i) for i in date.split(",")]
     19 # input = [int(i) for i in f_date.str.split(",")]

AttributeError: 'int' object has no attribute 'split'
```
<p>How can I solve this?</p>
<p>My code</p>
```date_val = {'date' : [],
            'value' : []}

for i in range(0, 25):
    for j in range(0, 12):
        month = str(j+1).zfill(2)
        date_val['date'].append( str(year[i]) + "," + month)
        date_val['value'].append(df.loc[i,j+1])
        date.append(str(year[i]) + "," + month)
        value.append(df.loc[i,j+1])
date_val = pd.DataFrame(date_val)

mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
          'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
def ex1_b(date:str):
    f_date = date_val[date_val.columns[0]] #IN CASE I WILL NEED IT

    years =  int(date.split(",")[0])
    months = int(date.split(",")[1])

    if(years<2022 or years>1996 or months>0 or months<13):
        year_month = f"{str(years)}-{mon[months-1]}"

    return year_month
print(ex1_b("2000,12")) #WORKS

# THE PROBLEM
new_format = []
for i in range (0, len(date)):
    new_format.append(ex1_b(date[i]))

print(new_format)
```

Body:
My task here is first split a given string into two parts, the year and month. For example, if the input is ex1_b("2000,12"), the function should return 2000-Dec.

And then I want to keep the new format of the data and insert into an array. Then after I will try to insert it inside a DataFrame. But I have problems with appending the results of the function.

The function itself is working, and outputs correctly, but when I try to append the results inside an array, it gives out the following error

AttributeError                            Traceback (most recent call last)
Cell In[460], line 4
      1 new_format = []
      3 for i in range (0, len(date)):
----> 4     new_format.append(ex1_b(date[i]))
      6 print(new_format)

Cell In[459], line 15, in ex1_b(date)
     11 f_date = date_val[date_val.columns[0]]
     12 # f_date = date_val[date_val.columns[0]]
     13 # s_value = date_val.iloc[:,1].values
---> 15 years =  int(date.split(",")[0]) # even if I change to str() no change
     16 months = int(date.split(",")[1])
     17 # matrix_b.to_csv("matrix-B.csv", index=False)
     18 # input = [int(i) for i in date.split(",")]
     19 # input = [int(i) for i in f_date.str.split(",")]

AttributeError: 'int' object has no attribute 'split'

How can I solve this?

My code

date_val = {'date' : [],
            'value' : []}

for i in range(0, 25):
    for j in range(0, 12):
        month = str(j+1).zfill(2)
        date_val['date'].append( str(year[i]) + "," + month)
        date_val['value'].append(df.loc[i,j+1])
        date.append(str(year[i]) + "," + month)
        value.append(df.loc[i,j+1])
date_val = pd.DataFrame(date_val)

mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
          'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
def ex1_b(date:str):
    f_date = date_val[date_val.columns[0]] #IN CASE I WILL NEED IT

    years =  int(date.split(",")[0])
    months = int(date.split(",")[1])

    if(years<2022 or years>1996 or months>0 or months<13):
        year_month = f"{str(years)}-{mon[months-1]}"

    return year_month
print(ex1_b("2000,12")) #WORKS

# THE PROBLEM
new_format = []
for i in range (0, len(date)):
    new_format.append(ex1_b(date[i]))

print(new_format)


问:
Convert timm model to huggingface
I have a (PyTorch) timm ViT-B/16 model that's been pre-trained on a bunch of domain specific data. I'd like to be able to load the parameters to an equivalent model created using the huggingface transformers library for usage with multi-modal data.

Googling hasn't really helped me locate a convenience function to do the conversion. Apart from going layer by layer and manually translating the keys of the state dictionary, is there any way to do this conversion?

And in case I'm missing something, if there's an intervening layer (say a BatchNorm) that doesn't have an equivalent in either model - is the conversion still useful?

Title: Convert timm model to huggingface


问:
Pass custom data to stateless EJB
I'm generating a correlation ID on my client and I need to pass it to the server so if anything is logged, the same ID is used.

I've tried

```<code>context = new InitialContext();
context.addToEnvironment("correlationId", correlationId);
context.lookup(jndi);
</code>```

and

```<code>Properties props = new Properties();
properties.put("correlationId", correlationId);
// as well as properties.setProperty("correlationId", correlationId);
context = new InitialContext(props);
context.lookup(jndi);
</code>```

and then I call my function.

I am attempting to get the data with the following, but none contain the data I would have expected:

```<code>Map<String, Object> hmm2 = sessionContext.getContextData();
</code>```

and

```<code>Context tmp = (Context)sessionContext.lookup("java:comp/env");
</code>```

sessionContext is injectected with DI.

Title: Pass custom data to stateless EJB

Body:
I'm generating a correlation ID on my client and I need to pass it to the server so if anything is logged, the same ID is used.

I've tried

context = new InitialContext();
context.addToEnvironment("correlationId", correlationId);
context.lookup(jndi);

and

Properties props = new Properties();
properties.put("correlationId", correlationId);
// as well as properties.setProperty("correlationId", correlationId);
context = new InitialContext(props);
context.lookup(jndi);

and then I call my function.

I am attempting to get the data with the following, but none contain the data I would have expected:

Map<String, Object> hmm2 = sessionContext.getContextData();

and

Context tmp = (Context)sessionContext.lookup("java:comp/env");

sessionContext is injectected with DI.


问:
Modifying a variable within a %%timeit cell doesn't change the variable
If in the first cell I write:

%%timeit
a = [1, 2, 3, 4, 5, 6, 7]
a.append(0)
```

when printing a in another cell, I don't have [1, 2, 3, 4, 5, 6, 7, 0], I thought I would've have it because after defining a and appending 0 n times, I would get the last a defined then appended with a 0.

Screenshot from VScode (Python 3.11)

Body:
If in the first cell I write:

%%timeit
a = [1, 2, 3, 4, 5, 6, 7]
a.append(0)

when printing a in another cell, I don't have [1, 2, 3, 4, 5, 6, 7, 0], I thought I would've have it because after defining a and appending 0 n times, I would get the last a defined then appended with a 0.

Screenshot from VScode (Python 3.11)


问:
Open a Window in JUCE and put a PluginEditor into it
The tl;dr How do I open a window in Juce to display a plugin Editor?

I am following the Juce AudioProcessGraph tutorial at https://docs.juce.com/master/tutorial_audio_processor_graph.html which shows how to dynamically load AudioProcessor objects.

I would like to open their GUIs as they're loaded.  This could be in separate windows or in the window that's got the slots for the graph.

I've tried creating a AudioProcessorEditor, but I'm at a loss on how to tell it to open.

Edit to add: What I've tried so far:

I've downloaded the code from the Tutorial: Cascading plug-in effects from https://docs.juce.com/master/tutorial_audio_processor_graph.html

I've also used ProJucer to create a new plugin. I've put the new plugin's files into the tutorial's files and used ProJucer to add PluginEditor.cpp and PluginEditor.h to the tutorial project.

I've changed the PluginEditor.h so the private class member audioProcessor is of type ProcessorBase&. And made ProcessorBase& the expected type for the data passed to the constructor.

In the tutorial code, in the header file, I've changed the ProcessorBase class so that the methods hasEditor() and createEditor() are just declarations and then modified main.cpp as follows:

```<code>#include "PluginEditor.h"
#include <iostream>

//=======================================================
juce::AudioProcessorEditor* ProcessorBase::createEditor()
{
  std::cout "asking for an editor\n";
  return  new NewProjectAudioProcessorEditor (*this);
}
bool ProcessorBase::hasEditor() const
{ return true; }
</code>```

In the included header, in the TutorialProcessor class, in the updateGraph() method, under the if (hasChanged), I've added slot->getProcessor()->createEditorIfNeeded (); on line 387-ish.

I can tell from my cout that createEditor() is being called and know that the constructor for the editor is running, but no window opens.

How do I tell it to open a window?

The code compiles and runs, but no window opens.

Body:
The tl;dr How do I open a window in Juce to display a plugin Editor?

I am following the Juce AudioProcessGraph tutorial at https://docs.juce.com/master/tutorial_audio_processor_graph.html which shows how to dynamically load AudioProcessor objects.

I would like to open their GUIs as they're loaded.  This could be in separate windows or in the window that's got the slots for the graph.

I've tried creating a AudioProcessorEditor, but I'm at a loss on how to tell it to open.

Edit to add: What I've tried so far:

I've downloaded the code from the Tutorial: Cascading plug-in effects from https://docs.juce.com/master/tutorial_audio_processor_graph.html

I've also used ProJucer to create a new plugin. I've put the new plugin's files into the tutorial's files and used ProJucer to add PluginEditor.cpp and PluginEditor.h to the tutorial project.

I've changed the PluginEditor.h so the private class member audioProcessor is of type ProcessorBase&. And made ProcessorBase& the expected type for the data passed to the constructor.

In the tutorial code, in the header file, I've changed the ProcessorBase class so that the methods hasEditor() and createEditor() are just declarations and then modified main.cpp as follows:

#include "PluginEditor.h"
#include <iostream>

//=======================================================
juce::AudioProcessorEditor* ProcessorBase::createEditor()
{
  std::cout "asking for an editor\n";
  return  new NewProjectAudioProcessorEditor (*this);
}
bool ProcessorBase::hasEditor() const
{ return true; }

In the included header, in the TutorialProcessor class, in the updateGraph() method, under the if (hasChanged), I've added slot->getProcessor()->createEditorIfNeeded (); on line 387-ish.

I can tell from my cout that createEditor() is being called and know that the constructor for the editor is running, but no window opens.

How do I tell it to open a window?

The code compiles and runs, but no window opens.


问:
Ruby on Rails 7, Action Text, Rich Content. Image in rich_content field does not render in View
Rookie trying to follow example in Rails Guide for Action Text using Trix editor

App works great locally but images in rich_content field appear as icons in Views when run in production on Heroku - and on Flyio as well.

I understand about the temporary nature of file system on Heroku; but, even right after saving [the blog article], only the image icon is displayed in View.  When user clicks to edit, the image is there.  Maybe 30minutes later the image is gone but I believe that is a different issue.

I tried connecting an AmazonS3 bucket - on Heroku; but there was no change. [Full- disclosure:  an examination of the bucket showed 0 contents so I didn't get that to work]

I tried on Fly.io.  Created a volume for disk storage there but behavior is the same:  icon displays in View and image displays in Edit.

I am using gem image-processing.  As said, all works fine locally.

This is code of _blob.html.erb.  I confirmed with the debugger that blob.representable? is true

```<code><figure class="attachment attachment--<%= blob.representable? ? "preview" : "file" %>
    attachment--<%= blob.filename.extension %>">
  <% if blob.representable? %>
    <%= image_tag blob.representation(resize_to_limit: local_assigns[:in_gallery] ?
             [ 800, 600 ] : [ 1024, 768 ]) %>
  <% end %>

  <figcaption class="attachment__caption">
    <% if caption = blob.try(:caption) %>
      <%= caption %>
    <% else %>
      <span class="attachment__name"><%= blob.filename %></span>
      <span class="attachment__size"><%= number_to_human_size blob.byte_size %></span>
    <% end %>
  </figcaption>
</figure>
</code>```

This is application.scss

@import 'bootstrap';
@import "custom";
@import "mystyles";
@import 'actiontext.css';
```

When I inspect the browser page, taken from the app on heroku:

I can confirm that the contents of "url=", when open in a browser tab, displays the image that is part of the rich_content

But, as shown in the screen image, I get status 404 errors
browser inspect

Body:
Rookie trying to follow example in Rails Guide for Action Text using Trix editor

App works great locally but images in rich_content field appear as icons in Views when run in production on Heroku - and on Flyio as well.

I understand about the temporary nature of file system on Heroku; but, even right after saving [the blog article], only the image icon is displayed in View.  When user clicks to edit, the image is there.  Maybe 30minutes later the image is gone but I believe that is a different issue.

I tried connecting an AmazonS3 bucket - on Heroku; but there was no change. [Full- disclosure:  an examination of the bucket showed 0 contents so I didn't get that to work]

I tried on Fly.io.  Created a volume for disk storage there but behavior is the same:  icon displays in View and image displays in Edit.

I am using gem image-processing.  As said, all works fine locally.

This is code of _blob.html.erb.  I confirmed with the debugger that blob.representable? is true

<figure class="attachment attachment--<%= blob.representable? ? "preview" : "file" %>
    attachment--<%= blob.filename.extension %>">
  <% if blob.representable? %>
    <%= image_tag blob.representation(resize_to_limit: local_assigns[:in_gallery] ?
             [ 800, 600 ] : [ 1024, 768 ]) %>
  <% end %>

    <% if caption = blob.try(:caption) %>
      <%= caption %>
    <% else %>
      <%= blob.filename %>
      <%= number_to_human_size blob.byte_size %>
    <% end %>

This is application.scss

@import 'bootstrap';
@import "custom";
@import "mystyles";
@import 'actiontext.css';

When I inspect the browser page, taken from the app on heroku:

I can confirm that the contents of "url=", when open in a browser tab, displays the image that is part of the rich_content

But, as shown in the screen image, I get status 404 errors
browser inspect


问:
How to use Firestore and Room together in MVVM?
My app currently uses Room for all its storage needs. It has a fairly complex database hierarchy, where there are two parent tables A and B (both <20 rows each) which then have children tables A1,A2,A3 and B1,B2. These sub-tables are quite data heavy with a few thousand rows each which are updated daily.

I recently learned about Firebase and specifically, authentification and cloud Firestore. I would like to leverage this for my app, so that when a user logs on from another device, they can be using the same synced data across devices.

Given my data structure mentioned in first paragraph, the way I am thinking of approaching it is having Tables A and B on Firestore. This will pull the core metadata needed and have small number of rows. I will then use this data to update the sub tables A1-A3 and B1-B2 which will be performed locally using Room.

I am having some trouble thinking about how I would integrate these two approaches together. For example, how to aggregate the parent and child table data in the domain layer. I previously used Room relational tables for this but that does not seem like an option now some of my tables are coming Firestore. Does anyone have any ideas/materials on how to use Firestore and Room in this way?


问:
Jekyll-archieves, trace tags in other folder
I tried to use Jekyll-archieves to generate the tags index in _sites by using the following

```<code>  jekyll-archives:
  enabled: [categories, tags]
  layouts:
    category: category
    tag: tag
  permalinks:
    tag: /tags/:name/
    category: /categories/:name/
</code>```

But I found it only works for the markdown files in _posts folder. Currently, I have created separate folders for different markdown files by using permalink , for example, I use a 'work' folder to store all work-related markdown files and a 'travel' folder to store all travel-related markdown files, like this. How should I modify the above codes so that the jekyll-archives can trace all tags?

Body:
I tried to use Jekyll-archieves to generate the tags index in _sites by using the following

  jekyll-archives:
  enabled: [categories, tags]
  layouts:
    category: category
    tag: tag
  permalinks:
    tag: /tags/:name/
    category: /categories/:name/

But I found it only works for the markdown files in _posts folder. Currently, I have created separate folders for different markdown files by using permalink , for example, I use a 'work' folder to store all work-related markdown files and a 'travel' folder to store all travel-related markdown files, like this. How should I modify the above codes so that the jekyll-archives can trace all tags?


问:
How do I select an attribute from a Nokogiri::XML.parse result set element
So far I can only get to each  element I wanna know how to get the attributes like address from results that look like <sms protocol="0" address="+18334120420" ...
Here's my code that only goes as far as getting each sms element:</p>
```<code>file=File.open('test.xml')
doc=Nokogiri::XML.parse(file)
doc.xpath('//sms').each do |msg|
  puts msg
end
</code>```

Body:
So far I can only get to each  element I wanna know how to get the attributes like address from results that look like <sms protocol="0" address="+18334120420" ...
Here's my code that only goes as far as getting each sms element:

file=File.open('test.xml')
doc=Nokogiri::XML.parse(file)
doc.xpath('//sms').each do |msg|
  puts msg
end


问:
Query Graphql is not called
After migrating a kotlin project's spring boot version to 2.7.5, I needed to change some old dependencies.
After these updates, neither queries nor mutations are being called.
As a result, the graphql call returns null.
The application starts up normally, with no errors. And no error is logged when I call graphql through postman.
Below is my Resolver class

```<code>package io.company.op.vehicle.resolver

import io.company.op.vehicle.model.\*
import io.company.op.vehicle.model.dto.ModelConfigInput
import io.company.op.vehicle.pagination.ModelConfigPage
import io.company.op.vehicle.security.SecurityService
import io.company.op.vehicle.service.ModelConfigService
import io.company.op.vehicle.utils.formattedError
import org.slf4j.LoggerFactory
import org.springframework.graphql.data.method.annotation.MutationMapping
import org.springframework.graphql.data.method.annotation.QueryMapping
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.stereotype.Component

@Component
class ModelConfigResolver(

    private val modelConfigService: ModelConfigService,

    private val securityService: SecurityService

) {

    @PreAuthorize("@securityService.canFetchModelConfig()")
    @QueryMapping
    fun fetchAllModelConfig(
        searchTerm: String,
        searchEngineTypeEmpty: Boolean,
        searchLockLocationTypeEmpty: Boolean,
        searchTransmissionTypeEmpty: Boolean,
        engineTypes: List<EngineType>,
        lockLocationTypes: List<LockLocationType>,
        transmissionTypes: List<TransmissionType>,
        status: List<ModelConfigStatus>,
        page: Int,
        pageSize: Int = 5
    ): ModelConfigPage? {
        val user = securityService.getUser()

        try {
            return modelConfigService.fetchAllModelConfig(
                searchTerm,
                searchEngineTypeEmpty,
                searchLockLocationTypeEmpty,
                searchTransmissionTypeEmpty,
                engineTypes,
                lockLocationTypes,
                transmissionTypes,
                status,
                page,
                pageSize
            )
        } catch (ex: Exception) {
            log.formattedError(
                "fetchAllModelConfig",
                user,
                "SearchTerm: $searchTerm, EngineTypes: $engineTypes, LockLocationTypes: $lockLocationTypes, TransmissionTypes: $transmissionTypes, Status: $status",
                ex
            )
            throw ex
        }
    }

    @PreAuthorize("@securityService.canFetchModelConfig()")
    @QueryMapping
    fun fetchModelConfig(
        vehicleModelId: Long,
        vds: String,
        modelYear: Int,
        transmissionType: TransmissionType
    ): ModelConfig? {
        val user = securityService.getUser()
        try {
            return modelConfigService.fetchModelConfig(
                vehicleModelId, vds, modelYear, transmissionType
            )
        } catch (ex: Exception) {
            log.formattedError(
                "fetchModelConfig",
                user,
                "VehicleModelId: $vehicleModelId, vds: $vds, modelYear: $modelYear, TransmissionType: $transmissionType",
                ex
            )
            throw ex
        }
    }

    @PreAuthorize("@securityService.canFetchModelConfig()")
    @QueryMapping
    fun fetchModelConfigById(
        id: Long
    ): ModelConfig? {
        val user = securityService.getUser()
        try {
            return modelConfigService.fetchModelConfigById(id)
        } catch (ex: Exception) {
            log.formattedError(
                "fetchModelConfig",
                user,
                "Id: $id",
                ex
            )
            throw ex
        }
    }

    @PreAuthorize("@securityService.canCreateOrUpdateModelConfig()")
    @MutationMapping
    fun createOrUpdateModelConfig(modelConfigInput: ModelConfigInput): ModelConfig {
        val user = securityService.getUser()
        try {
            return modelConfigService.createOrUpdateModelConfig(modelConfigInput, user)
        } catch (ex: Exception) {
            log.formattedError(
                "createOrUpdateModelConfig",
                user,
                "ModelConfigInput: $modelConfigInput",
                ex
            )
            throw ex
        }
    }

    @PreAuthorize("@securityService.canHomologateModelConfig()")
    @MutationMapping
    fun homologateModelConfig(modelConfigInput: ModelConfigInput): ModelConfig {
        val user = securityService.getUser()
        try {
            return modelConfigService.homologateModelConfig(modelConfigInput, user)
        } catch (ex: Exception) {
            log.formattedError(
                "homologateModelConfig",
                user,
                "ModelConfigInput: $modelConfigInput",
                ex
            )
            throw ex
        }
    }

    @PreAuthorize("@securityService.canDeleteModelConfig()")
    @MutationMapping
    fun deleteModelConfig(id: Long): ModelConfig {
        val user = securityService.getUser()
        try {
            return modelConfigService.deleteModelConfig(id, user)
        } catch (ex: Exception) {
            log.formattedError(
                "deleteModelConfig",
                user,
                "ModelConfigId: $id",
                ex
            )
            throw ex
        }
    }

    companion object {
        val log = LoggerFactory.getLogger(ModelConfigResolver::class.java)!!
    }

}

</code>```

SecurityConfiguration Class

```<code>
package io.company.op.vehicle.security

import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import io.company.cd.common.spring.auth.AuthFilter
import io.company.cd.common.spring.auth.domain.TokenType
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
class SecurityConfiguration : WebSecurityConfigurerAdapter() {

    @Value("\${vehicle.op.jwk.key-set}")
    private lateinit var keySet: List<String>

    @Value("\${vehicle.op.jwt.token-types}")
    private lateinit var jsonTokenTypes: String

    protected val mapper = jacksonObjectMapper()

    override fun configure(http: HttpSecurity) {
        val tokenTypes: List<TokenType> = mapper.readValue(jsonTokenTypes, Array<TokenType>::class.java).toList()
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/graphql").permitAll()
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .addFilterBefore(
                AuthFilter.create(keySet, tokenTypes),
                RequestHeaderAuthenticationFilter::class.java
            )
    }

}

</code>```

SecurityService Class

```<code>
package io.company.op.vehicle.security

import io.compaompanyny.cd.common.spring.auth.domain.IntegrationToken
import io.company.cd.common.spring.auth.domain.CToken
import io.company.cd.common.spring.auth.domain.UnrestrictedToken
import io.company.op.vehicle.exception.VehicleErrorType
import io.company.op.vehicle.exception.VehicleException
import org.slf4j.LoggerFactory
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.stereotype.Service

@Service
class SecurityService {

    fun getUser(): User {
        return when (val token = SecurityContextHolder.getContext().authentication.principal) {
            is CompanyToken ->
                User(
                    username = token.username,
                    type = UserType.COMPANY
                )

            is UnrestrictedToken ->
                User(
                    username = "Unrestricted",
                    type = UserType.UNRESTRICTED
                )
            is IntegrationToken ->
                User(
                    username = "Integration",
                    type = UserType.INTEGRATION
                )
            else -> throw VehicleException(VehicleErrorType.UNAUTHORIZED)
        }
    }

    fun canFetchModelConfig(): Boolean {
        val user = getUser()
        log.debug("Validating fetch model config for User: ${user.username}")
        return when (user.type) {
            UserType.COMPANY -> true
            UserType.UNRESTRICTED -> true
            UserType.INTEGRATION -> true
        }
    }

    fun canCreateOrUpdateModelConfig(): Boolean {
        val user = getUser()
        log.debug("Validating create model config for User: ${user.username}")
        return when (user.type) {
            UserType.COMPANY -> true
            UserType.UNRESTRICTED -> true
            UserType.INTEGRATION -> true
        }
    }

    fun canDeleteModelConfig(): Boolean {
        val user = getUser()
        log.debug("Validating delete model config for User: ${user.username}")
        return when (user.type) {
            UserType.COMPANY -> true
            UserType.UNRESTRICTED -> true
            UserType.INTEGRATION -> true
        }
    }

    fun canHomologateModelConfig(): Boolean {
        val user = getUser()
        log.debug("Validating homologate model config for User: ${user.username}")
        return when (user.type) {
            UserType.COMPANY -> true
            UserType.UNRESTRICTED -> true
            UserType.INTEGRATION -> true
        }
    }

    fun canFetchVehicleModel(): Boolean {
        val user = getUser()
        log.debug("Validating fetch vehicle model for User: ${user.username}")
        return when (user.type) {
            UserType.COMPANY -> true
            UserType.UNRESTRICTED -> true
            UserType.INTEGRATION -> true
        }
    }

    fun canFetchVehicleBrand(): Boolean {
        val user = getUser()
        log.debug("Validating fetch vehicle brand for User: ${user.username}")
        return when (user.type) {
            UserType.COMPANY -> true
            UserType.UNRESTRICTED -> true
            UserType.INTEGRATION -> true
        }
    }

    companion object {
        val log = LoggerFactory.getLogger(SecurityService::class.java)!!
    }

}

</code>```

Application Log

```<code>
2022-12-08 18:17:42.748  INFO 8516 --- \[           main\] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo \[name: default\]
2022-12-08 18:17:42.810  INFO 8516 --- \[           main\] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.6.12.Final
2022-12-08 18:17:43.005  INFO 8516 --- \[           main\] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-12-08 18:17:43.152  INFO 8516 --- \[           main\] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL9Dialect
2022-12-08 18:17:43.580  INFO 8516 --- \[           main\] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: \[org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform\]
2022-12-08 18:17:43.592  INFO 8516 --- \[           main\] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-12-08 18:17:43.883  WARN 8516 --- \[           main\] .s.s.UserDetailsServiceAutoConfiguration :

Using generated security password: 96d94b82-7cd1-431c-a831-3ed6d56519bc

This generated password is for development use only. Your security configuration must be updated before running your application in production.

2022-12-08 18:17:44.091  INFO 8516 --- \[           main\] o.s.s.web.DefaultSecurityFilterChain     : Will secure any request with \[org.springframework.security.web.session.DisableEncodeUrlFilter@32db94fb, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@6b61a4b0, org.springframework.security.web.context.SecurityContextPersistenceFilter@570089c4, org.springframework.security.web.header.HeaderWriterFilter@40e90634, org.springframework.security.web.authentication.logout.LogoutFilter@34538ffe, io.company.cd.common.spring.auth.AuthFilter@5c00de0d, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@6e818345, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@6e2e11ee, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@6278371a, org.springframework.security.web.session.SessionManagementFilter@b6fea12, org.springframework.security.web.access.ExceptionTranslationFilter@655d5285, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@64e680c5\]
2022-12-08 18:17:45.419  INFO 8516 --- \[           main\] s.b.a.g.s.GraphQlWebMvcAutoConfiguration : GraphQL endpoint HTTP POST /graphql
2022-12-08 18:17:45.981  INFO 8516 --- \[           main\] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 1 endpoint(s) beneath base path '/actuator'
2022-12-08 18:17:46.077  INFO 8516 --- \[           main\] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 9090 (http) with context path ''
2022-12-08 18:17:46.094  INFO 8516 --- \[           main\] io.company.op.vehicle.VehicleApplicationKt  : Started VehicleApplicationKt in 8.186 seconds (JVM running for 9.011)
2022-12-08 18:17:58.028  INFO 8516 --- \[nio-9090-exec-2\] o.a.c.c.C.\[Tomcat\].\[localhost\].\[/\]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-12-08 18:17:58.029  INFO 8516 --- \[nio-9090-exec-2\] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2022-12-08 18:17:58.031  INFO 8516 --- \[nio-9090-exec-2\] o.s.web.servlet.DispatcherServlet        : Completed initialization in 2 ms

</code>```

When calling the query fetchAllModelConfig it returns this:

```<code>
{
"data": {
"fetchAllModelConfig": null
}
}

</code>```

Title: Query Graphql is not called

Body:
After migrating a kotlin project's spring boot version to 2.7.5, I needed to change some old dependencies.
After these updates, neither queries nor mutations are being called.
As a result, the graphql call returns null.
The application starts up normally, with no errors. And no error is logged when I call graphql through postman.
Below is my Resolver class

package io.company.op.vehicle.resolver

import io.company.op.vehicle.model.\*
import io.company.op.vehicle.model.dto.ModelConfigInput
import io.company.op.vehicle.pagination.ModelConfigPage
import io.company.op.vehicle.security.SecurityService
import io.company.op.vehicle.service.ModelConfigService
import io.company.op.vehicle.utils.formattedError
import org.slf4j.LoggerFactory
import org.springframework.graphql.data.method.annotation.MutationMapping
import org.springframework.graphql.data.method.annotation.QueryMapping
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.stereotype.Component

@Component
class ModelConfigResolver(

    private val modelConfigService: ModelConfigService,

    private val securityService: SecurityService

) {

    @PreAuthorize("@securityService.canFetchModelConfig()")
    @QueryMapping
    fun fetchAllModelConfig(
        searchTerm: String,
        searchEngineTypeEmpty: Boolean,
        searchLockLocationTypeEmpty: Boolean,
        searchTransmissionTypeEmpty: Boolean,
        engineTypes: List<EngineType>,
        lockLocationTypes: List<LockLocationType>,
        transmissionTypes: List<TransmissionType>,
        status: List<ModelConfigStatus>,
        page: Int,
        pageSize: Int = 5
    ): ModelConfigPage? {
        val user = securityService.getUser()

        try {
            return modelConfigService.fetchAllModelConfig(
                searchTerm,
                searchEngineTypeEmpty,
                searchLockLocationTypeEmpty,
                searchTransmissionTypeEmpty,
                engineTypes,
                lockLocationTypes,
                transmissionTypes,
                status,
                page,
                pageSize
            )
        } catch (ex: Exception) {
            log.formattedError(
                "fetchAllModelConfig",
                user,
                "SearchTerm: $searchTerm, EngineTypes: $engineTypes, LockLocationTypes: $lockLocationTypes, TransmissionTypes: $transmissionTypes, Status: $status",
                ex
            )
            throw ex
        }
    }

    @PreAuthorize("@securityService.canFetchModelConfig()")
    @QueryMapping
    fun fetchModelConfig(
        vehicleModelId: Long,
        vds: String,
        modelYear: Int,
        transmissionType: TransmissionType
    ): ModelConfig? {
        val user = securityService.getUser()
        try {
            return modelConfigService.fetchModelConfig(
                vehicleModelId, vds, modelYear, transmissionType
            )
        } catch (ex: Exception) {
            log.formattedError(
                "fetchModelConfig",
                user,
                "VehicleModelId: $vehicleModelId, vds: $vds, modelYear: $modelYear, TransmissionType: $transmissionType",
                ex
            )
            throw ex
        }
    }

    @PreAuthorize("@securityService.canFetchModelConfig()")
    @QueryMapping
    fun fetchModelConfigById(
        id: Long
    ): ModelConfig? {
        val user = securityService.getUser()
        try {
            return modelConfigService.fetchModelConfigById(id)
        } catch (ex: Exception) {
            log.formattedError(
                "fetchModelConfig",
                user,
                "Id: $id",
                ex
            )
            throw ex
        }
    }

    @PreAuthorize("@securityService.canCreateOrUpdateModelConfig()")
    @MutationMapping
    fun createOrUpdateModelConfig(modelConfigInput: ModelConfigInput): ModelConfig {
        val user = securityService.getUser()
        try {
            return modelConfigService.createOrUpdateModelConfig(modelConfigInput, user)
        } catch (ex: Exception) {
            log.formattedError(
                "createOrUpdateModelConfig",
                user,
                "ModelConfigInput: $modelConfigInput",
                ex
            )
            throw ex
        }
    }

    @PreAuthorize("@securityService.canHomologateModelConfig()")
    @MutationMapping
    fun homologateModelConfig(modelConfigInput: ModelConfigInput): ModelConfig {
        val user = securityService.getUser()
        try {
            return modelConfigService.homologateModelConfig(modelConfigInput, user)
        } catch (ex: Exception) {
            log.formattedError(
                "homologateModelConfig",
                user,
                "ModelConfigInput: $modelConfigInput",
                ex
            )
            throw ex
        }
    }

    @PreAuthorize("@securityService.canDeleteModelConfig()")
    @MutationMapping
    fun deleteModelConfig(id: Long): ModelConfig {
        val user = securityService.getUser()
        try {
            return modelConfigService.deleteModelConfig(id, user)
        } catch (ex: Exception) {
            log.formattedError(
                "deleteModelConfig",
                user,
                "ModelConfigId: $id",
                ex
            )
            throw ex
        }
    }

    companion object {
        val log = LoggerFactory.getLogger(ModelConfigResolver::class.java)!!
    }

}

SecurityConfiguration Class

package io.company.op.vehicle.security

import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import io.company.cd.common.spring.auth.AuthFilter
import io.company.cd.common.spring.auth.domain.TokenType
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
class SecurityConfiguration : WebSecurityConfigurerAdapter() {

    @Value("\${vehicle.op.jwk.key-set}")
    private lateinit var keySet: List<String>

    @Value("\${vehicle.op.jwt.token-types}")
    private lateinit var jsonTokenTypes: String

    protected val mapper = jacksonObjectMapper()

    override fun configure(http: HttpSecurity) {
        val tokenTypes: List<TokenType> = mapper.readValue(jsonTokenTypes, Array<TokenType>::class.java).toList()
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/graphql").permitAll()
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .addFilterBefore(
                AuthFilter.create(keySet, tokenTypes),
                RequestHeaderAuthenticationFilter::class.java
            )
    }

}

SecurityService Class

package io.company.op.vehicle.security

import io.compaompanyny.cd.common.spring.auth.domain.IntegrationToken
import io.company.cd.common.spring.auth.domain.CToken
import io.company.cd.common.spring.auth.domain.UnrestrictedToken
import io.company.op.vehicle.exception.VehicleErrorType
import io.company.op.vehicle.exception.VehicleException
import org.slf4j.LoggerFactory
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.stereotype.Service

@Service
class SecurityService {

    fun getUser(): User {
        return when (val token = SecurityContextHolder.getContext().authentication.principal) {
            is CompanyToken ->
                User(
                    username = token.username,
                    type = UserType.COMPANY
                )

            is UnrestrictedToken ->
                User(
                    username = "Unrestricted",
                    type = UserType.UNRESTRICTED
                )
            is IntegrationToken ->
                User(
                    username = "Integration",
                    type = UserType.INTEGRATION
                )
            else -> throw VehicleException(VehicleErrorType.UNAUTHORIZED)
        }
    }

    fun canFetchModelConfig(): Boolean {
        val user = getUser()
        log.debug("Validating fetch model config for User: ${user.username}")
        return when (user.type) {
            UserType.COMPANY -> true
            UserType.UNRESTRICTED -> true
            UserType.INTEGRATION -> true
        }
    }

    fun canCreateOrUpdateModelConfig(): Boolean {
        val user = getUser()
        log.debug("Validating create model config for User: ${user.username}")
        return when (user.type) {
            UserType.COMPANY -> true
            UserType.UNRESTRICTED -> true
            UserType.INTEGRATION -> true
        }
    }

    fun canDeleteModelConfig(): Boolean {
        val user = getUser()
        log.debug("Validating delete model config for User: ${user.username}")
        return when (user.type) {
            UserType.COMPANY -> true
            UserType.UNRESTRICTED -> true
            UserType.INTEGRATION -> true
        }
    }

    fun canHomologateModelConfig(): Boolean {
        val user = getUser()
        log.debug("Validating homologate model config for User: ${user.username}")
        return when (user.type) {
            UserType.COMPANY -> true
            UserType.UNRESTRICTED -> true
            UserType.INTEGRATION -> true
        }
    }

    fun canFetchVehicleModel(): Boolean {
        val user = getUser()
        log.debug("Validating fetch vehicle model for User: ${user.username}")
        return when (user.type) {
            UserType.COMPANY -> true
            UserType.UNRESTRICTED -> true
            UserType.INTEGRATION -> true
        }
    }

    fun canFetchVehicleBrand(): Boolean {
        val user = getUser()
        log.debug("Validating fetch vehicle brand for User: ${user.username}")
        return when (user.type) {
            UserType.COMPANY -> true
            UserType.UNRESTRICTED -> true
            UserType.INTEGRATION -> true
        }
    }

    companion object {
        val log = LoggerFactory.getLogger(SecurityService::class.java)!!
    }

}

Application Log

2022-12-08 18:17:42.748  INFO 8516 --- \[           main\] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo \[name: default\]
2022-12-08 18:17:42.810  INFO 8516 --- \[           main\] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.6.12.Final
2022-12-08 18:17:43.005  INFO 8516 --- \[           main\] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-12-08 18:17:43.152  INFO 8516 --- \[           main\] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL9Dialect
2022-12-08 18:17:43.580  INFO 8516 --- \[           main\] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: \[org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform\]
2022-12-08 18:17:43.592  INFO 8516 --- \[           main\] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-12-08 18:17:43.883  WARN 8516 --- \[           main\] .s.s.UserDetailsServiceAutoConfiguration :

Using generated security password: 96d94b82-7cd1-431c-a831-3ed6d56519bc

This generated password is for development use only. Your security configuration must be updated before running your application in production.

2022-12-08 18:17:44.091  INFO 8516 --- \[           main\] o.s.s.web.DefaultSecurityFilterChain     : Will secure any request with \[org.springframework.security.web.session.DisableEncodeUrlFilter@32db94fb, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@6b61a4b0, org.springframework.security.web.context.SecurityContextPersistenceFilter@570089c4, org.springframework.security.web.header.HeaderWriterFilter@40e90634, org.springframework.security.web.authentication.logout.LogoutFilter@34538ffe, io.company.cd.common.spring.auth.AuthFilter@5c00de0d, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@6e818345, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@6e2e11ee, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@6278371a, org.springframework.security.web.session.SessionManagementFilter@b6fea12, org.springframework.security.web.access.ExceptionTranslationFilter@655d5285, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@64e680c5\]
2022-12-08 18:17:45.419  INFO 8516 --- \[           main\] s.b.a.g.s.GraphQlWebMvcAutoConfiguration : GraphQL endpoint HTTP POST /graphql
2022-12-08 18:17:45.981  INFO 8516 --- \[           main\] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 1 endpoint(s) beneath base path '/actuator'
2022-12-08 18:17:46.077  INFO 8516 --- \[           main\] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 9090 (http) with context path ''
2022-12-08 18:17:46.094  INFO 8516 --- \[           main\] io.company.op.vehicle.VehicleApplicationKt  : Started VehicleApplicationKt in 8.186 seconds (JVM running for 9.011)
2022-12-08 18:17:58.028  INFO 8516 --- \[nio-9090-exec-2\] o.a.c.c.C.\[Tomcat\].\[localhost\].\[/\]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-12-08 18:17:58.029  INFO 8516 --- \[nio-9090-exec-2\] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2022-12-08 18:17:58.031  INFO 8516 --- \[nio-9090-exec-2\] o.s.web.servlet.DispatcherServlet        : Completed initialization in 2 ms

When calling the query fetchAllModelConfig it returns this:

{
"data": {
"fetchAllModelConfig": null
}
}


问:
How can I set a different profile pic for different messages sent by my Slack app?
Please excuse my English. I have a Slack app that I am using to post messages. I am using a web API written in C# .NET 6.0 to post these messages.

I would like to change the profile pic based on which one of three types of content the bot is sending.

The bot used to use the Slack.Webhooks package. This lets me set up a SlackClient and SlackMessage. Then all I had to do was say client.PostAsync(message). It has a username property. But I couldn't change the username. When I changed the Username property of the SlackMessage object it still posted under the app name.

So I have started posting instead to https://slack.com/api/chat.postMessage. I am following the documentation here. First I set up a bot token for my app with the scopes chat:write and chat:write.customize, which says it allows me to "send messages as @My-SlackApp with a customized username and avatar". I also had to add the bot to my test channel.

Now when I changed the username in my model this is now working!

But I have tried changing the icon_url (I've also tried using icon_emoji which would also work). No matter what I do I only get the app's profile picture.

I am not sure if my app is a "classic slack app" (i created it today), but just in case I have also tried setting as_user=true, as_user=false and without as_user at all.

Here is the code that I am using to send the messages. What I expected to happen is that the message that got posted to slack would have the image (a google logo) as its profile pic. Instead, the message that got posted had my app's profile pic.

Any idea what I should be doing differently to be able to choose a custom avatar or emoji to display as my bot's profile pic for each message?

```<code>var slackMessage = new MySlackMessage()
{
    //As_User = false,
    Username = "My Custom Name",
    Text = "This text needs to have a google logo!",
    Icon_Url = "https://fulltimeblog.com/wp-content/uploads/2019/05/1024px-Google__G__Logo-1.png",
    //Icon_Emoji = ":heart:",
    Channel = "test"
};

using (HttpClient client = new HttpClient())
{
    var requestMessage = new HttpRequestMessage(HttpMethod.Post, "https://slack.com/api/chat.postMessage");
    requestMessage.Content = JsonContent.Create<MySlackMessage>(slackMessage);
    requestMessage.Headers.Add("Authorization", $"Bearer {token}");

    var response = client.Send(requestMessage);

    var result = response.Content.ReadAsStream();
    using (StreamReader sr = new StreamReader(result))
    {
        Console.WriteLine(sr.ReadToEnd());
    }
}
</code>```

Here's the model I'm sending through by the way.

```<code>public class MySlackMessage
{
    // public bool As_User { get; set; }
    public string Text { get; set; }
    public string Username { get; set; }
    public string Icon_Url { get; set; }
    // public string Icon_Emoji { get; set; }
    public string Channel { get; set; }
}
</code>```

Any ideas how I can set my bots profile pic dynamically when I create the message?

Body:
Please excuse my English. I have a Slack app that I am using to post messages. I am using a web API written in C# .NET 6.0 to post these messages.

I would like to change the profile pic based on which one of three types of content the bot is sending.

The bot used to use the Slack.Webhooks package. This lets me set up a SlackClient and SlackMessage. Then all I had to do was say client.PostAsync(message). It has a username property. But I couldn't change the username. When I changed the Username property of the SlackMessage object it still posted under the app name.

So I have started posting instead to https://slack.com/api/chat.postMessage. I am following the documentation here. First I set up a bot token for my app with the scopes chat:write and chat:write.customize, which says it allows me to "send messages as @My-SlackApp with a customized username and avatar". I also had to add the bot to my test channel.

Now when I changed the username in my model this is now working!

But I have tried changing the icon_url (I've also tried using icon_emoji which would also work). No matter what I do I only get the app's profile picture.

I am not sure if my app is a "classic slack app" (i created it today), but just in case I have also tried setting as_user=true, as_user=false and without as_user at all.

Here is the code that I am using to send the messages. What I expected to happen is that the message that got posted to slack would have the image (a google logo) as its profile pic. Instead, the message that got posted had my app's profile pic.

Any idea what I should be doing differently to be able to choose a custom avatar or emoji to display as my bot's profile pic for each message?

var slackMessage = new MySlackMessage()
{
    //As_User = false,
    Username = "My Custom Name",
    Text = "This text needs to have a google logo!",
    Icon_Url = "https://fulltimeblog.com/wp-content/uploads/2019/05/1024px-Google__G__Logo-1.png",
    //Icon_Emoji = ":heart:",
    Channel = "test"
};

using (HttpClient client = new HttpClient())
{
    var requestMessage = new HttpRequestMessage(HttpMethod.Post, "https://slack.com/api/chat.postMessage");
    requestMessage.Content = JsonContent.Create<MySlackMessage>(slackMessage);
    requestMessage.Headers.Add("Authorization", $"Bearer {token}");

    var response = client.Send(requestMessage);

    var result = response.Content.ReadAsStream();
    using (StreamReader sr = new StreamReader(result))
    {
        Console.WriteLine(sr.ReadToEnd());
    }
}

Here's the model I'm sending through by the way.

public class MySlackMessage
{
    // public bool As_User { get; set; }
    public string Text { get; set; }
    public string Username { get; set; }
    public string Icon_Url { get; set; }
    // public string Icon_Emoji { get; set; }
    public string Channel { get; set; }
}

Any ideas how I can set my bots profile pic dynamically when I create the message?


问:
Voila not displaying widgets due to tornado authorization error
I am trying to run this https://github.com/facebookresearch/aepsych/tree/main/visualizer visualization dashboard and I am able to run it with the jupyter notebook. I am running into an issue when I try to run it with the voila  command.

Ex:

```<code>voila visualizer/AEPsych_Visualizer_Dash_Beta.ipynb
</code>```

I have been able to run dashboards with voila in the past but for some reason am getting the following error when trying to launch any dashboard.

```<code>[Voila] WARNING | No handler found for comm target 'comm'
[Voila] WARNING | No handler found for comm target 'comm'
[Voila] WARNING | No handler found for comm target 'comm'
[Voila] WARNING | No handler found for comm target 'comm'
[Voila] WARNING | No handler found for comm target 'comm'
403 GET /voila/files/favicon.ico (::1): File not whitelisted
403 GET /voila/files/favicon.ico (::1) 0.85ms
/Users/ecortez/.pyenv/versions/3.9.4/lib/python3.9/site-packages/jupyter_server/base/handlers.py:197: UserWarning: The Tornado web application does not have an 'authorizer' defined in its settings. In future releases of jupyter_server, this will be a required key for all subclasses of `JupyterHandler`. For an example, see the jupyter_server source code for how to add an authorizer to the tornado settings: https://github.com/jupyter-server/jupyter_server/blob/653740cbad7ce0c8a8752ce83e4d3c2c754b13cb/jupyter_server/serverapp.py#L234-L256
  warnings.warn(
</code>```

I tried to create a new jupyter notebook that included just one widget and I am still running into the same problem "No handler found for comm target 'comm'".

```<code>import ipywidgets as widgets

w = widgets.Label(value = 'Test')

display(w)
</code>```

Does anyone know how to modify the authorizer settings in tornado?

Body:
I am trying to run this https://github.com/facebookresearch/aepsych/tree/main/visualizer visualization dashboard and I am able to run it with the jupyter notebook. I am running into an issue when I try to run it with the voila  command.

Ex:

voila visualizer/AEPsych_Visualizer_Dash_Beta.ipynb

I have been able to run dashboards with voila in the past but for some reason am getting the following error when trying to launch any dashboard.

[Voila] WARNING | No handler found for comm target 'comm'
[Voila] WARNING | No handler found for comm target 'comm'
[Voila] WARNING | No handler found for comm target 'comm'
[Voila] WARNING | No handler found for comm target 'comm'
[Voila] WARNING | No handler found for comm target 'comm'
403 GET /voila/files/favicon.ico (::1): File not whitelisted
403 GET /voila/files/favicon.ico (::1) 0.85ms
/Users/ecortez/.pyenv/versions/3.9.4/lib/python3.9/site-packages/jupyter_server/base/handlers.py:197: UserWarning: The Tornado web application does not have an 'authorizer' defined in its settings. In future releases of jupyter_server, this will be a required key for all subclasses of `JupyterHandler`. For an example, see the jupyter_server source code for how to add an authorizer to the tornado settings: https://github.com/jupyter-server/jupyter_server/blob/653740cbad7ce0c8a8752ce83e4d3c2c754b13cb/jupyter_server/serverapp.py#L234-L256
  warnings.warn(

I tried to create a new jupyter notebook that included just one widget and I am still running into the same problem "No handler found for comm target 'comm'".

import ipywidgets as widgets

w = widgets.Label(value = 'Test')

display(w)

Does anyone know how to modify the authorizer settings in tornado?


问:
Python newbie - trying to re-write this script to produce a dataframe not export to csv
I am convinced this is a really simple thing to achieve but I have limited python knowledge and struggling. I'm looking to adjust the script below so that rather than exporting to a local csv, I can use the same function and loop to produce a dataframe - for each vulnerability, I need the attributes defined in the function. The end goal being I can then use the df to export elsewhere. I'd really appreciate it if anyone could help me out with this.

`

```<code>import json, logging, time
from csv import DictWriter
from tenable.io import TenableIO

logging.basicConfig(level=logging.DEBUG)
tio = TenableIO(retries=3)

def transform_vuln(vuln, delim='|'):
    '''
    Transforms a single vulnerability item into the expected format.
    '''
    plugin = vuln.get('plugin', dict())
    asset = vuln.get('asset', dict())
    port = vuln.get('port', dict())
    return {
        # Asset Attributes
        'AgentUUID': asset.get('agent_uuid'),
        'AssetUUID': asset.get('uuid'),
        'NetBIOS': asset.get('netbios_name'),
        'FQDN': asset.get('fqdn'),
        'MAC': asset.get('mac_address'),
        'IPv4': asset.get('ipv4'),
        'HostName': asset.get('hostname'),
        'OS': delim.join(asset.get('operating_system', list())).replace('\\r', ''),

        # Plugin Attributes
        'CVE': delim.join(plugin.get('cve', list())),
        'CVSSv2BaseScore': plugin.get('cvss_base_score', 0),
        'CVSSv2TemporalScore': plugin.get('cvss_temporal_score', 0),
        'CVSSv3BaseScore': plugin.get('cvss3_base_score', 0),
        'CVSSv3TemporalScore': plugin.get('cvss3_temporal_score', 0),
        'Description': plugin.get('description', ''),
        'ExploitAvailable': plugin.get('exploit_available', 'false'),
        'ExploitMaturity': plugin.get('vpr', dict()).get('drivers', dict()).get(
            'exploit_code_maturity', '').replace('_', ' '),
        'MSBulletin': delim.join(plugin.get('ms_bulletin', list())),
        'PatchAvailable': plugin.get('has_patch'),
        'PluginFamily': plugin.get('family'),
        'PluginID': plugin.get('id'),
        'PluginName': plugin.get('name'),
        'Severity': plugin.get('risk_factor'),
        'SeeAlso': delim.join(plugin.get('see_also', list())),
        'Solution': plugin.get('solution'),
        'Synaopsis': plugin.get('synopsis'),
        'VulnerabilityPriorityRating': plugin.get('vpr', dict()).get('score', 0),

        # Vuln Instance Attributes
        'FirstSeen': vuln.get('first_found'),
        'LastSeen': vuln.get('last_found'),
        'PluginOutput': vuln.get('output'),
        'State': vuln.get('state'),

        # Port Attributes
        'Port': port.get('port', 0),
        'Protocol': port.get('protocol'),
        'Service': port.get('service'),
    }

def write_to_csv(filename):

    fields = sorted(transform_vuln(dict()).keys())
    counter = 0

    with open(filename, 'w') as reportfile:
        writer = DictWriter(reportfile, fields)
        writer.writeheader()
        for vuln in tio.exports.vulns(num_assets=500,
          severity=['Critical', 'High', 'Medium', 'Low']):
            writer.writerow(transform_vuln(vuln))
            counter += 1
    return counter

if __name__ == '__main__':
    start_time = time.time()
    rows = write_to_csv('vulnerabilities.csv')
    elapsed = time.gmtime(time.time() - start_time)
    print('\n'.join([
        'Runtime : {}'.format(time.strftime("%H:%M:%S", elapsed)),
        'Entries : {}'.format(rows)
    ]))
</code>```

`

I've tried using the loop and fields/dictionary - I can retrieve the column headings from this and one row of data, however it is the loop through vulnerabilities that I can't solve.

Body:
I am convinced this is a really simple thing to achieve but I have limited python knowledge and struggling. I'm looking to adjust the script below so that rather than exporting to a local csv, I can use the same function and loop to produce a dataframe - for each vulnerability, I need the attributes defined in the function. The end goal being I can then use the df to export elsewhere. I'd really appreciate it if anyone could help me out with this.

`

import json, logging, time
from csv import DictWriter
from tenable.io import TenableIO

logging.basicConfig(level=logging.DEBUG)
tio = TenableIO(retries=3)

def transform_vuln(vuln, delim='|'):
    '''
    Transforms a single vulnerability item into the expected format.
    '''
    plugin = vuln.get('plugin', dict())
    asset = vuln.get('asset', dict())
    port = vuln.get('port', dict())
    return {
        # Asset Attributes
        'AgentUUID': asset.get('agent_uuid'),
        'AssetUUID': asset.get('uuid'),
        'NetBIOS': asset.get('netbios_name'),
        'FQDN': asset.get('fqdn'),
        'MAC': asset.get('mac_address'),
        'IPv4': asset.get('ipv4'),
        'HostName': asset.get('hostname'),
        'OS': delim.join(asset.get('operating_system', list())).replace('\\r', ''),

        # Plugin Attributes
        'CVE': delim.join(plugin.get('cve', list())),
        'CVSSv2BaseScore': plugin.get('cvss_base_score', 0),
        'CVSSv2TemporalScore': plugin.get('cvss_temporal_score', 0),
        'CVSSv3BaseScore': plugin.get('cvss3_base_score', 0),
        'CVSSv3TemporalScore': plugin.get('cvss3_temporal_score', 0),
        'Description': plugin.get('description', ''),
        'ExploitAvailable': plugin.get('exploit_available', 'false'),
        'ExploitMaturity': plugin.get('vpr', dict()).get('drivers', dict()).get(
            'exploit_code_maturity', '').replace('_', ' '),
        'MSBulletin': delim.join(plugin.get('ms_bulletin', list())),
        'PatchAvailable': plugin.get('has_patch'),
        'PluginFamily': plugin.get('family'),
        'PluginID': plugin.get('id'),
        'PluginName': plugin.get('name'),
        'Severity': plugin.get('risk_factor'),
        'SeeAlso': delim.join(plugin.get('see_also', list())),
        'Solution': plugin.get('solution'),
        'Synaopsis': plugin.get('synopsis'),
        'VulnerabilityPriorityRating': plugin.get('vpr', dict()).get('score', 0),

        # Vuln Instance Attributes
        'FirstSeen': vuln.get('first_found'),
        'LastSeen': vuln.get('last_found'),
        'PluginOutput': vuln.get('output'),
        'State': vuln.get('state'),

        # Port Attributes
        'Port': port.get('port', 0),
        'Protocol': port.get('protocol'),
        'Service': port.get('service'),
    }

def write_to_csv(filename):

    fields = sorted(transform_vuln(dict()).keys())
    counter = 0

    with open(filename, 'w') as reportfile:
        writer = DictWriter(reportfile, fields)
        writer.writeheader()
        for vuln in tio.exports.vulns(num_assets=500,
          severity=['Critical', 'High', 'Medium', 'Low']):
            writer.writerow(transform_vuln(vuln))
            counter += 1
    return counter

if __name__ == '__main__':
    start_time = time.time()
    rows = write_to_csv('vulnerabilities.csv')
    elapsed = time.gmtime(time.time() - start_time)
    print('\n'.join([
        'Runtime : {}'.format(time.strftime("%H:%M:%S", elapsed)),
        'Entries : {}'.format(rows)
    ]))

`

I've tried using the loop and fields/dictionary - I can retrieve the column headings from this and one row of data, however it is the loop through vulnerabilities that I can't solve.


问:
Why error: no memory region specified for loadable section `.bss'?
I am trying to build an application manually using arm-none-eabi-gcc. The build goes fine but I get the following error during link time:

```<code>error: no memory region specified for loadable section `.bss'
</code>```

No other errors nor warnings. Just the build's output and this error,
I ended up trying back to the most basic type of linker script file that still allows me to build my app. This is the simplest/simplified linker script I can use and stil leads to the above error message:

```<code>MEMORY
{
    foo                   : ORIGIN = 0x50000000, LENGTH = 0xF0000000
}

SECTIONS
{
    .sram :
    {
        __sram_bss_start = .;
        *(.bss)
        *(.bss*)
        *(.text)
        __sram_bss_end = .;
    } > foo

}

</code>```

That's the linker file. Nothing more, nothing less.

As you can see the .bss segment is clearly defined so it is not clear to me why the linker is complaining.

This is how I am building and linking:

```<code>...
SOURCES := source1.c
SOURCES += source2.c
...

OBJECTS := $(SOURCES:$(MYSRCDIR)/%.c=$(MYOBJDIR)/%.o)

LD_FLAGS := -nostartfiles
LD_FLAGS += -T linkerScript.ld
LD_FLAGS += --entry=Reset_Handler
LD_FLAGS += -Wl,-Map,"memoryMap.map"
LD_FLAGS += -mcpu=cortex-m7
LD_FLAGS += -mthumb
LD_FLAGS += -mlittle-endian
LD_FLAGS += -mfloat-abi=hard
LD_FLAGS += -mfpu=fpv5-sp-d16
LD_FLAGS += -specs=nano.specs
LD_FLAGS += -specs=nosys.specs
LD_FLAGS += -lc
LD_FLAGS += -lm
LD_FLAGS += -lgcc
LD_FLAGS += --sysroot="/usr/lib/arm-none-eabi/newlib"
#LD_FLAGS += --verbose

all: $(BIN)

$(BIN): $(OBJECTS)
    $(CC) -o $@ $^ $(LD_FLAGS)

$(OBJDIR)/%.o : $(SRCDIR)/%.c
        @mkdir -p $(@D)
    $(CC) $(INC) $(CFLAGS) -o $@ -c $< $(DEFS)

```
```
<p>Compiler & linker version:</p>
```$ arm-none-eabi-gcc -v
...
gcc version 9.2.1 20191025
$ arm-none-eabi-ld -v
GNU ld (2.34-4ubuntu1+13ubuntu1) 2.34

```
<p>Did I misunderstand something here?</p>
<p>I expected the application to compile and link fine. I tried going through gnu's documentation to understand what I misunderstood. But no success so far.</p>
<p><strong>UPDATE:</strong></p>
<p>This linker file gets passed the aforementionned issue:</p>
```MEMORY
{
    foo                   : ORIGIN = 0x50000000, LENGTH = 0xF0000000
}

SECTIONS
{
    /* Works fine */
    .sram : { *(.text) } > foo
    .bss : { *(.bss) } > foo

    /* Does not work */
    /*
    .text : { *(.text) } > foo
    .sram : { *(.bss) } > foo
    */
}
```

So I presume it maybe somehow has issues with the sectionname .sram? Based on the information I could find online any sectionname can be given and this name is not dependent on any other definition/declaration/... elsewhere in the project

Body:
I am trying to build an application manually using arm-none-eabi-gcc. The build goes fine but I get the following error during link time:

error: no memory region specified for loadable section `.bss'

No other errors nor warnings. Just the build's output and this error,
I ended up trying back to the most basic type of linker script file that still allows me to build my app. This is the simplest/simplified linker script I can use and stil leads to the above error message:

MEMORY
{
    foo                   : ORIGIN = 0x50000000, LENGTH = 0xF0000000
}

SECTIONS
{
    .sram :
    {
        __sram_bss_start = .;
        *(.bss)
        *(.bss*)
        *(.text)
        __sram_bss_end = .;
    } > foo

}

That's the linker file. Nothing more, nothing less.

As you can see the .bss segment is clearly defined so it is not clear to me why the linker is complaining.

This is how I am building and linking:

...
SOURCES := source1.c
SOURCES += source2.c
...

OBJECTS := $(SOURCES:$(MYSRCDIR)/%.c=$(MYOBJDIR)/%.o)

LD_FLAGS := -nostartfiles
LD_FLAGS += -T linkerScript.ld
LD_FLAGS += --entry=Reset_Handler
LD_FLAGS += -Wl,-Map,"memoryMap.map"
LD_FLAGS += -mcpu=cortex-m7
LD_FLAGS += -mthumb
LD_FLAGS += -mlittle-endian
LD_FLAGS += -mfloat-abi=hard
LD_FLAGS += -mfpu=fpv5-sp-d16
LD_FLAGS += -specs=nano.specs
LD_FLAGS += -specs=nosys.specs
LD_FLAGS += -lc
LD_FLAGS += -lm
LD_FLAGS += -lgcc
LD_FLAGS += --sysroot="/usr/lib/arm-none-eabi/newlib"
#LD_FLAGS += --verbose

all: $(BIN)

$(BIN): $(OBJECTS)
    $(CC) -o $@ $^ $(LD_FLAGS)

$(OBJDIR)/%.o : $(SRCDIR)/%.c
        @mkdir -p $(@D)
    $(CC) $(INC) $(CFLAGS) -o $@ -c $< $(DEFS)

```

Compiler & linker version:

$ arm-none-eabi-gcc -v
...
gcc version 9.2.1 20191025
$ arm-none-eabi-ld -v
GNU ld (2.34-4ubuntu1+13ubuntu1) 2.34

Did I misunderstand something here?

I expected the application to compile and link fine. I tried going through gnu's documentation to understand what I misunderstood. But no success so far.

UPDATE:

This linker file gets passed the aforementionned issue:

MEMORY
{
    foo                   : ORIGIN = 0x50000000, LENGTH = 0xF0000000
}

SECTIONS
{
    /* Works fine */
    .sram : { *(.text) } > foo
    .bss : { *(.bss) } > foo

    /* Does not work */
    /*
    .text : { *(.text) } > foo
    .sram : { *(.bss) } > foo
    */
}

So I presume it maybe somehow has issues with the sectionname .sram? Based on the information I could find online any sectionname can be given and this name is not dependent on any other definition/declaration/... elsewhere in the project


问:
Rails : How to add user inputed value to button_to
I'm currently using Stripe Checkout and I want to add the quantity to my "Pay now" button.
I'm currently doing this

```<code><%= button_to "Pay Now", checkout_create_path, params: {
        :article_id => @article.id}, remote: true %>
</code>```

How can I add a field to my params of the button, filled by the user and add it to the params: field of my button ?

Like this it doesn't work :

```<code>    <%= number_field :quantity, :class => "form-control" %>
</code>```

Body:
I'm currently using Stripe Checkout and I want to add the quantity to my "Pay now" button.
I'm currently doing this

<%= button_to "Pay Now", checkout_create_path, params: {
        :article_id => @article.id}, remote: true %>

How can I add a field to my params of the button, filled by the user and add it to the params: field of my button ?

Like this it doesn't work :

    <%= number_field :quantity, :class => "form-control" %>


问:
Swift: OTA update default values without exposing the full list?
I regularly update some values in my app via a configuration JSON that I host on my server.

I have a singleton struct with default values, fetch the json and update the values in the singleton's struct. So far so good.

Now I'd prefer to not have all possible keys online if they are unused; I'd rather only have e.g. 2 or 3 keys in my JSON that need updating and the rest of the keys can remain the same as they are in the app binary.

The answers in With JSONDecoder in Swift 4, can missing keys use a default value instead of having to be optional properties? tackle this at wide variety however every single one of these solutions comes with a lot of code duplication (or at least having to mention each variable 2 to 4 times for the default values to apply in case of missing JSON keys).

Maybe there is a better solution for this, either via JSON, or via anything else. I'd prefer not to use services like Firebase Remote Config for things I can probably write by myself much more lighter too.

Somewhat of a solution to the "skip missing keys" problem is to simply use optionals however then I have the burden of guarding against nil everywhere in my code. I could probably also simply force-unwrap these everywhere since I know they exist in any case but this is quite dangerous for example in the case of me introducing a new key and forgetting to also provide a default value.

I've also thought about using protobuf for this since the pure data is way less "readable" in regards to exposing all possible keys however that seems too much of a hassle to use.

Is there any other approach I could take to tackle this? My current code is the same setup as the asker in With JSONDecoder in Swift 4, can missing keys use a default value instead of having to be optional properties? uses


问:
How one achieve a random long names in
 class properties
Recently I inspect a Facebook page and saw that all div tags has a strange class names. I guess this is used to prevent web scrapping from bots, but i can be mistaken. How this can be done and what is the purpose of it?

The html looks like this:

```

Title: How one achieve a random long names in <div> class properties


问:
Normalizing a table to handle row linking
I have a table that stores questions for some exam with the following structure:

ID: ID of the question. ]

Number: Question number in the exam.

Max: Maximum points for the question a student can get.

Text: The question description.

isSubQ: Is it a Sub Question? Boolean value.

part(Optional): What part of the question if it is a sub-question.

exam: ID of the exam(ForiegnKey).

I feel this structure to store sub-parts of the parent question is redundant and a much better relational schema exists. What is the best way to store sub-questions in other words, what is the best way to link two question rows(one as the parent and one as the sub-part)?

To give more clarity, here is an example. Let's say question 3 on the exam has parts a,b, and c. Part a has a different text, and points than other parts(b and c) but is still related to the parent question which is 3.


问:
Node cloud storage bucket how to rename image file and also get the image file buffer
I'm confused on two things. I need to do these 2, but am not sure how:

Get the buffer of a PRIVATE image in cloud firestore from node

change the name of an imagefile thats in storage.(Either by setting the name as it is being uploaded, or changed afterward, both work).

Here is my current code that logs some giant thing that does indeed contain the file, but I can't find how to get the image data from it besides just the name of it/oth irrelivant stuff.

```<code>var theFile = bucket.file('Walks For Lives.png');
       console.log(theFile)
</code>```

Ideally, to do both of these things, I seek some way to do this:

```<code>var theFile = bucket.file('Walks For Lives.png');
var the imageBuffer = theFile.buffer;

theFile.name.set("newName");
</code>```

Body:
I'm confused on two things. I need to do these 2, but am not sure how:

Get the buffer of a PRIVATE image in cloud firestore from node

change the name of an imagefile thats in storage.(Either by setting the name as it is being uploaded, or changed afterward, both work).

Here is my current code that logs some giant thing that does indeed contain the file, but I can't find how to get the image data from it besides just the name of it/oth irrelivant stuff.

var theFile = bucket.file('Walks For Lives.png');
       console.log(theFile)

Ideally, to do both of these things, I seek some way to do this:

var theFile = bucket.file('Walks For Lives.png');
var the imageBuffer = theFile.buffer;

theFile.name.set("newName");


问:
Using CustomJS in Make / Instomat
I'm experimenting with the CustomJS module inside of Make (was integromat). It appears to be quite counterintuitive.

If I set the input to look like this:

```<code>input = {"json": {"items": [{"item1":"fdafd","SKU":"SKU1"},{"item2":"fdafd","SKU":"SKU3"}], "products" :["SKU1", "SKU2"]}
</code>```

The following works fine:

```<code>function fudge(inp) { return inp.products;}
fudge(input)
</code>```

I can see the output gets the 2 item array. But the following Fails:

```<code>function fudge(inp){ let ret = []; ret = inp.products; return ret;} fudge(input)
</code>```

Excuse the one liner. I was experimenting to see if line breaks affected it. What gives here? I'm a bit of a generalist, so I appreciate I may be missing some of the finer points.

Anyone know why this doesn't work? And extending this onward, the goal is actually to produce an output that grabs the SKU values from the items too. Some thing like:

```<code>for (let i=0; i < items.length; i++) {
    ret.push(items[i].SKU;
}
</code>```

But obviously, I can't run this, since I can't even run the simple first bit yet.

Title: Using CustomJS in Make / Instomat

Body:
I'm experimenting with the CustomJS module inside of Make (was integromat). It appears to be quite counterintuitive.

If I set the input to look like this:

input = {"json": {"items": [{"item1":"fdafd","SKU":"SKU1"},{"item2":"fdafd","SKU":"SKU3"}], "products" :["SKU1", "SKU2"]}

The following works fine:

function fudge(inp) { return inp.products;}
fudge(input)

I can see the output gets the 2 item array. But the following Fails:

function fudge(inp){ let ret = []; ret = inp.products; return ret;} fudge(input)

Excuse the one liner. I was experimenting to see if line breaks affected it. What gives here? I'm a bit of a generalist, so I appreciate I may be missing some of the finer points.

Anyone know why this doesn't work? And extending this onward, the goal is actually to produce an output that grabs the SKU values from the items too. Some thing like:

for (let i=0; i < items.length; i++) {
    ret.push(items[i].SKU;
}

But obviously, I can't run this, since I can't even run the simple first bit yet.