问:
SwiftUI decoding JSON from API
I know there are already some articles regarding this issue, but I could not find anything related to my JSON.

This is how my JSON likes like:

```<code>{
  "message": {
    "affenpinscher": [],
    "african": [],
    "airedale": [],
    "akita": [],
    "appenzeller": [],
    "australian": [
      "shepherd"
    ],
    "basenji": []
  },
  "status: "succes"
}
</code>```

So, if I understand it correctly it is dictionary because it starts with {, but what are the things inside the "message"?

This is my Dog.swift class where I am re-writing the JSON, but I am not sure if it is correct:

```<code>class Dog: Decodable, Identifiable {

    var message: Message?
    var status: String?
}

struct Message: Decodable {

    var affenpinscher: [String:[String]]?
    var african: [String]?
    var airedale: [String]?
    var akita: [String]?
    var appenzeller: [String]?
    var australian: [String]?
    var basenji: [String]?
}
</code>```

As you can see in the first value I was trying to play with data types, but no success.

I am decoding and parsing JSON here:

```<code>class ContentModel: ObservableObject {

    @Published var dogs = Message()

    init() {
        getDogs()
    }

    func getDogs(){

        // Create URL
        let urlString = Constants.apiUrl
        let url = URL(string: urlString)

        if let url = url {
            // Create URL request
            var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
            request.httpMethod = "GET"

            // Get URLSession
            let session = URLSession.shared

            // Create Data Task
            let dataTask = session.dataTask(with: request) { (data, response, error) in
                // Check that there is not an error
                if error == nil {

                    do {
                        // Parse JSON
                        let decoder = JSONDecoder()
                        let result = try decoder.decode(Dog.self, from: data!)
                        print(result)

                        // Assign result to the dogs property
                        DispatchQueue.main.async {
                            self.dogs = result.message!
                        }
                    } catch {
                        print(error)
                    }
                }
            }

            // Start the Data Task
            dataTask.resume()
        }
    }

}
</code>```

And here I would love to iterate through it eventually, which I also have no idea how to do it:

```<code>struct ContentView: View {

    @EnvironmentObject var model: ContentModel

    var body: some View {
        NavigationView {
            ScrollView {
                LazyVStack {
                    if model.dogs != nil {
//                        ForEach(Array(model.dogs.keys), id: \.self) { d in
//                            Text(d)
//                        }
                    }
                }
                .navigationTitle("All Dogs")
            }

        }
    }
}
</code>```

What can I try next to resolve this?

答:
First of all don't use classes for a JSON model and to conform to Identifiable you have to add an id property and CodingKeys if there is no key id in the JSON.

My suggestion is to map the unhandy [String: [String]] dictionary to an array of an extra struct

I renamed Dog as Response and named the extra struct Dog

```<code>struct Dog {
    let name : String
    let types : [String]
}

struct Response: Decodable, Identifiable {

    private enum CodingKeys: String, CodingKey { case message, status }
    let id = UUID()

    let dogs: [Dog]
    let status: String

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        status = try container.decode(String.self, forKey: .status)
        let message = try container.decode([String:[String]].self, forKey: .message)
        dogs = message.map(Dog.init).sorted{$0.name < $1.name}
    }
}
</code>```

In the model declare

```<code>@Published var dogs = [Dog]()
</code>```

and decode

```<code>let result = try decoder.decode(Response.self, from: data!)
print(result)

// Assign result to the dogs property
DispatchQueue.main.async {
    self.dogs = result.dogs
}
</code>```

The dogs array can be displayed seamlessly in a List

PS: Actually appenzeller is supposed to be

```<code>"appenzeller": ["sennenhund"],
</code>```

or correctly in English

```<code> "appenzell": ["mountain dog"],
</code>```

Title: SwiftUI decoding JSON from API

Body:
I know there are already some articles regarding this issue, but I could not find anything related to my JSON.

This is how my JSON likes like:

{
  "message": {
    "affenpinscher": [],
    "african": [],
    "airedale": [],
    "akita": [],
    "appenzeller": [],
    "australian": [
      "shepherd"
    ],
    "basenji": []
  },
  "status: "succes"
}

So, if I understand it correctly it is dictionary because it starts with {, but what are the things inside the "message"?

This is my Dog.swift class where I am re-writing the JSON, but I am not sure if it is correct:

class Dog: Decodable, Identifiable {

    var message: Message?
    var status: String?
}

struct Message: Decodable {

    var affenpinscher: [String:[String]]?
    var african: [String]?
    var airedale: [String]?
    var akita: [String]?
    var appenzeller: [String]?
    var australian: [String]?
    var basenji: [String]?
}

As you can see in the first value I was trying to play with data types, but no success.

I am decoding and parsing JSON here:

class ContentModel: ObservableObject {

    @Published var dogs = Message()

    init() {
        getDogs()
    }

    func getDogs(){

        // Create URL
        let urlString = Constants.apiUrl
        let url = URL(string: urlString)

        if let url = url {
            // Create URL request
            var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
            request.httpMethod = "GET"

            // Get URLSession
            let session = URLSession.shared

            // Create Data Task
            let dataTask = session.dataTask(with: request) { (data, response, error) in
                // Check that there is not an error
                if error == nil {

                    do {
                        // Parse JSON
                        let decoder = JSONDecoder()
                        let result = try decoder.decode(Dog.self, from: data!)
                        print(result)

                        // Assign result to the dogs property
                        DispatchQueue.main.async {
                            self.dogs = result.message!
                        }
                    } catch {
                        print(error)
                    }
                }
            }

            // Start the Data Task
            dataTask.resume()
        }
    }

}

And here I would love to iterate through it eventually, which I also have no idea how to do it:

struct ContentView: View {

    @EnvironmentObject var model: ContentModel

    var body: some View {
        NavigationView {
            ScrollView {
                LazyVStack {
                    if model.dogs != nil {
//                        ForEach(Array(model.dogs.keys), id: \.self) { d in
//                            Text(d)
//                        }
                    }
                }
                .navigationTitle("All Dogs")
            }

        }
    }
}

What can I try next to resolve this?

Body:
First of all don't use classes for a JSON model and to conform to Identifiable you have to add an id property and CodingKeys if there is no key id in the JSON.

My suggestion is to map the unhandy [String: [String]] dictionary to an array of an extra struct

I renamed Dog as Response and named the extra struct Dog

struct Dog {
    let name : String
    let types : [String]
}

struct Response: Decodable, Identifiable {

    private enum CodingKeys: String, CodingKey { case message, status }
    let id = UUID()

    let dogs: [Dog]
    let status: String

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        status = try container.decode(String.self, forKey: .status)
        let message = try container.decode([String:[String]].self, forKey: .message)
        dogs = message.map(Dog.init).sorted{$0.name < $1.name}
    }
}

In the model declare

@Published var dogs = [Dog]()

and decode

let result = try decoder.decode(Response.self, from: data!)
print(result)

// Assign result to the dogs property
DispatchQueue.main.async {
    self.dogs = result.dogs
}

The dogs array can be displayed seamlessly in a List

PS: Actually appenzeller is supposed to be

"appenzeller": ["sennenhund"],

or correctly in English

 "appenzell": ["mountain dog"],


来源: stackexchange

问:
Robust SVN export and copy script?
I'm looking for the best way to run a nightly script that exports a set of
files from a SVN Repository to a local directory. When the export finishes,
copy the contents of the local directory to several remote servers.

This will be a scheduled back job running on a Windows Server 2003 machine.
Remote servers are all on the network, so there's no need for FTP, etc.

Pseudocode would run like this

```<code>1. svn export repo localdir (plus some switches)
2. ... wait to make sure export is finished ...
3. robocopy localdir \\remotedir1
4. robocopy localdir \\remotedir2, etc
</code>```

I'm very new to writing batch jobs, but I'd like this to be as robust as possible:
- copy doesn't start until export is done
- if copy to remotedir1 fails, script still proceeds copying to remotedir2,3,etc
- is it possible to log problems if there is any trouble at one of the steps?

Any input on what the batch job would look like would be much appreciated!

答:
Ant (Java required) might be a good candidate for this sort of work.

Ant is a build tool with strong support for the sort of reliance-chains that you describe. The syntax is fairly straightforward as well, since it is just XML.

OwnerDisplayName: AR

ContentLicense: CC BY-SA 2.5

Title: Robust SVN export and copy script?

Body:
I'm looking for the best way to run a nightly script that exports a set of
files from a SVN Repository to a local directory. When the export finishes,
copy the contents of the local directory to several remote servers.

This will be a scheduled back job running on a Windows Server 2003 machine.
Remote servers are all on the network, so there's no need for FTP, etc.

Pseudocode would run like this

1. svn export repo localdir (plus some switches)
2. ... wait to make sure export is finished ...
3. robocopy localdir \\remotedir1
4. robocopy localdir \\remotedir2, etc

I'm very new to writing batch jobs, but I'd like this to be as robust as possible:
- copy doesn't start until export is done
- if copy to remotedir1 fails, script still proceeds copying to remotedir2,3,etc
- is it possible to log problems if there is any trouble at one of the steps?

Any input on what the batch job would look like would be much appreciated!

OwnerDisplayName: tehblanx


问:
Is class.getName() expensive?
In many classes of a project I am working on, I see private static final members named CLASS_NAME, which are defined like this:

```<code>public class MyClass {
  private static final String CLASS_NAME = MyClass.class.getName();
  //...
}
</code>```

What are the benefits, if any, of doing this to get the class name, rather than doing the MyClass.class.getName() call directly where the name is needed?

答:
It's not expensive. It seems to be a convention for logging purposes.

compare

```<code>logger.entering(CLASS_NAME, ... )
</code>```

to

```<code>logger.entering( MyClass.class.getName() ,... )
</code>```

besides that, logging code wouldn't break (logging wrong class) when copied to another source.

ContentLicense: CC BY-SA 3.0

Title: Is class.getName() expensive?

Body:
In many classes of a project I am working on, I see private static final members named CLASS_NAME, which are defined like this:

public class MyClass {
  private static final String CLASS_NAME = MyClass.class.getName();
  //...
}

What are the benefits, if any, of doing this to get the class name, rather than doing the MyClass.class.getName() call directly where the name is needed?

Body:
It's not expensive. It seems to be a convention for logging purposes.

compare

logger.entering(CLASS_NAME, ... )

to

logger.entering( MyClass.class.getName() ,... )

besides that, logging code wouldn't break (logging wrong class) when copied to another source.


问:
Why is my C# AWS Lambda not publishing my SNS message?
I am new to C# and I am trying to build a handler function with Lambda to push messages to an SNS topic, this is what I have:

using MessagePublisher;

using Amazon.Lambda.Core;
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace SNSMessagePublisher
{
    public class Function
    {
        public string PublishMessageHandler(NewMessage input, ILambdaContext context)
        {
            var client = new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.EUWest2);
            LambdaLogger.Log($"Calling function name: {context.FunctionName}\n");
            var publishRequest = new PublishRequest(
                "arn:aws:sns:eu-west-2:123...9:TopicABC",
                input.body);
            client.PublishAsync(publishRequest);
            return $"Message Published: {input.body}";
        }
    }
}
```
<pre class="lang-cs prettyprint-override"><code>namespace MessagePublisher {
    public class NewMessage {
        public string body { get; set; }
    }
}
</code>```

I then trigger a set payload of:

{
  "body": "test body"
}
```
<p>and in the CloudWatch logs, I get an output of:</p>
<pre class="lang-sh prettyprint-override"><code>Calling function name: messagePublisher
</code>```

And the Lambda console returns:

"Message Published: test body"
```

However, the topic never actually receives a message.

答:
client.PublishAsync(publishRequest); is asynchronous, will return a Task and as such, you need to wait on the task to finish executing using await.

Without calling await on the task, there is no guarantee that the client has published the message before the Lambda finishes executing.

The message is not being sent as the task for sending the message hasn't finished executing before the Lambda function has returned.

This should work:

public async Task<string> PublishMessageHandler(NewMessage input, ILambdaContext context)
{
    var client = new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.EUWest2);
    LambdaLogger.Log($"Calling function name: {context.FunctionName}\n");
    var publishRequest = new PublishRequest(
        "arn:aws:sns:eu-west-2:123...9:TopicABC",
        input.body);
    await client.PublishAsync(publishRequest);
    return $"Message Published: {input.body}";
}
```

As you're new to C#, I would recommend reading Microsoft's Asynchronous programming with async and await article.

ContentLicense: CC BY-SA 4.0

Body:
I am new to C# and I am trying to build a handler function with Lambda to push messages to an SNS topic, this is what I have:

using MessagePublisher;

using Amazon.Lambda.Core;
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace SNSMessagePublisher
{
    public class Function
    {
        public string PublishMessageHandler(NewMessage input, ILambdaContext context)
        {
            var client = new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.EUWest2);
            LambdaLogger.Log($"Calling function name: {context.FunctionName}\n");
            var publishRequest = new PublishRequest(
                "arn:aws:sns:eu-west-2:123...9:TopicABC",
                input.body);
            client.PublishAsync(publishRequest);
            return $"Message Published: {input.body}";
        }
    }
}

namespace MessagePublisher {
    public class NewMessage {
        public string body { get; set; }
    }
}

I then trigger a set payload of:

{
  "body": "test body"
}

and in the CloudWatch logs, I get an output of:

Calling function name: messagePublisher

And the Lambda console returns:

"Message Published: test body"

However, the topic never actually receives a message.

Body:
client.PublishAsync(publishRequest); is asynchronous, will return a Task and as such, you need to wait on the task to finish executing using await.

Without calling await on the task, there is no guarantee that the client has published the message before the Lambda finishes executing.

The message is not being sent as the task for sending the message hasn't finished executing before the Lambda function has returned.

This should work:

public async Task<string> PublishMessageHandler(NewMessage input, ILambdaContext context)
{
    var client = new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.EUWest2);
    LambdaLogger.Log($"Calling function name: {context.FunctionName}\n");
    var publishRequest = new PublishRequest(
        "arn:aws:sns:eu-west-2:123...9:TopicABC",
        input.body);
    await client.PublishAsync(publishRequest);
    return $"Message Published: {input.body}";
}

As you're new to C#, I would recommend reading Microsoft's Asynchronous programming with async and await article.


问:
Getting "SyntaxError: Unexpected token" in Observable
I was trying vega-lite-api on observablehq here.

This is my code:

Putting these two in different cells work:

```<code>obj = vl.markPoint()
  .data(df)
  .encode(vl.y().fieldN('city'));
</code>```

In next cell:

```<code>obj.render()
</code>```

If I put both in the same cell, it gives SyntaxError: Unexpected token:

```<code>obj2 = vl.markPoint()
  .data(df)
  .encode(vl.y().fieldN('city'));

obj2.render();
^
</code>```

Why is this so?

答:
for obj you have a definition before you use it...

```<code>obj = N {
  Symbol(data): Object {mark: h, data: Object, encoding: h}
  <prototype>: N {}
}
</code>```

I guess you forgot about it for obj2?

Body:
I was trying vega-lite-api on observablehq here.

This is my code:

Putting these two in different cells work:

obj = vl.markPoint()
  .data(df)
  .encode(vl.y().fieldN('city'));

In next cell:

obj.render()

If I put both in the same cell, it gives SyntaxError: Unexpected token:

obj2 = vl.markPoint()
  .data(df)
  .encode(vl.y().fieldN('city'));

obj2.render();
^

Why is this so?

Body:
for obj you have a definition before you use it...

obj = N {
  Symbol(data): Object {mark: h, data: Object, encoding: h}
  <prototype>: N {}
}

I guess you forgot about it for obj2?


问:
Dependency injection in custom filters
I'm new to angular and trying create a custom filter which requires a service. I followed the answer here https://stackoverflow.com/a/43506252/15817005. It solved my issue partially.

Registering filter

```<code>angular.module('filters',[]).filter('dataFormat',['studentService', dataFormatFilter])
</code>```

My Filter factory and filter function.

```<code>    export function dataFormatFilter(studentService){
console.log(studentService); // Having access here
return dataFormatFunction;
}

function dataFormatFunction(name){
// All the formatting logic

//Need properties from studentService in this function.
}
</code>```

I am able to access the properties from studentService in dataFormatFilter(factory function). Is there a way to get it in dataFormatFunction.

All the solutions i have seen use dataFormatFunction inside of factory itself dataFormatFilter. But i cannot follows this way.

Thanks!

答:
What it looks like you need to to is return an arrow function that will keep the closure of your filter function so you can use the dependencies without having to pass them around.
I wrote this plunkr to demonstrate.

The critical part being:

```<code>const dataFormatFilter = function (studentService) {
  return (name) => {
    return myReusableFunction(studentService, name);
  }
}

app.filter('dataFormat',['studentService', dataFormatFilter]);
</code>```

Note that the returned value for the function is an arrow function. This isn't the only way to achieve what you are attempting, but should be the simplest.

Title: Dependency injection in custom filters

Body:
I'm new to angular and trying create a custom filter which requires a service. I followed the answer here https://stackoverflow.com/a/43506252/15817005. It solved my issue partially.

Registering filter

angular.module('filters',[]).filter('dataFormat',['studentService', dataFormatFilter])

My Filter factory and filter function.

    export function dataFormatFilter(studentService){
console.log(studentService); // Having access here
return dataFormatFunction;
}

function dataFormatFunction(name){
// All the formatting logic

//Need properties from studentService in this function.
}

I am able to access the properties from studentService in dataFormatFilter(factory function). Is there a way to get it in dataFormatFunction.

All the solutions i have seen use dataFormatFunction inside of factory itself dataFormatFilter. But i cannot follows this way.

Thanks!

Body:
What it looks like you need to to is return an arrow function that will keep the closure of your filter function so you can use the dependencies without having to pass them around.
I wrote this plunkr to demonstrate.

The critical part being:

const dataFormatFilter = function (studentService) {
  return (name) => {
    return myReusableFunction(studentService, name);
  }
}

app.filter('dataFormat',['studentService', dataFormatFilter]);

Note that the returned value for the function is an arrow function. This isn't the only way to achieve what you are attempting, but should be the simplest.


问:
How to replace value in a dataframe and convert it to a list of dictionary in python pandas
I have a data frame that is created after a query is executed. Call it df1.

```<code> customerID flag
0        123   No
</code>```

Now, I have another list of dictionary like below:

```<code>list2 = [{"customerID": "123", "response": "yes", "flag": ""}]
</code>```

Now, I want to replace the value of the flag with the values of the flag from df1 for that specific customer. So, I converted this list to a data frame say df2 and tried doing it but it didn't give any errors but didn't give my expected output.

Attempt:

```<code>df2.loc[df2['customerID'].isin(df1.to_dict().keys()), 'flag'] = df2['customerID'].map(df1.to_dict())
</code>```

Expected output:

```<code>[{"customerID": "123", "response": "yes", "flag": "No"}]
</code>```

I am looking to replace it in df2 itself. Later on, I can do .to_dict(orient="records") to get the format I need.

答:
One liner solution.</p>
```<code>df2 = df2.drop('flag',axis=1).merge(right=df1,on='customerID')
</code>```

Body:
I have a data frame that is created after a query is executed. Call it df1.

 customerID flag
0        123   No

Now, I have another list of dictionary like below:

list2 = [{"customerID": "123", "response": "yes", "flag": ""}]

Now, I want to replace the value of the flag with the values of the flag from df1 for that specific customer. So, I converted this list to a data frame say df2 and tried doing it but it didn't give any errors but didn't give my expected output.

Attempt:

df2.loc[df2['customerID'].isin(df1.to_dict().keys()), 'flag'] = df2['customerID'].map(df1.to_dict())

Expected output:

[{"customerID": "123", "response": "yes", "flag": "No"}]

I am looking to replace it in df2 itself. Later on, I can do .to_dict(orient="records") to get the format I need.

Body:
One liner solution.

df2 = df2.drop('flag',axis=1).merge(right=df1,on='customerID')


问:
GZIP Android requesting XML
I have code that I would like to convert so that I am grabbing my xml from the server in GZIP format.  I am not sure how I would send my requests to see if encoding is accepted and what not.  Here is some code:

```<code>    public void parse(String locCode, int isMetric, String langId) throws IOException, ParserConfigurationException, SAXException {
    //set member variables
    this.locCode    = locCode;
    this.isMetric   = isMetric;
    this.langId     = langId;
    wdm.metric      = isMetric;

    try {
        mCounter++;
        //create input stream from url
        InputStream is = getInputStream(this.locCode, this.isMetric, this.langId);
        InputSource inputSource = new InputSource(is);

        inputSource.setEncoding(ENCODING_TYPE);

        //create sax parser and xml reader
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        mCounter = 0;
        //pass in instance of FeedParser
        xr.setContentHandler(new WeatherFeedParser());
        xr.parse(inputSource);
        is.close();
    } catch (SocketException e){
        if (mCounter < 3){
            parse(locCode, isMetric, langId);
        }
        else e.printStackTrace();
    } catch (UnknownHostException e){
        if (mCounter < 3){
            parse(locCode, isMetric, langId);
        }
        else e.printStackTrace();
    }

}

private static final InputStream getInputStream(String locCode, int isMetric, String langId) throws IOException {
    //build url
    String addr = FEED_URL + LOCATION + cleanupInput(locCode) + "&" + METRIC + isMetric + "&" + LANG_ID + langId;
    URL url = new URL(addr);

    //create connection
    mCon = url.openConnection();
    mCon.setConnectTimeout((int)ACCUWX.Time._15_SECONDS);
    mCon.setReadTimeout((int)ACCUWX.Time._15_SECONDS);
    mCon.connect();

    return mCon.getInputStream();
}
</code>```

I have read other posts and am not sure where I would implement suggestions with this coding:

```<code>HttpUriRequest request = new HttpGet(url);
request.addHeader("Accept-Encoding", "gzip");
// ...
httpClient.execute(request);
Check response for content encoding:
InputStream instream = response.getEntity().getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
    instream = new GZIPInputStream(instream);
}</code>```

答: Your second code listing would replace much of the body of your getInputStream() method in your first listing.

Title: GZIP Android requesting XML

Body:
I have code that I would like to convert so that I am grabbing my xml from the server in GZIP format.  I am not sure how I would send my requests to see if encoding is accepted and what not.  Here is some code:

    public void parse(String locCode, int isMetric, String langId) throws IOException, ParserConfigurationException, SAXException {
    //set member variables
    this.locCode    = locCode;
    this.isMetric   = isMetric;
    this.langId     = langId;
    wdm.metric      = isMetric;

    try {
        mCounter++;
        //create input stream from url
        InputStream is = getInputStream(this.locCode, this.isMetric, this.langId);
        InputSource inputSource = new InputSource(is);

        inputSource.setEncoding(ENCODING_TYPE);

        //create sax parser and xml reader
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        mCounter = 0;
        //pass in instance of FeedParser
        xr.setContentHandler(new WeatherFeedParser());
        xr.parse(inputSource);
        is.close();
    } catch (SocketException e){
        if (mCounter < 3){
            parse(locCode, isMetric, langId);
        }
        else e.printStackTrace();
    } catch (UnknownHostException e){
        if (mCounter < 3){
            parse(locCode, isMetric, langId);
        }
        else e.printStackTrace();
    }

}

private static final InputStream getInputStream(String locCode, int isMetric, String langId) throws IOException {
    //build url
    String addr = FEED_URL + LOCATION + cleanupInput(locCode) + "&" + METRIC + isMetric + "&" + LANG_ID + langId;
    URL url = new URL(addr);

    //create connection
    mCon = url.openConnection();
    mCon.setConnectTimeout((int)ACCUWX.Time._15_SECONDS);
    mCon.setReadTimeout((int)ACCUWX.Time._15_SECONDS);
    mCon.connect();

    return mCon.getInputStream();
}

I have read other posts and am not sure where I would implement suggestions with this coding:

HttpUriRequest request = new HttpGet(url);
request.addHeader("Accept-Encoding", "gzip");
// ...
httpClient.execute(request);
Check response for content encoding:
InputStream instream = response.getEntity().getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
    instream = new GZIPInputStream(instream);
}


问:
How to remove a text fragment from the file using bat/cmd
I have a html file and need to remove the text fragment between tags "t193270" and "t226481". It looks like:

```<code>    <a href="#" class="bt-home">В начало</a>
    </div><a name=183586> </a><div class="cont" id="193270">
    <h1 id="t193270" class="heading1">Управление программой</h1>
    ...
     ...
    <a href="#" class="bt-home">В начало</a>
    </div><a name=226360> </a><div class="cont" id="198854">
    <h1 id="t226481" class="heading1">Создание резервной копии и восстановление программы</h1>
</code>```

I use the following batch script:

```<code>@echo off
set "f=all-in-one.htm"
set "tag1=t193270"
set "tag2=t226481"
for /f "delims=[]" %%a in ('findstr/rn /c:"^%tag1%$" "%f%"') do set/a nd=%%a
for /f "delims=[]" %%a in ('findstr/rn /c:"^%tag2%$" "%f%"') do set/a kd=%%a
<"%f%" (for /f "tokens=2 delims=[]" %%a in ('"for /l %%a in (%nd%,1,%kd%) do @find /n /v ""|find "[%%a]""') do @echo:%%a)
pause>nul
</code>```

It returns however the same unchanged file. Would you please help me? Thanks in advance.

答:
So based on all my comments above about your code you could do something like this.

```<code>@echo off
set "f=all-in-one.htm"
set "tag1=t193270"
set "tag2=t226481"

for /f "tokens=1 delims=:" %%a in ('findstr /rnc:"\<%tag1%\>" "%f%"') do set "nd=%%a"
for /f "tokens=1 delims=:" %%a in ('findstr /rnc:"\<%tag2%\>" "%f%"') do set "kd=%%a"

FOR /F "tokens=1,* delims=[]" %%G IN ('find /N /V "" ^<"%f%"') DO (
    IF %%G LEQ %nd% echo %%H
    IF %%G GEQ %kd% echo %%H
)
</code>```

This will output the following based on the example input file you provded.

```<code><a href="#" class="bt-home">В начало</a>
</div><a name=183586> </a><div class="cont" id="193270">
<h1 id="t193270" class="heading1">Управление программой</h1>
<h1 id="t226481" class="heading1">Создание резервной копии и восстановление программы</h1>
</code>```

Body:
I have a html file and need to remove the text fragment between tags "t193270" and "t226481". It looks like:

    В начало

Управление программой

    ...
     ...
    В начало

Создание резервной копии и восстановление программы

I use the following batch script:

@echo off
set "f=all-in-one.htm"
set "tag1=t193270"
set "tag2=t226481"
for /f "delims=[]" %%a in ('findstr/rn /c:"^%tag1%$" "%f%"') do set/a nd=%%a
for /f "delims=[]" %%a in ('findstr/rn /c:"^%tag2%$" "%f%"') do set/a kd=%%a
<"%f%" (for /f "tokens=2 delims=[]" %%a in ('"for /l %%a in (%nd%,1,%kd%) do @find /n /v ""|find "[%%a]""') do @echo:%%a)
pause>nul

It returns however the same unchanged file. Would you please help me? Thanks in advance.

Body:
So based on all my comments above about your code you could do something like this.

@echo off
set "f=all-in-one.htm"
set "tag1=t193270"
set "tag2=t226481"

for /f "tokens=1 delims=:" %%a in ('findstr /rnc:"\<%tag1%\>" "%f%"') do set "nd=%%a"
for /f "tokens=1 delims=:" %%a in ('findstr /rnc:"\<%tag2%\>" "%f%"') do set "kd=%%a"

FOR /F "tokens=1,* delims=[]" %%G IN ('find /N /V "" ^<"%f%"') DO (
    IF %%G LEQ %nd% echo %%H
    IF %%G GEQ %kd% echo %%H
)

This will output the following based on the example input file you provded.

<a href="#" class="bt-home">В начало</a>
</div><a name=183586> </a><div class="cont" id="193270">
<h1 id="t193270" class="heading1">Управление программой</h1>
<h1 id="t226481" class="heading1">Создание резервной копии и восстановление программы</h1>


问:
How do I use CSS to properly hide a form select element, including the select arrow
I'm using display: none; in the style sheet to hide a number of form fields. When the user clicks the visible First Name or Last Name fields, the rest of the fields display using JavaScript getElementById to display block.

Everything works except the down arrow still displays from the select element when it should be hidden with everything else. I tried CSS:

```<code>select {
    appearance: none;
}
</code>```

but that did not work. Image below of the problem and link here to the test page: Form Test Page

答: There is a :before psedo-element inside the select parent div. This is the arrow and not the select.

Body:
I'm using display: none; in the style sheet to hide a number of form fields. When the user clicks the visible First Name or Last Name fields, the rest of the fields display using JavaScript getElementById to display block.

Everything works except the down arrow still displays from the select element when it should be hidden with everything else. I tried CSS:

select {
    appearance: none;
}

but that did not work. Image below of the problem and link here to the test page: Form Test Page


问:
How i can get router params in apollo ? [VUE3]
here is my component script on VueJS. I want to know how to get router params in my apollo component to search item whith these params. The idea is to replace 953 by the id of the page. If you have any questions, ask me ! I'm using createRouter, createWebHashHistory from vue-router and VueJS 4.

Thanks for help.

```<code><script>
import gql from "graphql-tag";
// import { useRouter } from "vue-router";
import TemplatePresentationPage from "./TemplatePresentationPage.vue";
export default {
    name: "PresentationPage",
    apollo: {
        entry: gql`
            query entry {
                entry(id: 953) {
                    id
                    title
                }
            }
        `,
    },
    components: { TemplatePresentationPage },
    setup() {
        return {};
    },
};
</script>
</code>```

答:
If your routes looked like this

```<code>const routes = [{ path: '/user/:id', component: User }]
</code>```

then to get that id param on your component you just do as below

```<code>const User = {
   // make sure to add a prop named exactly like the route param
   props: ['id'],
  template: '<div>User {{ $route.params.id }}</div>'
}
</code>```

and this works on your template as well

```<code><template>
   <div>User {{ $route.params.id }}</div>
</template>
</code>```

But as for your case, it seems like you want to use it on your setup() function.
The way you access it is as below

```<code>import { useRoute } from 'vue-router';

export default {
 setup(){
  const route = useRoute();
  //console.log(route.params.parameterName)
}
}
</code>```

Body:
If your routes looked like this

const routes = [{ path: '/user/:id', component: User }]

then to get that id param on your component you just do as below

const User = {
   // make sure to add a prop named exactly like the route param
   props: ['id'],
  template: '<div>User {{ $route.params.id }}</div>'
}

and this works on your template as well

<template>
   <div>User {{ $route.params.id }}</div>
</template>

But as for your case, it seems like you want to use it on your setup() function.
The way you access it is as below

import { useRoute } from 'vue-router';

export default {
 setup(){
  const route = useRoute();
  //console.log(route.params.parameterName)
}
}


问:
how to replicate pinterest.com's absolute div stacking layout
I am looking to replicate Pinterest.com's div layout, specifically how the number of columns adjusts to fit more/less on browser resize and the vertical stacking is not dependent on adjacent column heights. The source code shows that each div is position absolute. A co-founder has answered a Quora post stating it is done with custom jQuery and CSS. I would like the results sorted left to right.  Any direction you could provide to make it myself would be greatly appreciated.</p>

答: They split entities by columns with ids (bad solution... better use class names) and then calculate positions by column groups</p>


问:
Is there a way to open multiple tabs simultaneously on Playwright or Puppeteer to complete the same tasks?
I just started coding, and I was wondering if there was a way to open multiple tabs concurrently with one another. Currently, my code goes something like this:

```<code>const puppeteer = require("puppeteer");

const rand_url = "https://www.google.com";

async function initBrowser() {
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();
  await page.goto(rand_url);
  await page.setViewport({
    width: 1200,
    height: 800,
  });

  return page;
}

async function login(page) {
  await page.goto("https://www.google.com");
  await page.waitFor(100);
  await page.type("input[id ='user_login'", "xxx");
  await page.waitFor(100);
  await page.type("input[id ='user_password'", "xxx");
}
</code>```

this is not my exact code, replaced with different aliases, but you get the idea. I was wondering if there was anyone out there that knows the code that allows this same exact browser to be opened on multiple instances, replacing the respective login info only. Of course, it would be great to prevent my IP from getting banned too, so if there was a way to apply proxies to each respective "browser"/ instance, that would be perfect.

Lastly, I would like to know whether or not playwright or puppeteer is superior in the way they can handle these multiple instances. I don't even know if this is a possibility, but please enlighten me. I want to learn more.

答:
There are profiling and proxy options; you could combine them to achieve your goal:

Profile, https://playwright.dev/docs/api/class-browsertype#browser-type-launch-persistent-context

import { chromium } from 'playwright'
const userDataDir = /tmp/ + process.argv[2]
const browserContext = await chromium.launchPersistentContext(userDataDir)
// ...
```
<blockquote>
<p>Proxy, https://playwright.dev/docs/api/class-browsertype#browser-type-launch</p>
</blockquote>
<pre class="lang-js prettyprint-override"><code>import { chromium } from 'playwright'
const proxy = { /* secret */ }
const browser = await chromium.launch({
  proxy: { server: 'pre-context' }
})
const browserContext = await browser.newContext({
  proxy: {
    server: `http://${proxy.ip}:${proxy.port}`,
    username: proxy.username,
    password: proxy.password,
  }
})
// ...
</code>```

Body:
I just started coding, and I was wondering if there was a way to open multiple tabs concurrently with one another. Currently, my code goes something like this:

const puppeteer = require("puppeteer");

const rand_url = "https://www.google.com";

async function initBrowser() {
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();
  await page.goto(rand_url);
  await page.setViewport({
    width: 1200,
    height: 800,
  });

  return page;
}

async function login(page) {
  await page.goto("https://www.google.com");
  await page.waitFor(100);
  await page.type("input[id ='user_login'", "xxx");
  await page.waitFor(100);
  await page.type("input[id ='user_password'", "xxx");
}

this is not my exact code, replaced with different aliases, but you get the idea. I was wondering if there was anyone out there that knows the code that allows this same exact browser to be opened on multiple instances, replacing the respective login info only. Of course, it would be great to prevent my IP from getting banned too, so if there was a way to apply proxies to each respective "browser"/ instance, that would be perfect.

Lastly, I would like to know whether or not playwright or puppeteer is superior in the way they can handle these multiple instances. I don't even know if this is a possibility, but please enlighten me. I want to learn more.

Body:
There are profiling and proxy options; you could combine them to achieve your goal:

Profile, https://playwright.dev/docs/api/class-browsertype#browser-type-launch-persistent-context

import { chromium } from 'playwright'
const userDataDir = /tmp/ + process.argv[2]
const browserContext = await chromium.launchPersistentContext(userDataDir)
// ...

Proxy, https://playwright.dev/docs/api/class-browsertype#browser-type-launch

import { chromium } from 'playwright'
const proxy = { /* secret */ }
const browser = await chromium.launch({
  proxy: { server: 'pre-context' }
})
const browserContext = await browser.newContext({
  proxy: {
    server: `http://${proxy.ip}:${proxy.port}`,
    username: proxy.username,
    password: proxy.password,
  }
})
// ...


问:
Is there a way to view the 2 connected DAGs in one graph view?
I have 2 DAGS:

example_call_other_dag which looks:

The second task (TriggerDagRunOperator) call the second DAG:

example_xcom which looks:

Is there a way to view the 2 connected DAGs in one graph view ?

I wan't see something like:

Is it possible ? How can I do it ?

答:
Yes. Airflow has Dag Dependencies view

You can access it via Browse -> Dag Dependencies:

The view exist for Airflow>=2.1.0


问:
How to display even Fibonacci numbers by specifying their number?
I have a function that checks Fibonacci numbers for even.

```<code>def fibonacci(num=4):
    fib1 = fib2 = 1
    print(0, end=' ')
    for i in range(1, num):
        fib1, fib2 = fib2, fib1 + fib2
        if (fib2 % 2) == 0:
            print(fib2, end=' ')

fibonacci()
</code>```

I need it to output a specified number of even numbers

Example input: 4

Example output: 0 2 8 34

答:
You could just go over the even ones directly:

```<code>def fibonacci(num=4):
    fib1, fib2 = 1, 0
    for _ in range(num):
        print(fib2, end=' ')
        fib1, fib2 = fib1 + 2*fib2, 2*fib1 + 3*fib2
</code>```

Consider two adjacent Fibonacci numbers a and b (initially 1 and 0) and what happens when you shift the window:

```<code>   a     b    # odd even
   b   a+b    # even odd
 a+b  a+2b    # odd odd
a+2b 2a+3b    # odd even
</code>```

So every third Fibonacci number is even and that last line also tells you how to shift by three steps directly.

Body:
I have a function that checks Fibonacci numbers for even.

def fibonacci(num=4):
    fib1 = fib2 = 1
    print(0, end=' ')
    for i in range(1, num):
        fib1, fib2 = fib2, fib1 + fib2
        if (fib2 % 2) == 0:
            print(fib2, end=' ')

fibonacci()

I need it to output a specified number of even numbers

Example input: 4

Example output: 0 2 8 34

Body:
You could just go over the even ones directly:

def fibonacci(num=4):
    fib1, fib2 = 1, 0
    for _ in range(num):
        print(fib2, end=' ')
        fib1, fib2 = fib1 + 2*fib2, 2*fib1 + 3*fib2

Consider two adjacent Fibonacci numbers a and b (initially 1 and 0) and what happens when you shift the window:

   a     b    # odd even
   b   a+b    # even odd
 a+b  a+2b    # odd odd
a+2b 2a+3b    # odd even

So every third Fibonacci number is even and that last line also tells you how to shift by three steps directly.


问:
VueJS 3 create/pass hyperscript to template at runtime?
I wanted to try something for performance/convenience purposes, I understand the gains will be minimal but understanding how/if/why this works would also just be helpful to learn.

I have a some custom data types (defined as classes) that are used to identify certain properties throughout my application. I want to use a static function on the type to define a display function. (stripped down) Example:

```<code>class Email extends String{
    static display = (value) => {
        return `<a href='mailto${value}'>${value}</a>`;
    }
}
</code>```

Call it like you do:

```<code>Email.display("test@test.com");
</code>```

And that works in the template, so long as it’s in a v-html attribute. This is perfectly acceptable.

It’s probably important to specify I’m working with Vue-CLI and single-file components, so all that sweet hyperscript gets created at compile time.

But it got me thinking, is there a way I can pass a freshly-created hyperscript to the template at render? Preferably in a way that works in the {{mustache}} if at all possible.

I tried doing it with h but that just displays the ol’ [object Object].

```<code>class Email extends String{
    static display = (value) => {
        return h('a', {innerHtml: value});
    }
}
</code>```

Update: also tried

I thought maybe going around the Vue render functions could get the job done, but they don't seem to like document fragments either.

```<code>static display = (value) => {
    var fragment = document.createDocumentFragment();
    var a = document.createElement('a');
    a.textContent = value;
    fragment.appendChild(a);
    return fragment;
}
</code>```

Question
Is there a way create hyperscript at runtime and utilize it in a vue template? Bonus points if it works in {{mustache}} and v-html.

答:
Generally component templates and render functions that use JSX or h (hyperscript) are mutually exclusive.

It's really possible to do this, in this case display is actually functional component, and it needs to be output as any other dynamic component:

```<code>setup() {
    const display = (props) => {
      return h(...);
    };

    return { display };
}
</code>```

and

```<code><component :is="display" :value="..."/>
</code>```

The return of display is a hierarchy of vnode objects, they can't be used as is in v-html without being previously rendered to HTML.

Body:
I wanted to try something for performance/convenience purposes, I understand the gains will be minimal but understanding how/if/why this works would also just be helpful to learn.

I have a some custom data types (defined as classes) that are used to identify certain properties throughout my application. I want to use a static function on the type to define a display function. (stripped down) Example:

class Email extends String{
    static display = (value) => {
        return `<a href='mailto${value}'>${value}</a>`;
    }
}

Call it like you do:

Email.display("test@test.com");

And that works in the template, so long as it’s in a v-html attribute. This is perfectly acceptable.

It’s probably important to specify I’m working with Vue-CLI and single-file components, so all that sweet hyperscript gets created at compile time.

But it got me thinking, is there a way I can pass a freshly-created hyperscript to the template at render? Preferably in a way that works in the {{mustache}} if at all possible.

I tried doing it with h but that just displays the ol’ [object Object].

class Email extends String{
    static display = (value) => {
        return h('a', {innerHtml: value});
    }
}

Update: also tried

I thought maybe going around the Vue render functions could get the job done, but they don't seem to like document fragments either.

static display = (value) => {
    var fragment = document.createDocumentFragment();
    var a = document.createElement('a');
    a.textContent = value;
    fragment.appendChild(a);
    return fragment;
}

Question
Is there a way create hyperscript at runtime and utilize it in a vue template? Bonus points if it works in {{mustache}} and v-html.

Body:
Generally component templates and render functions that use JSX or h (hyperscript) are mutually exclusive.

It's really possible to do this, in this case display is actually functional component, and it needs to be output as any other dynamic component:

setup() {
    const display = (props) => {
      return h(...);
    };

    return { display };
}

and

<component :is="display" :value="..."/>

The return of display is a hierarchy of vnode objects, they can't be used as is in v-html without being previously rendered to HTML.


问:
Remove duplicates from list of lists by column value
I have a list of list that look like this, they have been sorted so that duplicate IDs are arranged with the one I want to keep at the top..

```<code>[
    {'id': '23', 'type': 'car', 'price': '445'},
    {'id': '23', 'type': 'car', 'price': '78'},
    {'id': '23', 'type': 'car', 'price': '34'},
    {'id': '125', 'type': 'truck', 'price': '998'},
    {'id': '125', 'type': 'truck', 'price': '722'},
    {'id': '125', 'type': 'truck', 'price': '100'},
    {'id': '87', 'type': 'bike', 'price': '50'},
]
</code>```

What is the simplest way to remove rows that have duplicate IDs but always keep the first one? In this instance the end result would look like this...

```<code>[
    {'id': '23', 'type': 'car', 'price': '445'},
    {'id': '125', 'type': 'truck', 'price': '998'},
    {'id': '87', 'type': 'bike', 'price': '50'},
]
</code>```

I know I can remove duplicates from lists by converting to set like set(my_list) but in this instance it is duplicates by ID that I want to remove by

答:
Let's take the name of the given list as data.

```<code>unique_ids = []
result = []
for item in data:
    if item["id"] not in unique_ids:
        result.append(item)
        unique_ids.append(item["id"])
print(result)
</code>```

The result will be,

```<code>[{'id': '23', 'type': 'car', 'price': '445'},
 {'id': '125', 'type': 'truck', 'price': '998'},
 {'id': '87', 'type': 'bike', 'price': '50'}]
</code>```

Body:
I have a list of list that look like this, they have been sorted so that duplicate IDs are arranged with the one I want to keep at the top..

[
    {'id': '23', 'type': 'car', 'price': '445'},
    {'id': '23', 'type': 'car', 'price': '78'},
    {'id': '23', 'type': 'car', 'price': '34'},
    {'id': '125', 'type': 'truck', 'price': '998'},
    {'id': '125', 'type': 'truck', 'price': '722'},
    {'id': '125', 'type': 'truck', 'price': '100'},
    {'id': '87', 'type': 'bike', 'price': '50'},
]

What is the simplest way to remove rows that have duplicate IDs but always keep the first one? In this instance the end result would look like this...

[
    {'id': '23', 'type': 'car', 'price': '445'},
    {'id': '125', 'type': 'truck', 'price': '998'},
    {'id': '87', 'type': 'bike', 'price': '50'},
]

I know I can remove duplicates from lists by converting to set like set(my_list) but in this instance it is duplicates by ID that I want to remove by

Body:
Let's take the name of the given list as data.

unique_ids = []
result = []
for item in data:
    if item["id"] not in unique_ids:
        result.append(item)
        unique_ids.append(item["id"])
print(result)

The result will be,

[{'id': '23', 'type': 'car', 'price': '445'},
 {'id': '125', 'type': 'truck', 'price': '998'},
 {'id': '87', 'type': 'bike', 'price': '50'}]


问:
How to avoid keyerror with two forms with two submit buttons in HTML
I have 2 separate forms on my page, and I gave them 2 separate submit buttons (has to be like that because of the task), they would initiate a search each. The problem is that when I check on values in an if/elif statement if one of the forms is empty, I get an error message for it and I don't understand why, since I originally tried it like this: if request.form["applicant_name"]: do something which is supposed to check if it exists right?

Anyway here is the code in my html and my server.py file below:

```<code>  <h3>Search for applicants</h3>
  <form action="/applicant-phone" method="post" id="form1">
    <input
      type="text"
      name="applicant-name"
      id="form1"
      placeholder="Applicant name"
    />
    <button type="submit" form="form1">Search</button>
  </form>

  <form action="/applicant-phone" method="post" id="form2">
    <input
      type="text"
      name="email-ending"
      id="form2"
      placeholder="Email ending"
    />
    <button type="submit" form="form2">Search</button>
  </form>
</section>
</code>```
```<code>    name = request.form["applicant-name"]
    email = request.form["email-ending"]

    if name:
        applicant_details = data_manager.get_applicant_data_by_name(name)
        return render_template('applicants.html', applicants=applicant_details)
    elif email:
        applicant_details = data_manager.get_applicant_data_by_email_ending(email)
        return render_template('applicants.html', applicants=applicant_details)

    return redirect("/")
</code>```

Sadly it runs on an error on the first lines when I try to get the variables in the functions, it ran on an error when I tried to check on the request.form data in the If statement as well.

答:
No, with regular Python dicts, indexing with [...] raises a KeyError if ... is not in the dictionary. Change the indexing to .get(); it returns a default value if the key is not found; the default default is None.

```<code>name = request.form.get("applicant-name")
email = request.form.get("email-ending")
</code>```

You can also simplify your code to not have multiple render_template calls:

```<code>name = request.form.get("applicant-name")
email = request.form.get("email-ending")

applicant_details = None

if name:
    applicant_details = data_manager.get_applicant_data_by_name(name)
elif email:
    applicant_details = data_manager.get_applicant_data_by_email_ending(email)

if applicant_details is not None:
    return render_template("applicants.html", applicants=applicant_details)

return redirect("/")
</code>```

Body:
I have 2 separate forms on my page, and I gave them 2 separate submit buttons (has to be like that because of the task), they would initiate a search each. The problem is that when I check on values in an if/elif statement if one of the forms is empty, I get an error message for it and I don't understand why, since I originally tried it like this: if request.form["applicant_name"]: do something which is supposed to check if it exists right?

Anyway here is the code in my html and my server.py file below:

Search for applicants

  <form action="/applicant-phone" method="post" id="form1">
    <input
      type="text"
      name="applicant-name"
      id="form1"
      placeholder="Applicant name"
    />
    <button type="submit" form="form1">Search</button>
  </form>

  <form action="/applicant-phone" method="post" id="form2">
    <input
      type="text"
      name="email-ending"
      id="form2"
      placeholder="Email ending"
    />
    <button type="submit" form="form2">Search</button>
  </form>

    name = request.form["applicant-name"]
    email = request.form["email-ending"]

    if name:
        applicant_details = data_manager.get_applicant_data_by_name(name)
        return render_template('applicants.html', applicants=applicant_details)
    elif email:
        applicant_details = data_manager.get_applicant_data_by_email_ending(email)
        return render_template('applicants.html', applicants=applicant_details)

    return redirect("/")

Sadly it runs on an error on the first lines when I try to get the variables in the functions, it ran on an error when I tried to check on the request.form data in the If statement as well.

Body:
No, with regular Python dicts, indexing with [...] raises a KeyError if ... is not in the dictionary. Change the indexing to .get(); it returns a default value if the key is not found; the default default is None.

name = request.form.get("applicant-name")
email = request.form.get("email-ending")

You can also simplify your code to not have multiple render_template calls:

name = request.form.get("applicant-name")
email = request.form.get("email-ending")

applicant_details = None

if name:
    applicant_details = data_manager.get_applicant_data_by_name(name)
elif email:
    applicant_details = data_manager.get_applicant_data_by_email_ending(email)

if applicant_details is not None:
    return render_template("applicants.html", applicants=applicant_details)

return redirect("/")


问:
Visual Studio keeps incorrectly trying to create "AtlTraceTool8.exe"
I've been trying to figure out why Visual Studio 2008 is running so slowly. With Process Monitor, I noticed a ton of instances of devenv trying to work with or create the file "AtlTraceTool8.exe" (which exists on my system). The problem is, the path it's using to work with this file looks like a failed resolution of an absolute path, and it causing a ton of repeated failed file operations.

It's looking for paths like

```<code>C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\"C:\Program Files\Microsoft Visual Studio 9.0\Common7\Tools\AtlTraceTool8.exe"
</code>```

Notice how the path is broken near the middle.

How might I fix this problem? It seems like it might be a Visual Studio configuration error.

答:
Found what's wrong. This is probably something the developers of Visual Studio need to address, because this is definitely how it came when it was installed.

After installing visual studio, the AtlTraceTool8.exe command menu is incorrectly configured in the registry. You can see this by going to the "Tools" menu bar, and seeing that the option "ATL/MFC Trace Tool" is disabled.

This can be solved by searching for the HKEY_USERS registry key corresponding to these menu items. It will be in a folder structure that looks like
Software\Microsoft\VisualStudio\9.0\External Tools\ The key name is "ToolCMD2". All the other tool command paths are written out plainly in this set of keys, but for some reason, this one key has the path surrounded by quotation marks. If you edit the key to remove these quotation mars, the tool becomes usable and the silent errors ProcessMon picks up on all go away.

OwnerDisplayName: Alain

Body:
I've been trying to figure out why Visual Studio 2008 is running so slowly. With Process Monitor, I noticed a ton of instances of devenv trying to work with or create the file "AtlTraceTool8.exe" (which exists on my system). The problem is, the path it's using to work with this file looks like a failed resolution of an absolute path, and it causing a ton of repeated failed file operations.

It's looking for paths like

C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\"C:\Program Files\Microsoft Visual Studio 9.0\Common7\Tools\AtlTraceTool8.exe"

Notice how the path is broken near the middle.

How might I fix this problem? It seems like it might be a Visual Studio configuration error.


问:
How to set container with max-width but only from one side?
My container looks like this:

```<code>.container{
    width: 100%;
    max-width: 1254px;
    margin-left: auto;
    margin-right: auto;
}
</code>```

then I need a container that has the same margin from the left, but from the right it should have none.

I tried something like this however unfortunately it does not work.

```<code> .containerFromLeft {
    width: 100%;
    max-width: 1254px;
    margin-left: auto;
    margin-right: 0;
}
</code>```

答:
You can do it like below. I am using 500px for the demo but you can replace it with your width

.container {
  height: 100px;
  background: red;
  margin-left: max(0px, (100% - 500px)/2); /* what you need */
}

/* to compare with the classic configuration */
.box {
  height: 100px;
  background: green;
  max-width:500px;
  margin:auto;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container"></div>

<div class="box"></div></code>```

Body:
My container looks like this:

.container{
    width: 100%;
    max-width: 1254px;
    margin-left: auto;
    margin-right: auto;
}

then I need a container that has the same margin from the left, but from the right it should have none.

I tried something like this however unfortunately it does not work.

 .containerFromLeft {
    width: 100%;
    max-width: 1254px;
    margin-left: auto;
    margin-right: 0;
}

Body:
You can do it like below. I am using 500px for the demo but you can replace it with your width

.container {
  height: 100px;
  background: red;
  margin-left: max(0px, (100% - 500px)/2); /* what you need */
}

/* to compare with the classic configuration */
.box {
  height: 100px;
  background: green;
  max-width:500px;
  margin:auto;
 }

<div class="container"></div>

<div class="box"></div>


问:
React-native: Hooks can only be called inside of the body of a function component
Hey i have a problem with my react-native app.

I have 3 file

App.tsx

```<code> /**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow strict-local
 */

import React from 'react';
import {
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  useColorScheme,
  View,
  Button
} from 'react-native';

import {
  Colors,
  DebugInstructions,
  Header,
  LearnMoreLinks,
  ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import { NavigationContainer, useNavigation } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import Helloworld from './components/Helloworld';
import Test from './components/Test';
const Stack = createNativeStackNavigator();

class App extends React.Component {
  render() {
    const isDarkMode = useColorScheme() === 'dark';

    const backgroundStyle = {
      backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
    };
    return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={Helloworld} />
        <Stack.Screen name="Test" component={Test} />

      </Stack.Navigator>
    </NavigationContainer>

  );
}
};
export default App;
</code>```

components/Test.tsx

```<code>import React from 'react';
import {
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  useColorScheme,
  View,
  Button
} from 'react-native';

import {
  Colors,
  DebugInstructions,
  Header,
  LearnMoreLinks,
  ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { StackScreenProps } from '@react-navigation/stack';

// eslint-disable-next-line  @typescript-eslint/no-explicit-any
const Test = ({ navigation }:any) => {

    return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
          <Text>BAGOU IS BEST</Text>
           <Button
            title="Go to Home... again"
            onPress={() => navigation.push('Home')}
          />
        </View>
      );
}

export default Test;
</code>```

components/Helloworld.tsx

```<code>import React from 'react';
import {
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  useColorScheme,
  View,
  Button
} from 'react-native';

import {
  Colors,
  DebugInstructions,
  Header,
  LearnMoreLinks,
  ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { StackScreenProps } from '@react-navigation/stack';

const Helloworld = ({ navigation }:any) => {

        return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
          <Text>BAGOU IS BEST</Text>
           <Button
            title="Go to Home... again"
            onPress={() => navigation.navigate.push('Home')}
          />
        </View>
      );
    }

export default Helloworld;
</code>```

and i have this error when i run "yarn android"

```<code>BUNDLE  ./index.js
LOG  Running "appfirst" with {"rootTag":1}
ERROR  Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

This error is located at:
    in App (at renderApplication.js:50)
    in RCTView (at View.js:32)
    in View (at AppContainer.js:92)
    in RCTView (at View.js:32)
    in View (at AppContainer.js:119)
    in AppContainer (at renderApplication.js:43)
    in appfirst(RootComponent) (at renderApplication.js:60)
 ERROR  Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

This error is located at:
    in App (at renderApplication.js:50)
    in RCTView (at View.js:32)
    in View (at AppContainer.js:92)
    in RCTView (at View.js:32)
    in View (at AppContainer.js:119)
    in AppContainer (at renderApplication.js:43)
    in appfirst(RootComponent) (at renderApplication.js:60)
</code>```

I don't understand why.

Can you explain me why?

Also what can i set instead of "{ navigation }:any" because i know is not any but i don t know the type of navigation

答:
The main problem are on the file App.tsx.
You are using useColorScheme inside of a class.
useColorScheme are a Hook, look: https://reactnative.dev/docs/usecolorscheme

Solution, follow one partner only using functions not class.
The best practice is using functional components rather than Class component.

Look the difference here and why are better use functional component, https://reactjs.org/docs/components-and-props.html

Solution

Replace this:

```<code>class App extends React.Component {
  render() {
    const isDarkMode = useColorScheme() === 'dark';

    const backgroundStyle = {
      backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
    };
    return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={Helloworld} />
        <Stack.Screen name="Test" component={Test} />

      </Stack.Navigator>
    </NavigationContainer>

  );
}
};
</code>```

For this:

```<code>const  App = ()=>{

    const isDarkMode = useColorScheme() === 'dark';

    const backgroundStyle = {
      backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
    };
    return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={Helloworld} />
        <Stack.Screen name="Test" component={Test} />

      </Stack.Navigator>
    </NavigationContainer>)

};
</code>```

Body:
Hey i have a problem with my react-native app.

I have 3 file

App.tsx

 /**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow strict-local
 */

import React from 'react';
import {
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  useColorScheme,
  View,
  Button
} from 'react-native';

import {
  Colors,
  DebugInstructions,
  Header,
  LearnMoreLinks,
  ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import { NavigationContainer, useNavigation } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import Helloworld from './components/Helloworld';
import Test from './components/Test';
const Stack = createNativeStackNavigator();

class App extends React.Component {
  render() {
    const isDarkMode = useColorScheme() === 'dark';

    const backgroundStyle = {
      backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
    };
    return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={Helloworld} />
        <Stack.Screen name="Test" component={Test} />

      </Stack.Navigator>
    </NavigationContainer>

  );
}
};
export default App;

components/Test.tsx

import React from 'react';
import {
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  useColorScheme,
  View,
  Button
} from 'react-native';

import {
  Colors,
  DebugInstructions,
  Header,
  LearnMoreLinks,
  ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { StackScreenProps } from '@react-navigation/stack';

// eslint-disable-next-line  @typescript-eslint/no-explicit-any
const Test = ({ navigation }:any) => {

    return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
          <Text>BAGOU IS BEST</Text>
           <Button
            title="Go to Home... again"
            onPress={() => navigation.push('Home')}
          />
        </View>
      );
}

export default Test;

components/Helloworld.tsx

import React from 'react';
import {
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  useColorScheme,
  View,
  Button
} from 'react-native';

import {
  Colors,
  DebugInstructions,
  Header,
  LearnMoreLinks,
  ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { StackScreenProps } from '@react-navigation/stack';

const Helloworld = ({ navigation }:any) => {

        return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
          <Text>BAGOU IS BEST</Text>
           <Button
            title="Go to Home... again"
            onPress={() => navigation.navigate.push('Home')}
          />
        </View>
      );
    }

export default Helloworld;

and i have this error when i run "yarn android"

BUNDLE  ./index.js
LOG  Running "appfirst" with {"rootTag":1}
ERROR  Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

This error is located at:
    in App (at renderApplication.js:50)
    in RCTView (at View.js:32)
    in View (at AppContainer.js:92)
    in RCTView (at View.js:32)
    in View (at AppContainer.js:119)
    in AppContainer (at renderApplication.js:43)
    in appfirst(RootComponent) (at renderApplication.js:60)
 ERROR  Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

This error is located at:
    in App (at renderApplication.js:50)
    in RCTView (at View.js:32)
    in View (at AppContainer.js:92)
    in RCTView (at View.js:32)
    in View (at AppContainer.js:119)
    in AppContainer (at renderApplication.js:43)
    in appfirst(RootComponent) (at renderApplication.js:60)

I don't understand why.

Can you explain me why?

Also what can i set instead of "{ navigation }:any" because i know is not any but i don t know the type of navigation

Body:
The main problem are on the file App.tsx.
You are using useColorScheme inside of a class.
useColorScheme are a Hook, look: https://reactnative.dev/docs/usecolorscheme

Solution, follow one partner only using functions not class.
The best practice is using functional components rather than Class component.

Look the difference here and why are better use functional component, https://reactjs.org/docs/components-and-props.html

Solution

Replace this:

class App extends React.Component {
  render() {
    const isDarkMode = useColorScheme() === 'dark';

    const backgroundStyle = {
      backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
    };
    return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={Helloworld} />
        <Stack.Screen name="Test" component={Test} />

      </Stack.Navigator>
    </NavigationContainer>

  );
}
};

For this:

const  App = ()=>{

    const isDarkMode = useColorScheme() === 'dark';

    const backgroundStyle = {
      backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
    };
    return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={Helloworld} />
        <Stack.Screen name="Test" component={Test} />

      </Stack.Navigator>
    </NavigationContainer>)

};


问:
How to compare two values in different rows AND different columns in pandas
I have it currently working comparing two values on the same row but different columns but I need it to compare one value to the previous row.

For example:
I need to compare the column 'Close' of the row at index 0 to the column 'Open' of the row at index 1.

```<code>df['HigherLower'] = 'No Change'

for index, row in df.iterrows():
    if row['Open'] < row['Close'] :
        df['HigherLower'] = df['HigherLower'].replace(['No Change'],'Lower')
    else:
        df['HigherLower'] = df['HigherLower'].replace(['No Change'],'Higher')
</code>```

答:
Use np.where:

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame({'Open': [10, 20, 30], 'Close': [5, 25, 15]})

df['HigherLower'] = np.where(df['Open'].shift() < df['Close'], 'Lower', 'Higher')
print(df)

# Output:
   Open  Close HigherLower
0    10      5      Higher
1    20     25       Lower
2    30     15      Higher
</code>```

Body:
I have it currently working comparing two values on the same row but different columns but I need it to compare one value to the previous row.

For example:
I need to compare the column 'Close' of the row at index 0 to the column 'Open' of the row at index 1.

df['HigherLower'] = 'No Change'

for index, row in df.iterrows():
    if row['Open'] < row['Close'] :
        df['HigherLower'] = df['HigherLower'].replace(['No Change'],'Lower')
    else:
        df['HigherLower'] = df['HigherLower'].replace(['No Change'],'Higher')

Body:
Use np.where:

import pandas as pd
import numpy as np

df = pd.DataFrame({'Open': [10, 20, 30], 'Close': [5, 25, 15]})

df['HigherLower'] = np.where(df['Open'].shift() < df['Close'], 'Lower', 'Higher')
print(df)

# Output:
   Open  Close HigherLower
0    10      5      Higher
1    20     25       Lower
2    30     15      Higher


问:
log4j2: Is there any way to display sql values in log4j2?
Right now my info logs only show sql queries with ? for values. Can you suggest me changes to log4j2.xml file to display values?

log4j2.xml:

```<code>   <RollingRandomAccessFile name="SQLLOGFILE">
    <PatternLayout>
      <Pattern>%-5p:%d{dd-MMM-yyyy HH:mm:ss,SSS}: %-25t %c : %m%n</Pattern>
    </PatternLayout>
   </RollingRandomAccessFile>

     <AsyncLogger name="jdbc.sqlonly" level="INFO">
       <AppenderRef ref="LOGFILE" level="INFO"/>
     </AsyncLogger>

     <AsyncLogger name="jdbc.audit" level="off"></AsyncLogger>

     <AsyncLogger name="jdbc.resultset" level="off"></AsyncLogger>

     <AsyncLogger name="jdbc.connection" level="DEBUG">
       <AppenderRef ref="CONNECTION"/>
     </AsyncLogger>
</code>```

答:
If your ORM vendor is Hiberante, which is by default in Spring framework you can use the following properties inside log4j2.xml

```<code>  <AsyncLogger name="org.hibernate.SQL" level="DEBUG">
      <AppenderRef ref="LOGFILE"/>
  </AsyncLogger>

  <AsyncLogger name="org.hibernate.type" level="TRACE">
      <AppenderRef ref="LOGFILE"/>
  </AsyncLogger>
</code>```

Those 2 above properties include all necessary classes for the SQLs to appear correctly in your logs, including the binded values inside ? placeholders.

More specifically in hibernate the responsible class for placing values inside ? is the org.hibernate.type.descriptor.sql.BasicBinder. Those 2 above properties include this class as well to the Trace level, so the binded values for ? are correctly appended.

Body:
Right now my info logs only show sql queries with ? for values. Can you suggest me changes to log4j2.xml file to display values?

log4j2.xml:

   <RollingRandomAccessFile name="SQLLOGFILE">
    <PatternLayout>
      <Pattern>%-5p:%d{dd-MMM-yyyy HH:mm:ss,SSS}: %-25t %c : %m%n</Pattern>
    </PatternLayout>
   </RollingRandomAccessFile>

     <AsyncLogger name="jdbc.sqlonly" level="INFO">
       <AppenderRef ref="LOGFILE" level="INFO"/>
     </AsyncLogger>

     <AsyncLogger name="jdbc.audit" level="off"></AsyncLogger>

     <AsyncLogger name="jdbc.resultset" level="off"></AsyncLogger>

     <AsyncLogger name="jdbc.connection" level="DEBUG">
       <AppenderRef ref="CONNECTION"/>
     </AsyncLogger>

Body:
If your ORM vendor is Hiberante, which is by default in Spring framework you can use the following properties inside log4j2.xml

  <AsyncLogger name="org.hibernate.SQL" level="DEBUG">
      <AppenderRef ref="LOGFILE"/>
  </AsyncLogger>

  <AsyncLogger name="org.hibernate.type" level="TRACE">
      <AppenderRef ref="LOGFILE"/>
  </AsyncLogger>

Those 2 above properties include all necessary classes for the SQLs to appear correctly in your logs, including the binded values inside ? placeholders.

More specifically in hibernate the responsible class for placing values inside ? is the org.hibernate.type.descriptor.sql.BasicBinder. Those 2 above properties include this class as well to the Trace level, so the binded values for ? are correctly appended.


问:
How to create new c++ object in gdb prompt via new operator
How to create c++ object via new operator in gdb.

I am looking for something similar to

option-1) (gdb) call new ClassType()

or

option-2) (gdb) set $obj = new ClassType()

But both of these options failing in gdb.

答:
Try this way:</p>
```<code>set var $new = malloc(sizeof(class ClassType))
call ClassType::ClassType($var)
</code>```

Body:
Try this way:

set var $new = malloc(sizeof(class ClassType))
call ClassType::ClassType($var)


问:
How to use ResourceManager in a "website" mode?
I am trying here to do a manual translation for the application I am working with. (There is already a working LocalizationModule but it's working dodgy, so I can't use <asp:Localize /> tags.

Normally with ResourceManager you are supposed to be using it as Namespace.Folder.Resourcename (in an application). Currently I am translating an existing asp.net "website" (not web application so no namespace here....).

The resources are located into a folder name "Locales/resources" which contains "fr-ca.resx" and "en-us.resx".

So I used a code with something like this :

```<code>public static string T(string search)
 {
  System.Resources.ResourceManager resMan = new System.Resources.ResourceManager( "Locales", System.Reflection.Assembly.GetExecutingAssembly(), null );

  var text = resMan.GetString(search, System.Threading.Thread.CurrentThread.CurrentCulture);

  if (text == null)
   return "null";
  else if (text == string.Empty)
   return "empty";
  else
   return text;
 }
</code>```

and inside the page I have something like this <%= Locale.T("T_HOME") %>

When I refresh I have this :

Could not find any resources
  appropriate for the specified culture
  or the neutral culture.  Make sure
  "Locales.resources" was correctly
  embedded or linked into assembly
  "App_Code.9yopn1f7" at compile time,
  or that all the satellite assemblies
  required are loadable and fully
  signed. Description: An unhandled
  exception occurred during the
  execution of the current web request.
  Please review the stack trace for more
  information about the error and where
  it originated in the code.

Exception Details:
  System.Resources.MissingManifestResourceException:
  Could not find any resources
  appropriate for the specified culture
  or the neutral culture.  Make sure
  "Locales.resources" was correctly
  embedded or linked into assembly
  "App_Code.9yopn1f7" at compile time,
  or that all the satellite assemblies
  required are loadable and fully
  signed.

Source Error:

Line 14:

  System.Resources.ResourceManager
  resMan = new
  System.Resources.ResourceManager(
  "Locales",
  System.Reflection.Assembly.GetExecutingAssembly(),
  null );   Line 15:    Line 16:   var
  text = resMan.GetString(search,
  System.Threading.Thread.CurrentThread.CurrentCulture);
  Line 17:  Line 18:   if (text == null)

Source File:
  c:\inetpub\vhosts\galerieocarre.com\subdomains\dev\httpdocs\App_Code\Locale.cs
  Line: 16

I even tried to load the resource with Locales.fr-ca or only fr-ca nothing quite work here.

答:
Marvin Smit's solution is great if you do not have access to the HTTPContext

```<code>const string ASSEMBLY_NAME = "App_GlobalResources";
const string RESOURCE_NAME = "Resources.MetaTagResource";
const string RESOURCE_MANAGER = "ResourceManager";

Assembly assembly = Assembly.Load(ASSEMBLY_NAME);
Type type = assembly.GetType(RESOURCE_NAME);
PropertyInfo propertyInfo = type.GetProperty(RESOURCE_MANAGER);
ResourceManager resourceManager = propertyInfo.GetValue(null, new object[] { }) as ResourceManager;
resourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, true);
</code>```

But if you have access to the HTTPContext just use HttpContext.GetGlobalResourceObject

```<code>string title = HttpContext.GetGlobalResourceObject("MetaTagResource", "Title").ToString();
string keywords = HttpContext.GetGlobalResourceObject("MetaTagResource", "keywords").ToString();
string description = HttpContext.GetGlobalResourceObject("MetaTagResource", "Description").ToString();
</code>```

Body:
I am trying here to do a manual translation for the application I am working with. (There is already a working LocalizationModule but it's working dodgy, so I can't use <asp:Localize /> tags.

Normally with ResourceManager you are supposed to be using it as Namespace.Folder.Resourcename (in an application). Currently I am translating an existing asp.net "website" (not web application so no namespace here....).

The resources are located into a folder name "Locales/resources" which contains "fr-ca.resx" and "en-us.resx".

So I used a code with something like this :

public static string T(string search)
 {
  System.Resources.ResourceManager resMan = new System.Resources.ResourceManager( "Locales", System.Reflection.Assembly.GetExecutingAssembly(), null );

  var text = resMan.GetString(search, System.Threading.Thread.CurrentThread.CurrentCulture);

  if (text == null)
   return "null";
  else if (text == string.Empty)
   return "empty";
  else
   return text;
 }

and inside the page I have something like this <%= Locale.T("T_HOME") %>

When I refresh I have this :

Could not find any resources
  appropriate for the specified culture
  or the neutral culture.  Make sure
  "Locales.resources" was correctly
  embedded or linked into assembly
  "App_Code.9yopn1f7" at compile time,
  or that all the satellite assemblies
  required are loadable and fully
  signed. Description: An unhandled
  exception occurred during the
  execution of the current web request.
  Please review the stack trace for more
  information about the error and where
  it originated in the code.

Exception Details:
  System.Resources.MissingManifestResourceException:
  Could not find any resources
  appropriate for the specified culture
  or the neutral culture.  Make sure
  "Locales.resources" was correctly
  embedded or linked into assembly
  "App_Code.9yopn1f7" at compile time,
  or that all the satellite assemblies
  required are loadable and fully
  signed.

Source Error:

Line 14:

  System.Resources.ResourceManager
  resMan = new
  System.Resources.ResourceManager(
  "Locales",
  System.Reflection.Assembly.GetExecutingAssembly(),
  null );   Line 15:    Line 16:   var
  text = resMan.GetString(search,
  System.Threading.Thread.CurrentThread.CurrentCulture);
  Line 17:  Line 18:   if (text == null)

Source File:
  c:\inetpub\vhosts\galerieocarre.com\subdomains\dev\httpdocs\App_Code\Locale.cs
  Line: 16

I even tried to load the resource with Locales.fr-ca or only fr-ca nothing quite work here.

Body:
Marvin Smit's solution is great if you do not have access to the HTTPContext

const string ASSEMBLY_NAME = "App_GlobalResources";
const string RESOURCE_NAME = "Resources.MetaTagResource";
const string RESOURCE_MANAGER = "ResourceManager";

Assembly assembly = Assembly.Load(ASSEMBLY_NAME);
Type type = assembly.GetType(RESOURCE_NAME);
PropertyInfo propertyInfo = type.GetProperty(RESOURCE_MANAGER);
ResourceManager resourceManager = propertyInfo.GetValue(null, new object[] { }) as ResourceManager;
resourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, true);

But if you have access to the HTTPContext just use HttpContext.GetGlobalResourceObject

string title = HttpContext.GetGlobalResourceObject("MetaTagResource", "Title").ToString();
string keywords = HttpContext.GetGlobalResourceObject("MetaTagResource", "keywords").ToString();
string description = HttpContext.GetGlobalResourceObject("MetaTagResource", "Description").ToString();


问:
matplotlib histogram: how to display the count over the bar?
With matplotlib's hist function, how can one make it display the count for each bin over the bar?

For example,

```<code>import matplotlib.pyplot as plt
data = [ ... ] # some data
plt.hist(data, bins=10)
</code>```

How can we make the count in each bin display over its bar?

答:
New in matplotlib 3.4.0

There is a new plt.bar_label method to automatically label bar containers.

plt.hist returns the bar container(s) as the third output:

```<code>data = np.random.default_rng(123).rayleigh(1, 70)
counts, edges, bars = plt.hist(data)
#              ^

plt.bar_label(bars)
</code>```

If you have a grouped or stacked histogram, bars will contain multiple containers (one per group), so iterate:

```<code>fig, ax = plt.subplots()
counts, edges, bars = ax.hist([data, data * 0.3], histtype='barstacked')

for b in bars:
    ax.bar_label(b)
</code>```

Note that you can also access the bar container(s) via ax.containers:

```<code>for c in ax.containers:
    ax.bar_label(c)
</code>```

Body:
With matplotlib's hist function, how can one make it display the count for each bin over the bar?

For example,

import matplotlib.pyplot as plt
data = [ ... ] # some data
plt.hist(data, bins=10)

How can we make the count in each bin display over its bar?

Body:
New in matplotlib 3.4.0

There is a new plt.bar_label method to automatically label bar containers.

plt.hist returns the bar container(s) as the third output:

data = np.random.default_rng(123).rayleigh(1, 70)
counts, edges, bars = plt.hist(data)
#              ^

plt.bar_label(bars)

If you have a grouped or stacked histogram, bars will contain multiple containers (one per group), so iterate:

fig, ax = plt.subplots()
counts, edges, bars = ax.hist([data, data * 0.3], histtype='barstacked')

for b in bars:
    ax.bar_label(b)

Note that you can also access the bar container(s) via ax.containers:

for c in ax.containers:
    ax.bar_label(c)


问:
I/flutter (16745): LateInitializationError: Field 'email' has not been initialized
```<code>class _RigestritState extends State<Rigestrit> {
  final _auth = FirebaseAuth.instance;

  late String email;
  late String password;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: backrond,
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 24),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Text('تسجيل' ,style: logo, textAlign: TextAlign.center,),
              SizedBox(height: 50,),
              ButtenHint(hint: 'الايميل  ', onpressed:(value){ email = value;}, obscureText: false, ),
              ButtenHint(hint: 'كلمة السر ', onpressed:(value){password = value;}, obscureText: true, ),

              Mybouttn(color: blueColor, titel: 'تسجيل', onpressed: () async  {//to send the data to firebase
                try{
                  final newUer = await  _auth.createUserWithEmailAndPassword(email: email, password: password);
                  Navigator.pushNamed(context, home.homePage);
                }catch(e){
                  print(e);

                }

              }),
</code>```

答:
Name and Email are initialized as late but not initialized before accessing the field.

Fields are initialized with the value

```<code>String email = '';
String password = '';
</code>```

or it should be initialized before accessing the value

```<code>  late String email;
  late String password;

  @override
  void initState(){
    email = '';
    password = '';
    super.initState();
  }
</code>```

And the late keyword is mostly used to define the final value when the value might be available in the future.

Body:
Name and Email are initialized as late but not initialized before accessing the field.

Fields are initialized with the value

String email = '';
String password = '';

or it should be initialized before accessing the value

  late String email;
  late String password;

  @override
  void initState(){
    email = '';
    password = '';
    super.initState();
  }

And the late keyword is mostly used to define the final value when the value might be available in the future.


问:
How to change the version of the 'default gradle wrapper' in IntelliJ IDEA?
I want to use Gradle 1.10 instead of 1.9. I cannot seem to find where to change this.

If I put this:

```<code>task wrapper(type: Wrapper) {
    gradleVersion = '1.10'
}
</code>```

in my build.gradle and rebuild, it is built with Gradle 1.9 again (so nothing actually happens).

These seem to be all the settings: (and IntelliJ's help section about Gradle doesn't help at all :( )

答:
You can set the version of Gradle generated by the wrapper task.

Note that this solution is in Kotlin DSL (build.gradle.kts).

Put this code in your top-level build.gradle.kts file:

tasks.wrapper {
    gradleVersion = "7.4"
    // You can either download the binary-only version of Gradle (BIN) or
    // the full version (with sources and documentation) of Gradle (ALL)
    distributionType = Wrapper.DistributionType.ALL
}
```

Whenever you want to change Gradle version:

Update the version above to your desired version

Execute Gradle wrapper task: ./gradlew wrapper

Sync the IDE (from Gradle sidebar -> reload icon)

Body:
I want to use Gradle 1.10 instead of 1.9. I cannot seem to find where to change this.

If I put this:

task wrapper(type: Wrapper) {
    gradleVersion = '1.10'
}

in my build.gradle and rebuild, it is built with Gradle 1.9 again (so nothing actually happens).

These seem to be all the settings: (and IntelliJ's help section about Gradle doesn't help at all :( )

Body:
You can set the version of Gradle generated by the wrapper task.

Note that this solution is in Kotlin DSL (build.gradle.kts).

Put this code in your top-level build.gradle.kts file:

tasks.wrapper {
    gradleVersion = "7.4"
    // You can either download the binary-only version of Gradle (BIN) or
    // the full version (with sources and documentation) of Gradle (ALL)
    distributionType = Wrapper.DistributionType.ALL
}

Whenever you want to change Gradle version:

Update the version above to your desired version

Execute Gradle wrapper task: ./gradlew wrapper

Sync the IDE (from Gradle sidebar -> reload icon)


问:
Mailgun Attachment + Axios
I would like to send an attachment with Mailgun using react+axios.

Currently, I get an email with an attachment, but it is not named correctly (the name is ".") and if I rename it to a text file it contains the text "[object Object]".
Do you have any idea how to solve this problem?

```<code>const form = new FormData();

const fs = require("fs");

form.append("from", "example@gmx.ch");
form.append("to", "Bob <example@hotmail.ch>");
form.append("subject", "Test");
form.append("text", "Hello!!");
form.append("attachment", [{
    filename: "example.txt",
    data: fs.readFileSync(__dirname + "/text.txt", {
        encoding: "utf8",
        flag: "r"
    })
}]);

const endpoint = "https://api.mailgun.net/v3/sandbox123.mailgun.org/messages";

await axios.post(endpoint, form, {
    auth: {
        username: "api",
        password: process.env.MAILGUN_API_KEY
    },
    headers: { "Content-Type": "multipart/form-data" }
});
</code>```

答:
Two things:

As per the mailgun docs when sending attachments you must use "multipart/form-data" encoding. Try:

await axios.post(endpoint, form, {
    auth: {
        username: "api",
        password: process.env.MAILGUN_API_KEY
    },
    headers: { 'Content-Type': 'multipart/form-data' }
 });
```

Try putting your attachment object inside an array. I am not familiar with the mailgun API but I saw a couple examples where the attachments were inside an array, maybe even if there is a single attachment the API is still expecting it this way.

Title: Mailgun Attachment + Axios

Body:
I would like to send an attachment with Mailgun using react+axios.

Currently, I get an email with an attachment, but it is not named correctly (the name is ".") and if I rename it to a text file it contains the text "[object Object]".
Do you have any idea how to solve this problem?

const form = new FormData();

const fs = require("fs");

form.append("from", "example@gmx.ch");
form.append("to", "Bob <example@hotmail.ch>");
form.append("subject", "Test");
form.append("text", "Hello!!");
form.append("attachment", [{
    filename: "example.txt",
    data: fs.readFileSync(__dirname + "/text.txt", {
        encoding: "utf8",
        flag: "r"
    })
}]);

const endpoint = "https://api.mailgun.net/v3/sandbox123.mailgun.org/messages";

await axios.post(endpoint, form, {
    auth: {
        username: "api",
        password: process.env.MAILGUN_API_KEY
    },
    headers: { "Content-Type": "multipart/form-data" }
});

Body:
Two things:

As per the mailgun docs when sending attachments you must use "multipart/form-data" encoding. Try:

await axios.post(endpoint, form, {
    auth: {
        username: "api",
        password: process.env.MAILGUN_API_KEY
    },
    headers: { 'Content-Type': 'multipart/form-data' }
 });

Try putting your attachment object inside an array. I am not familiar with the mailgun API but I saw a couple examples where the attachments were inside an array, maybe even if there is a single attachment the API is still expecting it this way.


问:
How do i make my button link to the next page without changing the styling?
How do i make my button link to the next page without changing the styling?</p>

```<code>  <div class="image-round-fit">

    <img src="images/pic.jpg" alt="photo" width="300px" height="300px" />

    <span class="caption">Hello World</span></br>

      <a href="#" class="btn btn-info role=button">Click Next</a>

  </div>
</code>```

答:
You can use CSS to do it. CSS is a language to style content in HTML.

a{
    color: black;
    text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Click Next</code>```

The a is the tag name it is relating to. The color and text-decoration are properties. The color changes the text color and the text-decoration changes extras to the text, including if you want to include underline or not.

Or maybe it was this? To not change the color to purple permanently.

a:visited{
    color: blue;
}
a:active{
    color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Click Next</code>```

The : stands for it relating to the a when in a condition. :visited stands for when you visited it, it will do whatever below. :active does whatever below when your mouse is down on the link. Remove the :active if you don't want it to change color at any state.

Body:
How do i make my button link to the next page without changing the styling?

    Hello World

      Click Next

Body:
You can use CSS to do it. CSS is a language to style content in HTML.

a{
    color: black;
    text-decoration: none;
}

<a href = "#" class = "btn btn-info" role = "button">Click Next</a>

The a is the tag name it is relating to. The color and text-decoration are properties. The color changes the text color and the text-decoration changes extras to the text, including if you want to include underline or not.

Or maybe it was this? To not change the color to purple permanently.

a:visited{
    color: blue;
}
a:active{
    color: red;
}

<a href = "#" role = "button" class = "btn btn-info">Click Next</a>

The : stands for it relating to the a when in a condition. :visited stands for when you visited it, it will do whatever below. :active does whatever below when your mouse is down on the link. Remove the :active if you don't want it to change color at any state.


问:
How to logout with flask_jwt_extended
Generating jwt with flask_jwt_extended.

creating token

```<code>create_access_token(identity=identity)
</code>```

i couldn't find anything about logout. Revoking jwt token

Thanks

答:
Define a callback function via the token_in_blocklist_loader() decorator.

In practice you'd have some DB where you are keeping track of this.

I don't know what you mean by did not find anything, there is a documentation on revoking it that has some good advice.

Title: How to logout with flask_jwt_extended

Body:
Generating jwt with flask_jwt_extended.

creating token

create_access_token(identity=identity)

i couldn't find anything about logout. Revoking jwt token

Thanks


问:
React Router 6 using Fragment in Route
I have this code here for a route which works with react router v5

```<code><Route
  path="/"
  render={() => (
    <React.Fragment>
      <AddPostForm />
      <PostsList />
    </React.Fragment>
  )}
/>
</code>```

How can I refactor it for react router v6?

答:
This might help.</p>
```<code>  <Routes>
    <Route
      path="/"
      element={<>
               <AddPostForm />
               <PostsList />
              </>
              }
    />
    </Routes>
</code>```

Title: React Router 6 using Fragment in Route

Body:
I have this code here for a route which works with react router v5

<Route
  path="/"
  render={() => (
    <React.Fragment>
      <AddPostForm />
      <PostsList />
    </React.Fragment>
  )}
/>

How can I refactor it for react router v6?

Body:
This might help.

  <Routes>
    <Route
      path="/"
      element={<>
               <AddPostForm />
               <PostsList />
              </>
              }
    />
    </Routes>