问:
Run script before building image in dockerfile
I have a Dockerfile that needs to run a bash script before building.

Dockerfile:

```<code>ARG  IMAGE_VERSION
FROM path_to_image/images/base:${IMAGE_VERSION}
CMD  /code/run-app
</code>```

The script will find the latest image version by scraping a website. I can't use the "latest" key word as the images are not hosted on docker hub. I need the IMAGE_VERSION to be equal to the output of a script before running the docker build command?

答:
Assuming your script outputs the tag you need, you can do something like this (assuming your script is called myscript.sh)</p>
```<code>docker build --build-arg IMAGE_VERSION=$(./myscript.sh) -t myimage .
</code>```

Body:
I have a Dockerfile that needs to run a bash script before building.

Dockerfile:

ARG  IMAGE_VERSION
FROM path_to_image/images/base:${IMAGE_VERSION}
CMD  /code/run-app

The script will find the latest image version by scraping a website. I can't use the "latest" key word as the images are not hosted on docker hub. I need the IMAGE_VERSION to be equal to the output of a script before running the docker build command?

Body:
Assuming your script outputs the tag you need, you can do something like this (assuming your script is called myscript.sh)

docker build --build-arg IMAGE_VERSION=$(./myscript.sh) -t myimage .


来源: stackexchange

问:
Java Streams: Find first for multiple filter predicates
I have a Collection<Product> and a Collection<Predicate<Product>>. The Predicates are a simple combination of boolean flags. For example:

```<code>             | isNew | isSoldOut
--------------------------------
predicate 1: | false | false
predicate 2: | false | true
predicate 3: | true  | false
predicate 4: | true  | true
</code>```

I want to find "one of every kind", though I'd like to find the first match for every Predicate within the products Collection.

Currently my code looks like this:

List<Product> products = getProducts();
List<Predicate<Product>> predicates = getPredicates();

List<Product> result = predicates.stream()
  .flatMap(predicate -> products.stream().filter(predicate).findFirst().stream())
  .collect(Collectors.toList());
```

But this of course will iterate of the products Collection multiple times, which is not desired, because in my case I have 100000 Products and 64 Predicates and it takes a long time.

In my special case the Predicates are mutually exclusive: If a Predicate returns true, then all other Predicates can be skipped for that particular Product. And because I use findFirst this Predicate then can be skipped for all other Products.

I was wondering if it is possible to iterate over the Product Collection instead, and check every Product only once against all the Predicates.

答:
Your current solution will iterate over the collection many times, but as findFirst is a short-circuiting operator, it will stop as soon as it finds a match. Have you bench-marked it to make sure it is not good enough?

An alternative is to use a stateful filter (see the top answer to this post):

```<code>public static Predicate<Product> matchAndDiscard(final List<Predicate<Product>> predicates) {
  final Set<Predicate<Product>> remaining = new HashSet<>(predicates);
  return product -> {
    final var match = remaining.stream().filter(pred -> pred.test(product)).findFirst();
    match.ifPresent(remaining::remove);
    return match.isPresent();
  };
}
</code>```

much like @Chaosfire's approach, but with the state contained within the filter function. If you believe that all predicates will be matched by at least one product, you can also save some time by limiting the stream to the number of predicates, like so:

```<code>final var predicates = getPredicates()
final var result = getProducts().stream()
    .filter(matchAndDiscard(predicates))
    .limit(predicates.size())
    .toList()
</code>```

In your current solution, you would traverse the products "horisontally":

```<code>       --> products
pred1: ffffffffffffft
pred2: fffft
pred3: ffffffffffffffft
pred4: ft
etc.
</code>```

The alternative will instead do a "vertical" traversal:

```<code>           products
pred1: | ffffffffffffft
pred2: | fffft
pred3: v ffff fffffffffft
pred4:   ft
</code>```

so it is not obvious that one would be much faster than the other, it depends on the particular configuration.

ContentLicense: CC BY-SA 4.0

Body:
I have a Collection<Product> and a Collection<Predicate<Product>>. The Predicates are a simple combination of boolean flags. For example:

             | isNew | isSoldOut
--------------------------------
predicate 1: | false | false
predicate 2: | false | true
predicate 3: | true  | false
predicate 4: | true  | true

I want to find "one of every kind", though I'd like to find the first match for every Predicate within the products Collection.

Currently my code looks like this:

List<Product> products = getProducts();
List<Predicate<Product>> predicates = getPredicates();

List<Product> result = predicates.stream()
  .flatMap(predicate -> products.stream().filter(predicate).findFirst().stream())
  .collect(Collectors.toList());

But this of course will iterate of the products Collection multiple times, which is not desired, because in my case I have 100000 Products and 64 Predicates and it takes a long time.

In my special case the Predicates are mutually exclusive: If a Predicate returns true, then all other Predicates can be skipped for that particular Product. And because I use findFirst this Predicate then can be skipped for all other Products.

I was wondering if it is possible to iterate over the Product Collection instead, and check every Product only once against all the Predicates.

Body:
Your current solution will iterate over the collection many times, but as findFirst is a short-circuiting operator, it will stop as soon as it finds a match. Have you bench-marked it to make sure it is not good enough?

An alternative is to use a stateful filter (see the top answer to this post):

public static Predicate<Product> matchAndDiscard(final List<Predicate<Product>> predicates) {
  final Set<Predicate<Product>> remaining = new HashSet<>(predicates);
  return product -> {
    final var match = remaining.stream().filter(pred -> pred.test(product)).findFirst();
    match.ifPresent(remaining::remove);
    return match.isPresent();
  };
}

much like @Chaosfire's approach, but with the state contained within the filter function. If you believe that all predicates will be matched by at least one product, you can also save some time by limiting the stream to the number of predicates, like so:

final var predicates = getPredicates()
final var result = getProducts().stream()
    .filter(matchAndDiscard(predicates))
    .limit(predicates.size())
    .toList()

In your current solution, you would traverse the products "horisontally":

       --> products
pred1: ffffffffffffft
pred2: fffft
pred3: ffffffffffffffft
pred4: ft
etc.

The alternative will instead do a "vertical" traversal:

           products
pred1: | ffffffffffffft
pred2: | fffft
pred3: v ffff fffffffffft
pred4:   ft

so it is not obvious that one would be much faster than the other, it depends on the particular configuration.


问:
Promise not returning resolve from express app.get Nodejs
I'm trying to return a resolve or reject depending on if the promise was successful or not. I can't seem to figure out why this isn't returning the response. All I get from my promise is [object Object]. This is what I get in response.

Here's the code:

```<code>app.get('/', (req,res) => {
    return new Promise((resolve,reject) => {
        var sql = "INSERT INTO usersinfo (firstname,lastname,email,number,latitude,longitude) VALUES(?,?,?,?,?,?)";
        conn.query(sql,[fname,lname,email,num,req.query.latitude,req.query.longitude], (err,result) => {
            if (err) {
                res.send('error')
                console.log(err,'there has been an error')
                reject('There was an error')
                return
            }else{
                console.log('inserted')
                resolve({ success:'true' })
            }
            res.end()
        })
    })
})
</code>```

Where I'm fetching the url:

```<code>const res = await fetch(`http://MYIPADDRESS?latitude=${latitude}&longitude=${longitude}`)
                console.log(res)
</code>```

I don't seem to get what's wrong. And if I attach the then((response) => console.log(response)) method I get an error in the expo app saying There was an error sending log messages to your development environment PrettyFormatPluginError:value.hasOwnProperty is not a function. (In 'value.hasOwnProperty('tag')','value.hasOwnProperty is undefined)

答:
You don't need to create a promise. The send method can be called asynchronously -- when the response is ready:

```<code>app.get('/', (req,res) => {
    var sql = "INSERT INTO usersinfo (firstname,lastname,email,number,latitude,longitude) VALUES(?,?,?,?,?,?)";
    conn.query(sql,[fname,lname,email,num,req.query.latitude,req.query.longitude], (err,result) => {
        if (err) {
            res.send('error');
            console.log(err,'there has been an error');
        } else {
            res.send({ success:'true' }); // <---
            console.log('inserted');
        }
    });
});
</code>```

NB: also, there is no need to call res.end() as res.send() already implies that.

On the client side you'll have to await the JSON content to be generated:

```<code>const response = await fetch(`http://MYIPADDRESS?latitude=${latitude}&longitude=${longitude}`);
const result = await response.json(); // <---
console.log(result);
</code>```

Body:
I'm trying to return a resolve or reject depending on if the promise was successful or not. I can't seem to figure out why this isn't returning the response. All I get from my promise is [object Object]. This is what I get in response.

Here's the code:

app.get('/', (req,res) => {
    return new Promise((resolve,reject) => {
        var sql = "INSERT INTO usersinfo (firstname,lastname,email,number,latitude,longitude) VALUES(?,?,?,?,?,?)";
        conn.query(sql,[fname,lname,email,num,req.query.latitude,req.query.longitude], (err,result) => {
            if (err) {
                res.send('error')
                console.log(err,'there has been an error')
                reject('There was an error')
                return
            }else{
                console.log('inserted')
                resolve({ success:'true' })
            }
            res.end()
        })
    })
})

Where I'm fetching the url:

const res = await fetch(`http://MYIPADDRESS?latitude=${latitude}&longitude=${longitude}`)
                console.log(res)

I don't seem to get what's wrong. And if I attach the then((response) => console.log(response)) method I get an error in the expo app saying There was an error sending log messages to your development environment PrettyFormatPluginError:value.hasOwnProperty is not a function. (In 'value.hasOwnProperty('tag')','value.hasOwnProperty is undefined)

Body:
You don't need to create a promise. The send method can be called asynchronously -- when the response is ready:

app.get('/', (req,res) => {
    var sql = "INSERT INTO usersinfo (firstname,lastname,email,number,latitude,longitude) VALUES(?,?,?,?,?,?)";
    conn.query(sql,[fname,lname,email,num,req.query.latitude,req.query.longitude], (err,result) => {
        if (err) {
            res.send('error');
            console.log(err,'there has been an error');
        } else {
            res.send({ success:'true' }); // <---
            console.log('inserted');
        }
    });
});

NB: also, there is no need to call res.end() as res.send() already implies that.

On the client side you'll have to await the JSON content to be generated:

const response = await fetch(`http://MYIPADDRESS?latitude=${latitude}&longitude=${longitude}`);
const result = await response.json(); // <---
console.log(result);


问:
Controlling other app's volumes
I've got an app written to control my iPodMusicPlayer, but I want to be able to control the system's default music source (Pandora, Spotify, etc) as opposed to the iPod when they're playing. I can write the code to check if they're playing or not and respectively change the volumes, I just don't know how to access the default audio source/other app's audio.

Suggestions?

答:
I don't think you can manipulate the system or other app volume. The best you can do is to display an alert asking the user to go to Settings & increase/decrease the volume. You cannot even launch the Settings app directly from your app.

HTH,

Akshay

ContentLicense: CC BY-SA 3.0

Title: Controlling other app's volumes


问:
What am I missing in defining an array?
I have been trying to learn arrays and I can't seem to define an array.

```<code>const int size = 10;
??[size];
</code>```

Can anybody spot my mistakes? Thank You.

答:
To declare an array using a constant, you should use this syntax:

```<code>// constexpr is explicitly compile time constant
constexpr int size = 10;
int my_array[size]; // int array, can be changed to float
</code>```

For dynamic array, use vector:

```<code>int size = ...;
std::vector<int> my_array;
array.resize(size);
</code>```

You can also use modern statically sized array:

```<code>constexpr int size = 10;
std::array<int, size> my_array;
</code>```

Title: What am I missing in defining an array?

Body:
I have been trying to learn arrays and I can't seem to define an array.

const int size = 10;
??[size];

Can anybody spot my mistakes? Thank You.

Body:
To declare an array using a constant, you should use this syntax:

// constexpr is explicitly compile time constant
constexpr int size = 10;
int my_array[size]; // int array, can be changed to float

For dynamic array, use vector:

int size = ...;
std::vector<int> my_array;
array.resize(size);

You can also use modern statically sized array:

constexpr int size = 10;
std::array<int, size> my_array;


问:
Advise on how to structure code in relation to models in Angular/TypeScript
In my C# backend I have classes for my entities and entity lists. When I need a function/method on that entity or entity list, I just add it to the class.

In Angular/TypeScript models are defined as interfaces in every example I come across. How should I organize the functions that operate on objects of these interfaces?

I'm using NgRx, and it is tempting to put much of this code alongside the selectors, but I feel that it will quickly become quite messy.

答:
You can use classes and the class keyword in Angular/typescript/(modern) javascript. A rule of thumb is to use an interface to store data (like DTO/POCO s in c#) and if you are modeling behavior use a class.

Furthermore, if you want to separate the logic, you should use delegate that to services, just like in server side frameworks like .net and spring.

A good place to start is John Pappa's angular style guide. github.com/johnpapa/angular-styleguide . This has has been the de facto place to see best practices for a while now. Good luck!


问:
Avoid double spacing in Rmarkdown pdf (within chunk)
I am trying to make my own APA7 style Rmarkdown template (with pdf output). Feel pretty good so far. The only thing left for me to fix is the double spacing in code chunks.

I have quickly found this thread which resolves the issue on how to double space with the following code.

```<code>header-includes:
    - \usepackage{setspace}\doublespacing
</code>```

However, the double spacing also apply to code chunks which I would prefer them to be single space. I know I could add something like \singlespacing before and after the chunks, but since I use many chucks, is there a cleverer way?

It there a way to avoid the double spacing produced by \doublespacing in code chunks?

EDIT

Here is a reproducible example.

```<code>---
output: pdf_document
header-includes:
  - \usepackage{setspace}\doublespacing
---

I am trying to make my own APA7 style Rmarkdown template (with pdf output). Feel pretty good so far. The only thing left for me to fix is the double spacing in code chunks.

```{r}
# This chuck is also double spaced
# But I would prefer it to be single spaces
```
</code>```

答:
Rmarkdown defines a Shaded environment, which is used to set these code snippets. You can patch it to automatically add \singlespace:

```<code>---
output:
  pdf_document:
    keep_tex: true
header-includes:
  - \usepackage{setspace}\doublespacing
  - \usepackage{etoolbox}
  - \AtBeginEnvironment{Shaded}{\singlespace}
---

I am trying to make my own APA7 style Rmarkdown template (with pdf output). Feel pretty good so far. The only thing left for me to fix is the double spacing in code chunks.

```{r}
# This chuck is also double spaced
# But I would prefer it to be single spaces
```
I am trying to make my own APA7 style Rmarkdown template (with pdf output). Feel pretty good so far. The only thing left for me to fix is the double spacing in code chunks.
</code>```

Body:
I am trying to make my own APA7 style Rmarkdown template (with pdf output). Feel pretty good so far. The only thing left for me to fix is the double spacing in code chunks.

I have quickly found this thread which resolves the issue on how to double space with the following code.

header-includes:
    - \usepackage{setspace}\doublespacing

However, the double spacing also apply to code chunks which I would prefer them to be single space. I know I could add something like \singlespacing before and after the chunks, but since I use many chucks, is there a cleverer way?

It there a way to avoid the double spacing produced by \doublespacing in code chunks?

EDIT

Here is a reproducible example.

---
output: pdf_document
header-includes:
  - \usepackage{setspace}\doublespacing
---

I am trying to make my own APA7 style Rmarkdown template (with pdf output). Feel pretty good so far. The only thing left for me to fix is the double spacing in code chunks.

```{r}
# This chuck is also double spaced
# But I would prefer it to be single spaces
```

Body:
Rmarkdown defines a Shaded environment, which is used to set these code snippets. You can patch it to automatically add \singlespace:

---
output:
  pdf_document:
    keep_tex: true
header-includes:
  - \usepackage{setspace}\doublespacing
  - \usepackage{etoolbox}
  - \AtBeginEnvironment{Shaded}{\singlespace}
---

I am trying to make my own APA7 style Rmarkdown template (with pdf output). Feel pretty good so far. The only thing left for me to fix is the double spacing in code chunks.

```{r}
# This chuck is also double spaced
# But I would prefer it to be single spaces
```
I am trying to make my own APA7 style Rmarkdown template (with pdf output). Feel pretty good so far. The only thing left for me to fix is the double spacing in code chunks.


问:
How do I attach a method to a dynamically-created C# type at runtime?
I have been saddled with using an in-house data access library that is effectively XML passed to a stored procedure, which returns XML. There is nothing I can do about this. I tried to get ActiveRecord approved, but my request was declined. However, using the excellent code provided at http://blog.bodurov.com/Post.aspx?postID=27, I added an extension method to IEnumerable that converts the key-value pairs I make out of the ragged XML coming back into strongly typed objects, complete with property names!

This:

```<code>dict["keyName1"]
</code>```

becomes

```<code>MyObject.keyName1
</code>```

Now the interface supports databinding! Pretty cool! I'd like to take it a step further, though. I want the objects emitted to have Save() methods too, so that I can ape the ActiveRecord pattern and provide my web guys with an intuitive object layer to use from ASP.net.

How do I write a method in Visual Studio, in source code, and attach it at runtime to the emitted objects? I am not interested in (or qualified for) writing assembly or IL. I'd like to do this in C#. This is my first StackOverflow question and I am posting this with company-mandated IE6, so please be gentle.

答:
From what I gather on that article, it's creating anonymous types for you, and you're using that to get the values. If that's the case, there's no easy way to add methods on to those objects. However, if the XML structure will be the same every time the SP executes, why not create a concrete class that has all the properties you need, and populate a collection of those objects yourself with the XML. That way, you can easily add any methods you need directly into the class...

EDIT: Based on our discussion in the comments, here's a thought:

In the code there, when you're building up the type, you're using: ModuleBuilder.DefineType. There's an overload to DefineType which takes a type to extend. Link.. Therefore, create an interface (it doesn't event have to have any methods in it), and when you're dynamically building up the type, extend that interface using the overload I linked you to. Then create an extension method on that interface that does the Save().

There's another overload that may be of interest that takes a type to extend, and interfaces:

http://msdn.microsoft.com/en-us/library/f53tx4x8.aspx

EDIT2: Code sample:

First, create an interface:

```<code>public interface ISaveExtentable //I suck at naming stuff :-p
{

}
</code>```

Then, in the code you liked to in that site, you'll find a method called: GetTypeBuilder. Change it to this:

```<code>        private static TypeBuilder GetTypeBuilder(string typeSigniture)
        {
            AssemblyName an = new AssemblyName("TempAssembly" + typeSigniture);
            AssemblyBuilder assemblyBuilder =
                AppDomain.CurrentDomain.DefineDynamicAssembly(
                    an, AssemblyBuilderAccess.Run);
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");

            TypeBuilder tb = moduleBuilder.DefineType("TempType" + typeSigniture
                                , TypeAttributes.Public |
                                TypeAttributes.Class |
                                TypeAttributes.AutoClass |
                                TypeAttributes.AnsiClass |
                                TypeAttributes.BeforeFieldInit |
                                TypeAttributes.AutoLayout
                                , typeof(object), new Type[] {typeof(ISaveExtentable)});
            return tb;
        }
</code>```

Then, create an extension method on that interface to do the save:

```<code>    public static class SaveExtendableExtensions
    {
          public static void Save(this ISaveExtentable ise)
          {
              //implement save functionality.
          }
    }
</code>```

You'll most likely need to use reflection in your Save method to get all the properties since the type was created dynamically.

OwnerDisplayName: Chris McCall

ContentLicense: CC BY-SA 2.5

Body:
I have been saddled with using an in-house data access library that is effectively XML passed to a stored procedure, which returns XML. There is nothing I can do about this. I tried to get ActiveRecord approved, but my request was declined. However, using the excellent code provided at http://blog.bodurov.com/Post.aspx?postID=27, I added an extension method to IEnumerable that converts the key-value pairs I make out of the ragged XML coming back into strongly typed objects, complete with property names!

This:

dict["keyName1"]

becomes

MyObject.keyName1

Now the interface supports databinding! Pretty cool! I'd like to take it a step further, though. I want the objects emitted to have Save() methods too, so that I can ape the ActiveRecord pattern and provide my web guys with an intuitive object layer to use from ASP.net.

How do I write a method in Visual Studio, in source code, and attach it at runtime to the emitted objects? I am not interested in (or qualified for) writing assembly or IL. I'd like to do this in C#. This is my first StackOverflow question and I am posting this with company-mandated IE6, so please be gentle.

LastEditorDisplayName: Chris McCall

Body:
From what I gather on that article, it's creating anonymous types for you, and you're using that to get the values. If that's the case, there's no easy way to add methods on to those objects. However, if the XML structure will be the same every time the SP executes, why not create a concrete class that has all the properties you need, and populate a collection of those objects yourself with the XML. That way, you can easily add any methods you need directly into the class...

EDIT: Based on our discussion in the comments, here's a thought:

In the code there, when you're building up the type, you're using: ModuleBuilder.DefineType. There's an overload to DefineType which takes a type to extend. Link.. Therefore, create an interface (it doesn't event have to have any methods in it), and when you're dynamically building up the type, extend that interface using the overload I linked you to. Then create an extension method on that interface that does the Save().

There's another overload that may be of interest that takes a type to extend, and interfaces:

http://msdn.microsoft.com/en-us/library/f53tx4x8.aspx

EDIT2: Code sample:

First, create an interface:

public interface ISaveExtentable //I suck at naming stuff :-p
{

}

Then, in the code you liked to in that site, you'll find a method called: GetTypeBuilder. Change it to this:

        private static TypeBuilder GetTypeBuilder(string typeSigniture)
        {
            AssemblyName an = new AssemblyName("TempAssembly" + typeSigniture);
            AssemblyBuilder assemblyBuilder =
                AppDomain.CurrentDomain.DefineDynamicAssembly(
                    an, AssemblyBuilderAccess.Run);
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");

            TypeBuilder tb = moduleBuilder.DefineType("TempType" + typeSigniture
                                , TypeAttributes.Public |
                                TypeAttributes.Class |
                                TypeAttributes.AutoClass |
                                TypeAttributes.AnsiClass |
                                TypeAttributes.BeforeFieldInit |
                                TypeAttributes.AutoLayout
                                , typeof(object), new Type[] {typeof(ISaveExtentable)});
            return tb;
        }

Then, create an extension method on that interface to do the save:

    public static class SaveExtendableExtensions
    {
          public static void Save(this ISaveExtentable ise)
          {
              //implement save functionality.
          }
    }

You'll most likely need to use reflection in your Save method to get all the properties since the type was created dynamically.

OwnerDisplayName: BFree

LastEditorDisplayName: BFree


问:
SwiftUI ContentView_Previews not running function
I'm trying to generate some mock data for my preview in Xcode with a method written directly in ContentView_Previews but I have no success and I don't understand why.

```<code>struct ContentView_Previews: PreviewProvider {
    static let healthManager = generateMockData()

    static var previews: some View {
        MainView().environmentObject(healthManager)
    }

    static func generateMockData() -> HealthManager {
        let defaultHealthManager = HealthManager()
        defaultHealthManager.gavePermissions = true

        for i in 1...10 {
            let defaultWorkout = HKWorkout(activityType: .traditionalStrengthTraining,
                                           start: .now - Double(i * 50),
                                           end: .now,
                                           duration: Double(i * 100),
                                           totalEnergyBurned: HKQuantity(unit: .largeCalorie(), doubleValue: Double(i * 100)),
                                           totalDistance: nil,
                                           device: nil,
                                           metadata: nil)

            defaultHealthManager.previousWorkouts.append(defaultWorkout)
        }

        return defaultHealthManager
    }
}
</code>```

Basically it shows up defaultHealthManager object has no values set besides the default ones.
If I call ContentView_Previews. generateMockData() for my property in the actual view at runtime, it works fine.

答:
On occasion, I seem to need to create what I call an intermediary view to get things to work. Does something like this work?

```<code>struct MainViewIntermediary: View {
    @State var healthManager: HealthManager

    init() {
        let defaultHealthManager = HealthManager()
        defaultHealthManager.gavePermissions = true

        for i in 1...10 {
            let defaultWorkout = HKWorkout(activityType: .traditionalStrengthTraining,
                                           start: .now - Double(i * 50),
                                           end: .now,
                                           duration: Double(i * 100),
                                           totalEnergyBurned: HKQuantity(unit: .largeCalorie(), doubleValue: Double(i * 100)),
                                           totalDistance: nil,
                                           device: nil,
                                           metadata: nil)

            defaultHealthManager.previousWorkouts.append(defaultWorkout)
            _healthManager = State(initialValue: defaultHealthManager)
        }
    }

   var body: some View {
        MainView().environmentObject(healthManager)
    }
}
</code>```

Then your preview provider becomes:

```<code>struct ContentView_Previews: PreviewProvider {

    static var previews: some View {
        MainViewIntermediary()
    }
}
</code>```

Body:
I'm trying to generate some mock data for my preview in Xcode with a method written directly in ContentView_Previews but I have no success and I don't understand why.

struct ContentView_Previews: PreviewProvider {
    static let healthManager = generateMockData()

    static var previews: some View {
        MainView().environmentObject(healthManager)
    }

    static func generateMockData() -> HealthManager {
        let defaultHealthManager = HealthManager()
        defaultHealthManager.gavePermissions = true

        for i in 1...10 {
            let defaultWorkout = HKWorkout(activityType: .traditionalStrengthTraining,
                                           start: .now - Double(i * 50),
                                           end: .now,
                                           duration: Double(i * 100),
                                           totalEnergyBurned: HKQuantity(unit: .largeCalorie(), doubleValue: Double(i * 100)),
                                           totalDistance: nil,
                                           device: nil,
                                           metadata: nil)

            defaultHealthManager.previousWorkouts.append(defaultWorkout)
        }

        return defaultHealthManager
    }
}

Basically it shows up defaultHealthManager object has no values set besides the default ones.
If I call ContentView_Previews. generateMockData() for my property in the actual view at runtime, it works fine.

Body:
On occasion, I seem to need to create what I call an intermediary view to get things to work. Does something like this work?

struct MainViewIntermediary: View {
    @State var healthManager: HealthManager

    init() {
        let defaultHealthManager = HealthManager()
        defaultHealthManager.gavePermissions = true

        for i in 1...10 {
            let defaultWorkout = HKWorkout(activityType: .traditionalStrengthTraining,
                                           start: .now - Double(i * 50),
                                           end: .now,
                                           duration: Double(i * 100),
                                           totalEnergyBurned: HKQuantity(unit: .largeCalorie(), doubleValue: Double(i * 100)),
                                           totalDistance: nil,
                                           device: nil,
                                           metadata: nil)

            defaultHealthManager.previousWorkouts.append(defaultWorkout)
            _healthManager = State(initialValue: defaultHealthManager)
        }
    }

   var body: some View {
        MainView().environmentObject(healthManager)
    }
}

Then your preview provider becomes:

struct ContentView_Previews: PreviewProvider {

    static var previews: some View {
        MainViewIntermediary()
    }
}


问:
How exactly are structs captured in escaping closures?
It seems logical to me that escaping closures would capture structs by copying. But if that was the case, the following code makes no sense and should not compile:

```<code>struct Wtf {
    var x = 1
}

func foo(){

    var wtf = Wtf()

    DispatchQueue.global().async {
        wtf.x = 5
    }

    Thread.sleep(forTimeInterval: 2)
    print("x = \(wtf.x)")
}
</code>```

Yet it compiles successfully and even prints 5 when foo is called. How is this possible?

答:
While it might make sense for a struct to be copied, as your code demonstrates, it is not. That's a powerful tool. For example:

```<code>func makeCounter() -> () -> Int {
    var n = 0
    return {
        n += 1  // This `n` is the same `n` from the outer scope
        return n
    }

    // At this point, the scope is gone, but the `n` lives on in the closure.
}

let counter1 = makeCounter()
let counter2 = makeCounter()

print("Counter1: ", counter1(), counter1())  // Counter1:  1 2
print("Counter2: ", counter2(), counter2())  // Counter2:  1 2
print("Counter1: ", counter1(), counter1())  // Counter1:  3 4
</code>```

If n were copied into the closure, this couldn't work. The whole point is the closure captures and can modify state outside itself. This is what separates a closure (which "closes over" the scope where it was created) and an anonymous function (which does not).

(The history of the term "close over" is kind of obscure. It refers to the idea that the lambda expression's free variables have been "closed," but IMO "bound" would be a much more obvious term, and is how we describe this everywhere else. But the term "closure" has been used for decades, so here we are.)

Note that it is possible to get copy semantics. You just have to ask for it:

```<code>func foo(){

    var wtf = Wtf()

    DispatchQueue.global().async { [wtf] in // Make a local `let` copy
        var wtf = wtf   // To modify it, we need to make a `var` copy
        wtf.x = 5
    }

    Thread.sleep(forTimeInterval: 2)
    // Prints 1 as you expected
    print("x = \(wtf.x)")
}
</code>```

In C++, lambdas have to be explicit about how to capture values, by binding or by copying. But in Swift, they chose to make binding the default.

As to why you're allowed to access wtf after it's been captured by the closure, that's just a lack of move semantics in Swift. There's no way in Swift today to express "this variable has been passed to something else and may no longer be accessed in this scope." That's a known limitation of the language, and a lot of work is going into fix it. See The Ownership Manifesto for more.

Body:
It seems logical to me that escaping closures would capture structs by copying. But if that was the case, the following code makes no sense and should not compile:

struct Wtf {
    var x = 1
}

func foo(){

    var wtf = Wtf()

    DispatchQueue.global().async {
        wtf.x = 5
    }

    Thread.sleep(forTimeInterval: 2)
    print("x = \(wtf.x)")
}

Yet it compiles successfully and even prints 5 when foo is called. How is this possible?

Body:
While it might make sense for a struct to be copied, as your code demonstrates, it is not. That's a powerful tool. For example:

func makeCounter() -> () -> Int {
    var n = 0
    return {
        n += 1  // This `n` is the same `n` from the outer scope
        return n
    }

    // At this point, the scope is gone, but the `n` lives on in the closure.
}

let counter1 = makeCounter()
let counter2 = makeCounter()

print("Counter1: ", counter1(), counter1())  // Counter1:  1 2
print("Counter2: ", counter2(), counter2())  // Counter2:  1 2
print("Counter1: ", counter1(), counter1())  // Counter1:  3 4

If n were copied into the closure, this couldn't work. The whole point is the closure captures and can modify state outside itself. This is what separates a closure (which "closes over" the scope where it was created) and an anonymous function (which does not).

(The history of the term "close over" is kind of obscure. It refers to the idea that the lambda expression's free variables have been "closed," but IMO "bound" would be a much more obvious term, and is how we describe this everywhere else. But the term "closure" has been used for decades, so here we are.)

Note that it is possible to get copy semantics. You just have to ask for it:

func foo(){

    var wtf = Wtf()

    DispatchQueue.global().async { [wtf] in // Make a local `let` copy
        var wtf = wtf   // To modify it, we need to make a `var` copy
        wtf.x = 5
    }

    Thread.sleep(forTimeInterval: 2)
    // Prints 1 as you expected
    print("x = \(wtf.x)")
}

In C++, lambdas have to be explicit about how to capture values, by binding or by copying. But in Swift, they chose to make binding the default.

As to why you're allowed to access wtf after it's been captured by the closure, that's just a lack of move semantics in Swift. There's no way in Swift today to express "this variable has been passed to something else and may no longer be accessed in this scope." That's a known limitation of the language, and a lot of work is going into fix it. See The Ownership Manifesto for more.


问:
use ftp to transfer a file between Mininet hosts
I want to start an ftp server on one Mininet host and access that server from another host, Here is what I've tried:

Installing vsftpd on the Mininet VM, the server works fine to access
the VM itself but I cannot figure out how to run the server on a
specific host, say a host with IP = 10.0.0.10.

I tried what this thread suggested, the second answer seemed
promising but sadly it did not work, after running the commands I
get the following error on the destination-host:

[connection refused]

To sum up: I would like to send a file between two Mininet hosts using ftp, I fail to start an ftp server on any specific host.

I am using Ubuntu 20.04 as my Mininet VM.

答:
open the shell of the exact host by:

xterm "hostname"

then install your ftp server and start it.


问:
I've created a nested table. Is it possible to make a query on the table that really memorize the data of the nested table (STUDEN_NT_TAB)
```<code>CREATE TYPE STUDENT_T AS OBJECT (
   NOME  VARCHAR2(30),
   COGNOME VARCHAR2(20),
   MATRICOLA INT(6));

CREATE TYPE STUDENT_NT IS TABLE OF STUDENT_T;

CREATE TABLE CORSO_DI_LAUREA (
   NOME_CORSO VARCHAR2(50),
   STUDENTI STUDENT_NT )
NESTED TABLE STUDENTI STORE AS STUDEN_NT_TAB;
</code>```

答:
Check out https://asktom.oracle.com/pls/apex/asktom.search%3Ftag%3Daccessing-nested-tables-elements.

From that page we can see that your query would be somthing on the order of:

```<code>select nome_corso from coroso_id_laurea, table(studenti)
</code>```

I highly agree with what they say immediately after the example:

"Finally, while you can store multiple values using nested tables, in
the vast majority of cases you're better off using regular tables
instead. This makes it easier to query and work with your data!"

I have done some experimentation with nested tables. For me they became a nightmare of complexity so I switched back to the standard relational model.

Body:
Check out https://asktom.oracle.com/pls/apex/asktom.search%3Ftag%3Daccessing-nested-tables-elements.

From that page we can see that your query would be somthing on the order of:

select nome_corso from coroso_id_laurea, table(studenti)

I highly agree with what they say immediately after the example:

"Finally, while you can store multiple values using nested tables, in
the vast majority of cases you're better off using regular tables
instead. This makes it easier to query and work with your data!"

I have done some experimentation with nested tables. For me they became a nightmare of complexity so I switched back to the standard relational model.


问:
is this syntax correct in jquery
is the syntax of the jquery correct?

the first two lines in the code of jquery

```<code>$("input[name='title']").val(json.title);
$("input[name='age']").val(json.age);
</code>```

is two insert data in the forms

the next line is to display all the echoed elements in the server:

```<code>$('#age').html(json).show();//at age part of the html
</code>```

the first two lines inserting elements in the form works fine,but displaying the echo elements does not work fine..is there anything wrong in the code??

Code:

```<code>$(document).ready(function(){
    $("#button1").click(function(){
        $.post(
            'script.php',
            { id: $('input[name="id"]', '#myForm').val() },
            function(json) {
                $("input[name='title']").val(json.title);
                $("input[name='age']").val(json.age);
                $('#age').html(json).show();
            },
            "json"
        );
    });
 });

 <div id="age"></div>
</code>```

答:
Your problem is in this line:

```<code>$('#age').html(json).show();
</code>```

The html() function is expectiong a string. You're passing it the JSON object that you got back.

Title: is this syntax correct in jquery

Body:
is the syntax of the jquery correct?

the first two lines in the code of jquery

$("input[name='title']").val(json.title);
$("input[name='age']").val(json.age);

is two insert data in the forms

the next line is to display all the echoed elements in the server:

$('#age').html(json).show();//at age part of the html

the first two lines inserting elements in the form works fine,but displaying the echo elements does not work fine..is there anything wrong in the code??

Code:

$(document).ready(function(){
    $("#button1").click(function(){
        $.post(
            'script.php',
            { id: $('input[name="id"]', '#myForm').val() },
            function(json) {
                $("input[name='title']").val(json.title);
                $("input[name='age']").val(json.age);
                $('#age').html(json).show();
            },
            "json"
        );
    });
 });

Body:
Your problem is in this line:

$('#age').html(json).show();

The html() function is expectiong a string. You're passing it the JSON object that you got back.


问:
Ruby on Rail running apache show index of when accessing the site
I have recently updated to Apache 2.4, and I am using Ruby on Rail to run my application. Following the upgrade, the site shows a content as seen in the image below, and the error on the log file shows this error message. I have tried using the 'Bundle Install' and checked the permission but that hasn't helped. Any advice would be greatly appreciated. Thanks

```<code>[ 2022-02-07 07:47:24.5559 8104/7efc89c8f700 age/Cor/App/Implementation.cpp:304 ]: Could not spawn process for application /home/adminuser/hroot: An error occured while starting up the preloader.
  Error ID: ba7e6074
  Error details saved to: /tmp/passenger-error-RA01E9.html
  Message from application: libmysqlclient.so.18: cannot open shared object file: No such file or directory - /usr/local/rvm/gems/ruby-2.0.0-p353@hroot/gems/mysql2-0.3.14/lib/mysql2/mysql2.so (LoadError)
</code>```

```<code>             PassengerRuby /usr/local/rvm/gems/ruby-2.0.0-p353@hroot/wrappers/ruby
             SetEnv GEM_HOME /root/.gem/ruby/1.9.1
</code>```

答:
This error shows a problem with the shared objects. You probably updated MySQL/MariaDB libraries with Apache and new libraries are incompatible with your mysql2 gem build. The solution is simple:

First, ensure you are using the ruby-2.0.0-p353@hroot RVM environment.

Then, execute the following command:

```<code>gem install mysql2 --version 0.3.14
</code>```

This should rebuild your mysql2 gem for the new MySQL/MariaDB client libraries on your system.

Body:
I have recently updated to Apache 2.4, and I am using Ruby on Rail to run my application. Following the upgrade, the site shows a content as seen in the image below, and the error on the log file shows this error message. I have tried using the 'Bundle Install' and checked the permission but that hasn't helped. Any advice would be greatly appreciated. Thanks

[ 2022-02-07 07:47:24.5559 8104/7efc89c8f700 age/Cor/App/Implementation.cpp:304 ]: Could not spawn process for application /home/adminuser/hroot: An error occured while starting up the preloader.
  Error ID: ba7e6074
  Error details saved to: /tmp/passenger-error-RA01E9.html
  Message from application: libmysqlclient.so.18: cannot open shared object file: No such file or directory - /usr/local/rvm/gems/ruby-2.0.0-p353@hroot/gems/mysql2-0.3.14/lib/mysql2/mysql2.so (LoadError)

             PassengerRuby /usr/local/rvm/gems/ruby-2.0.0-p353@hroot/wrappers/ruby
             SetEnv GEM_HOME /root/.gem/ruby/1.9.1

Body:
This error shows a problem with the shared objects. You probably updated MySQL/MariaDB libraries with Apache and new libraries are incompatible with your mysql2 gem build. The solution is simple:

First, ensure you are using the ruby-2.0.0-p353@hroot RVM environment.

Then, execute the following command:

gem install mysql2 --version 0.3.14

This should rebuild your mysql2 gem for the new MySQL/MariaDB client libraries on your system.


问:
Maximum number in SQL
I'm having these schema
STUDENT (Sid, Name, City, Adm_date, Paper1, Paper2)

And I want to find the maximum number of students were admitted in which date and the city where maximum number of students lives.

I'm using these queries in ORACLE 11g Express Edition:
For City:

```<code>SELECT COUNT(Sid) AS No_of_students, City
FROM STUDENT
GROUP BY City
ORDER BY No_of_students DESC
LIMIT 1;
</code>```

And For Date:

```<code>SELECT COUNT(Sid) AS No_of_students, Adm_date
           FROM STUDENT
           GROUP BY Adm_date
           ORDER BY No_of_students DESC
            LIMIT 1;
</code>```

But here I'm getting error for both these tables:
ORA-00933: SQL command not properly ended

答:
Please try rownum with subquery (Since Limit is not available in Oracle):

For city wise:

```<code>select * from
(SELECT COUNT(Sid) AS No_of_students, City
FROM STUDENT
GROUP BY City
ORDER BY No_of_students DESC) where rownum=1
</code>```

For Adm_date wise:

```<code>select * from
(SELECT COUNT(Sid) AS No_of_students, Adm_date
FROM STUDENT
GROUP BY Adm_date
ORDER BY No_of_students DESC) where rownum=1
</code>```

Found a great article explaining the mechanism of selecting top-N rows using rownum:

https://blogs.oracle.com/oraclemagazine/post/on-rownum-and-limiting-results

Title: Maximum number in SQL

Body:
I'm having these schema
STUDENT (Sid, Name, City, Adm_date, Paper1, Paper2)

And I want to find the maximum number of students were admitted in which date and the city where maximum number of students lives.

I'm using these queries in ORACLE 11g Express Edition:
For City:

SELECT COUNT(Sid) AS No_of_students, City
FROM STUDENT
GROUP BY City
ORDER BY No_of_students DESC
LIMIT 1;

And For Date:

SELECT COUNT(Sid) AS No_of_students, Adm_date
           FROM STUDENT
           GROUP BY Adm_date
           ORDER BY No_of_students DESC
            LIMIT 1;

But here I'm getting error for both these tables:
ORA-00933: SQL command not properly ended

Body:
Please try rownum with subquery (Since Limit is not available in Oracle):

For city wise:

select * from
(SELECT COUNT(Sid) AS No_of_students, City
FROM STUDENT
GROUP BY City
ORDER BY No_of_students DESC) where rownum=1

For Adm_date wise:

select * from
(SELECT COUNT(Sid) AS No_of_students, Adm_date
FROM STUDENT
GROUP BY Adm_date
ORDER BY No_of_students DESC) where rownum=1

Found a great article explaining the mechanism of selecting top-N rows using rownum:

https://blogs.oracle.com/oraclemagazine/post/on-rownum-and-limiting-results


问:
Android - Hide all shown Toast Messages
How do I remove all toast messages currently displayed?

In my App, there is a list, when a user clicks on an item, a toast message is displayed,
10 items - 10 toast messages.

So if the user clicks 10 times, then presses the menu button, they have to wait for some seconds until they're able to read the menu option text.

It shouldn't be like that :)

答:
```<code>mToast=Toast.makeText(this, "", Toast.LENGTH_LONG);
        showToast.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {

                mToast.cancel();
                String text=null;
                if(ON)
                {
                    text="Toast is on";
                }
                else
                {
                    text="Toast is off";
                }
                mToast.setText(text);
                mToast.setDuration(Toast.LENGTH_SHORT);
                mToast.show();

            }
        });
</code>```

Title: Android - Hide all shown Toast Messages


问:
JPA: How to save from flux in reactive repository
Given a repository that extends ReactiveCrudRepository:

```<code>interface PersonRepo extends ReactiveCrudRepository<Person, Long> {
    // ...
}
</code>```

and a Person data class with Name and Age

```<code>class Person { ... }
</code>```

Should this client code not save my persons to the repository?

```<code>private void savePeople() {
    Person p1 = new Person(23L, "p1", 22);
    Person p2 = new Person(25L, "p2", 39);
    List<Person> peoples = new ArrayList<>();
    peoples.add(p1);
    peoples.add(p2);
    personRepository.saveAll(Flux.fromIterable(peoples));
}
</code>```

I can't find p1 or p2 in the H2 in-memory database. Why not?

答:
change you method signature to private Mono<Void> savePeople()

and then replace personRepository.saveAll(Flux.fromIterable(peoples)) with following

```<code>return personRepository.saveAll(Flux.fromIterable(peoples)).then();
</code>```

last statement is not going to be invoked until you subscribe to saveAll method returned Flux. follow above steps. you will see p1 & p2 in DB

Body:
Given a repository that extends ReactiveCrudRepository:

interface PersonRepo extends ReactiveCrudRepository<Person, Long> {
    // ...
}

and a Person data class with Name and Age

class Person { ... }

Should this client code not save my persons to the repository?

private void savePeople() {
    Person p1 = new Person(23L, "p1", 22);
    Person p2 = new Person(25L, "p2", 39);
    List<Person> peoples = new ArrayList<>();
    peoples.add(p1);
    peoples.add(p2);
    personRepository.saveAll(Flux.fromIterable(peoples));
}

I can't find p1 or p2 in the H2 in-memory database. Why not?

Body:
change you method signature to private Mono<Void> savePeople()

and then replace personRepository.saveAll(Flux.fromIterable(peoples)) with following

return personRepository.saveAll(Flux.fromIterable(peoples)).then();

last statement is not going to be invoked until you subscribe to saveAll method returned Flux. follow above steps. you will see p1 & p2 in DB


问:
Cost of storing AMI
I understand Amazon will charge per GB provisioned EBS storage. If I create AMI of my instance, does this mean my EBS volume will be duplicated, and hence incur additional cost?

Is there other cost charge in creating and storing an AMI (Amazon Machine Image)?

答:
In short, yes, you will incur additional charges, but at a less rate, namely, EBS snapshot storage rate.  Provisioned EBS is the 'live' HD that will be charged at $0.10 per GB per month if using standard SSD (gp2, USA east pricing for 2022 used throughout).  And if you provisioned 50 GB, you will be fully charged for that 50 GB, even if you are only using 5% of it.  The charges will incur even if you forget to attach to an EC2 instance. $5 per month in this case.

When you create an AMI, AWS will create a snapshot in the background.  This snapshot is viewable under EBS Snapshots and will not be deletable as long as that AMI is in existence.  You will get an error if you try to delete this snapshot.  Snapshots cost less than 'provisioned' EBS at $0.05 per GB per month, and since snapshots ignore empty blocks, it will be shrunk to used size, so if you are only using 5% of 50GB, the snapshot should only be around 2.5 GB.  $0.13 per month in this case.  No other charges.

If you are creating a lot of these, it can get expensive very quickly, so some people save these AMIs into S3, which is cheaper than EBS snapshots.  This is somewhat advanced and as far as I know, it can only be done via AWS CLI, and not in the console.  You use a command called aws ec2 create-store-image-task and you have to specify the destination bucket name, and make sure permissions for S3, EBS and EC2 will all allow it.  More detail at the official AWS documentation.  This would reduce the cost to about $0.023 per GB per month.  There are other changes relating to this method, i.e. EBS Direct API, but it is not much and you can look it up in the documentations.

Recently in November 2021, AWS released archived function for EBS snapshots, which allows you to archive your snapshots for a minimum of 90 days for $0.0125. You do have to pay $0.03 per GB for restoring the data.  However, this is designed for EBS backups (e.g. daily backups using snapshots) and you cannot archive an EBS snapshot that is associated with an AMI.  You will get an error: Failed to archive snapshot... snap-xyz is in use by ami-123.

Below is an excerpt of an actual AWS bill that will explain it in a visual sense.

Title: Cost of storing AMI


问:
Redis master slave replication network latency
which network delay is acceptable for Redis master-slave replication? Which network latency is acceptable?</p>

答:
It's a complex mix of the number of write operations, the size of the write operations and the number of operations on the master.  The very short answer is keep the replicas as close a possible to the master.

You can observe the replica flushing and issuing a full resync command when you have exceeded the capacity of the replication.

You can also tune the replication buffers if the latency between the two nodes is high to mitigate any issues.


问:
Rails 3.1 private gems installation
I have a private gem, I added to my gemfile

gem 'saml-response', '0.0.0', :path =>"#{File.expand_path(FILE)}/../vendor/gems/"

Then bundle install it, and the bundle gets installed in:

```<code>DANIELs-MacBook-Air:Authy-Google-SSO dani$ bundle show saml-response
 /Users/dani/Development/authy/Authy-Google-SSO/vendor/gems
</code>```

But rails 3.1 seems not no load any gems from vendor/gems

```<code>ruby-1.9.2-p290 :001 > require 'saml-response'
LoadError: no such file to load -- saml-response
</code>```

So if vendor/gems are not loaded why is bundler installing the gem there.

答:
Why the path magic?

Simply:

```<code>gem "yourgem", :path => "vendor/gems/yourgem"
</code>```

will work, and yeah, it will load from there.

It appears to be your path.  You're pointing to your gems directory but you need to point to directory of the gem itself.

```<code># not
:path => "vendor/gems"

# but rather
:path => "vendor/gems/saml-response"
</code>```

Title: Rails 3.1 private gems installation

Body:
I have a private gem, I added to my gemfile

gem 'saml-response', '0.0.0', :path =>"#{File.expand_path(FILE)}/../vendor/gems/"

Then bundle install it, and the bundle gets installed in:

DANIELs-MacBook-Air:Authy-Google-SSO dani$ bundle show saml-response
 /Users/dani/Development/authy/Authy-Google-SSO/vendor/gems

But rails 3.1 seems not no load any gems from vendor/gems

ruby-1.9.2-p290 :001 > require 'saml-response'
LoadError: no such file to load -- saml-response

So if vendor/gems are not loaded why is bundler installing the gem there.

Body:
Why the path magic?

Simply:

gem "yourgem", :path => "vendor/gems/yourgem"

will work, and yeah, it will load from there.

It appears to be your path.  You're pointing to your gems directory but you need to point to directory of the gem itself.

# not
:path => "vendor/gems"

# but rather
:path => "vendor/gems/saml-response"


问:
DHL Tracking HTML Form?
Does anyone know if I can create an HTML Form to search the DHL tracking website?
http://www.dhl.co.uk/en/express/tracking.html

I have tried using the following but get the error 'down for maintenance':

```<code><!DOCTYPE html>
<!--[if IE]>
<![endif]-->
<html><head><meta charset="utf-8" />
</head>
<body>

<form action="http://www.dhl.co.uk/content/gb/en/express/tracking.shtml?brand=DHL&AWB=1212121212" method="post">

<input type="submit" value="go" />

</form>

</body>

</html>
</code>```

Will I have to use the API?

答:
Big shout out to @WeezHard for dropping that form. I figured his solution is directed at DHL USA, so if you want a global DHL tracking form you can use the follow code.</p>
```<code><form name="form1" method="get" action="https://www.dhl.com/global-en/home/tracking/tracking-express.html?submit=1&tracking-id=" target="_blank">
<input type=hidden name=submit VALUE="1">
<input type="text" name="tracking-id" size="10" placeholder="Enter your DHL waybill number here..."><br>
<input type="submit" value="Track">
</form>
</code>```

Title: DHL Tracking HTML Form?

Body:
Does anyone know if I can create an HTML Form to search the DHL tracking website?
http://www.dhl.co.uk/en/express/tracking.html

I have tried using the following but get the error 'down for maintenance':

<!DOCTYPE html>

<meta charset="utf-8" />

<form action="http://www.dhl.co.uk/content/gb/en/express/tracking.shtml?brand=DHL&AWB=1212121212" method="post">

<input type="submit" value="go" />

</form>

Will I have to use the API?

Body:
Big shout out to @WeezHard for dropping that form. I figured his solution is directed at DHL USA, so if you want a global DHL tracking form you can use the follow code.

<form name="form1" method="get" action="https://www.dhl.com/global-en/home/tracking/tracking-express.html?submit=1&tracking-id=" target="_blank">
<input type=hidden name=submit VALUE="1">
<input type="text" name="tracking-id" size="10" placeholder="Enter your DHL waybill number here..."><br>
<input type="submit" value="Track">
</form>


问:
How do I download and save an inbuilt library from R in my desktop as a .Rdata file?
everyone! I am kinda new to R and was trying to download the Women data from the inbuilt Data set library in R. I understand that I have to use the save function to do so, but i am uncertain how.</p>

答:
Running:

```<code>write.csv(x = data("women"), file = "women.csv")
</code>```

will save the women.csv in your working directory. You can check location by running getwd() or specify path using the file argument.

Body:
Running:

write.csv(x = data("women"), file = "women.csv")

will save the women.csv in your working directory. You can check location by running getwd() or specify path using the file argument.


问:
Controlling the labels on the primary and secondary axis with facet_wrap()
The following code produces a single plot:

```<code>data <- tibble(model = rep(c("model 0", "model I", "model II", "model III", "model IV"),3),
                year = c(rep('2005-2009', 5), rep('2010-2014',5), rep('2015-2017',5)),
                value = c(0.0, 10.4, 30.7, 26.7, 32.2, 0.0, 9.9, 31.0, 26.5, 32.6, 0.0, 19.1, 29.6, 25.6, 25.7),
                unknown = c(rep(30,5), rep(40,5), rep(27,5)),
                region = 'Asia')

# Numeric year
data$year_num <- as.numeric(factor(data$year))
# Labels for primary scale
labels <- levels(factor(data$year))
# Labels for secondary scale
dup_labels <- distinct(data, year, unknown) %>% tibble::deframe()

p1 <- ggplot(data, aes(fill=model, x=value, y = year_num)) +
  geom_bar(stat='identity', position = position_fill(reverse = TRUE), orientation = "y") +
  scale_fill_grey(start=0.8, end=0.2) +
  theme_bw() +
  ggtitle('Model') +
  xlab('') + ylab('') +
  theme(legend.position="bottom",
        plot.title = element_text(hjust = 0.5),
        legend.title=element_blank(),
        text = element_text(family = "serif")
  ) +
  scale_x_continuous(labels = percent_format(scale = 100)) +
  scale_y_continuous(breaks = seq_along(labels), labels = labels, sec.axis = dup_axis(labels = dup_labels))

p1
</code>```

Next, I would like to produce several plots with facet_wrap but I have a challenge controlling the labels. I am not quite sure how to iterate the labels for the corresponding plot.

Eg., if I want to plot the following data with facet_wrap(~region, dir = 'v', nrow = 2):

```<code>data1 <- tibble(model = rep(c("model 0", "model I", "model II", "model III", "model IV"),3),
                year = c(rep('2005-2009', 5), rep('2010-2014',5), rep('2015-2017',5)),
                value = c(0.0, 10.4, 30.7, 26.7, 32.2, 0.0, 9.9, 31.0, 26.5, 32.6, 0.0, 19.1, 29.6, 25.6, 25.7),
                unknown = c(rep(30,5), rep(40,5), rep(27,5)),
                region = 'Asia')

data2 <- tibble(model = rep(c("model 0", "model I", "model II", "model III", "model IV"),3),
                year = c(rep('2005-2009', 5), rep('2010-2014',5), rep('2015-2017',5)),
                value = c(0.4, 15.0, 25.6, 20.6, 38.3, 1.1, 15, 13, 14.6, 56.9, 0.8, 19.8, 22, 18.8,38.1),
                unknown = c(rep(28,5), rep(35,5), rep(17,5)),
                region = 'Europe')

data <- rbind(data1, data2)

</code>```

I reckon that I need to have some sort of iteration but I can't really figure it out for this problem.

答:
One option would be the ggh4x package which allows to set a scale for each facet via ggh4x::facetted_pos_scales.

To this end, make e.g. a list of labels for your dup_axis then add a scale with the respective dup_labels to each facet via ggh4x::facetted_pos_scales:

library(ggplot2)
library(ggh4x)
library(scales)
library(dplyr)

# Numeric year
data$year_num <- as.numeric(factor(data$year))
# Labels for primary scale
labels <- levels(factor(data$year))
# Make a list of labels for secondary scale by region
dup_labels <- data %>%
  split(.$region) %>%
  lapply(function(x) distinct(x, year, unknown) %>% tibble::deframe())

p <- ggplot(data, aes(fill=model, x=value, y = year_num)) +
  geom_bar(stat='identity', position = position_fill(reverse = TRUE), orientation = "y") +
  scale_fill_grey(start=0.8, end=0.2) +
  theme_bw() +
  ggtitle('Model') +
  xlab('') + ylab('') +
  theme(legend.position="bottom",
        plot.title = element_text(hjust = 0.5),
        legend.title=element_blank(),
        text = element_text(family = "serif")
  ) +
  scale_x_continuous(labels = percent_format(scale = 100)) +
  facet_wrap(~region, nrow = 2, scales = "free_y")

p +
  facetted_pos_scales(
    y = list(
      scale_y_continuous(breaks = seq_along(labels), labels = labels, sec.axis = dup_axis(labels = dup_labels[["Asia"]])),
      scale_y_continuous(breaks = seq_along(labels), labels = labels, sec.axis = dup_axis(labels = dup_labels[["Europe"]])))
  )
```
<p>Or instead of duplicating the code to add the scale for each region you could make use of e.g. <code>lapply</code>:</p>
<pre class="lang-r prettyprint-override"><code>p + facetted_pos_scales(y = lapply(dup_labels, function(x) scale_y_continuous(breaks = seq_along(labels), labels = labels, sec.axis = dup_axis(labels = x))))
</code>```

Body:
The following code produces a single plot:

data <- tibble(model = rep(c("model 0", "model I", "model II", "model III", "model IV"),3),
                year = c(rep('2005-2009', 5), rep('2010-2014',5), rep('2015-2017',5)),
                value = c(0.0, 10.4, 30.7, 26.7, 32.2, 0.0, 9.9, 31.0, 26.5, 32.6, 0.0, 19.1, 29.6, 25.6, 25.7),
                unknown = c(rep(30,5), rep(40,5), rep(27,5)),
                region = 'Asia')

# Numeric year
data$year_num <- as.numeric(factor(data$year))
# Labels for primary scale
labels <- levels(factor(data$year))
# Labels for secondary scale
dup_labels <- distinct(data, year, unknown) %>% tibble::deframe()

p1 <- ggplot(data, aes(fill=model, x=value, y = year_num)) +
  geom_bar(stat='identity', position = position_fill(reverse = TRUE), orientation = "y") +
  scale_fill_grey(start=0.8, end=0.2) +
  theme_bw() +
  ggtitle('Model') +
  xlab('') + ylab('') +
  theme(legend.position="bottom",
        plot.title = element_text(hjust = 0.5),
        legend.title=element_blank(),
        text = element_text(family = "serif")
  ) +
  scale_x_continuous(labels = percent_format(scale = 100)) +
  scale_y_continuous(breaks = seq_along(labels), labels = labels, sec.axis = dup_axis(labels = dup_labels))

p1

Next, I would like to produce several plots with facet_wrap but I have a challenge controlling the labels. I am not quite sure how to iterate the labels for the corresponding plot.

Eg., if I want to plot the following data with facet_wrap(~region, dir = 'v', nrow = 2):

data1 <- tibble(model = rep(c("model 0", "model I", "model II", "model III", "model IV"),3),
                year = c(rep('2005-2009', 5), rep('2010-2014',5), rep('2015-2017',5)),
                value = c(0.0, 10.4, 30.7, 26.7, 32.2, 0.0, 9.9, 31.0, 26.5, 32.6, 0.0, 19.1, 29.6, 25.6, 25.7),
                unknown = c(rep(30,5), rep(40,5), rep(27,5)),
                region = 'Asia')

data2 <- tibble(model = rep(c("model 0", "model I", "model II", "model III", "model IV"),3),
                year = c(rep('2005-2009', 5), rep('2010-2014',5), rep('2015-2017',5)),
                value = c(0.4, 15.0, 25.6, 20.6, 38.3, 1.1, 15, 13, 14.6, 56.9, 0.8, 19.8, 22, 18.8,38.1),
                unknown = c(rep(28,5), rep(35,5), rep(17,5)),
                region = 'Europe')

data <- rbind(data1, data2)

I reckon that I need to have some sort of iteration but I can't really figure it out for this problem.

Body:
One option would be the ggh4x package which allows to set a scale for each facet via ggh4x::facetted_pos_scales.

To this end, make e.g. a list of labels for your dup_axis then add a scale with the respective dup_labels to each facet via ggh4x::facetted_pos_scales:

library(ggplot2)
library(ggh4x)
library(scales)
library(dplyr)

# Numeric year
data$year_num <- as.numeric(factor(data$year))
# Labels for primary scale
labels <- levels(factor(data$year))
# Make a list of labels for secondary scale by region
dup_labels <- data %>%
  split(.$region) %>%
  lapply(function(x) distinct(x, year, unknown) %>% tibble::deframe())

p <- ggplot(data, aes(fill=model, x=value, y = year_num)) +
  geom_bar(stat='identity', position = position_fill(reverse = TRUE), orientation = "y") +
  scale_fill_grey(start=0.8, end=0.2) +
  theme_bw() +
  ggtitle('Model') +
  xlab('') + ylab('') +
  theme(legend.position="bottom",
        plot.title = element_text(hjust = 0.5),
        legend.title=element_blank(),
        text = element_text(family = "serif")
  ) +
  scale_x_continuous(labels = percent_format(scale = 100)) +
  facet_wrap(~region, nrow = 2, scales = "free_y")

p +
  facetted_pos_scales(
    y = list(
      scale_y_continuous(breaks = seq_along(labels), labels = labels, sec.axis = dup_axis(labels = dup_labels[["Asia"]])),
      scale_y_continuous(breaks = seq_along(labels), labels = labels, sec.axis = dup_axis(labels = dup_labels[["Europe"]])))
  )

Or instead of duplicating the code to add the scale for each region you could make use of e.g. lapply:

p + facetted_pos_scales(y = lapply(dup_labels, function(x) scale_y_continuous(breaks = seq_along(labels), labels = labels, sec.axis = dup_axis(labels = x))))


问:
`docker-compose up` doesn't create a persistent volume for PostgreSQL container
I am trying to create a persistent volume storage for a postgres docker container. Because I will have some other services within this docker environment, I am using docker-compose to start the container.

The contents of my docker-compose.yml file are:

```<code>version: "3.8"

services:
  db:
    image: postgres:12.3
    volumes:
      - ./postgres-data:/var/lib/posgresql/data
    environment:
      - POSTGRES_NAME=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres

volumes:
  postgres-data:
</code>```

I run the command:

```<code>docker-compose up
</code>```

Now, based on the documentation, and this example, I expect to have one persistent volume created, with its name including postgres-data (e.g., postgres-volume_postgres-data).

Instead, two volumes are created:

```<code>docker volume ls
</code>```

Output:

```<code>DRIVER    VOLUME NAME
local     a53a5b161f0fefca840e2f0cd2a97ad019864dea23c7f23f07c94e6be7ace601
local     postgres-volume_postgres-data
</code>```

Inspecting the volumes:

```<code>docker volume inspect a53a5b161f0fefca840e2f0cd2a97ad019864dea23c7f23f07c94e6be7ace601
</code>```

Output:

```<code>[
    {
        "CreatedAt": "2022-02-07T19:12:04Z",
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/a53a5b161f0fefca840e2f0cd2a97ad019864dea23c7f23f07c94e6be7ace601/_data",
        "Name": "a53a5b161f0fefca840e2f0cd2a97ad019864dea23c7f23f07c94e6be7ace601",
        "Options": null,
        "Scope": "local"
    }
]
</code>```

Inspecting the second volume:

```<code>docker volume inspect postgres-volume_postgres-data
</code>```

Output:

```<code>[
    {
        "CreatedAt": "2022-02-07T19:12:02Z",
        "Driver": "local",
        "Labels": {
            "com.docker.compose.project": "postgres-volume",
            "com.docker.compose.version": "1.29.2",
            "com.docker.compose.volume": "postgres-data"
        },
        "Mountpoint": "/var/lib/docker/volumes/postgres-volume_postgres-data/_data",
        "Name": "postgres-volume_postgres-data",
        "Options": null,
        "Scope": "local"
    }
]
</code>```

Of these two volumes only the a53a5b161f0fefca840e2f0cd2a97ad019864dea23c7f23f07c94e6be7ace601 is active and all the data seem to be stored within this volume.

The effect is that when I use docker-compose down, all data saved to the database when the container was running are lost, i.e., the data are not persisted, and they are not available after running the docker-compose up again.

What I am doing wrong?

(I am using macOS Big Sur, v.11.4.)

Docker & docker-compose versions:

```<code>➜  ~ docker --version
Docker version 20.10.7, build f0df350

➜  ~ docker-compose version
docker-compose version 1.29.2, build 5becea4c
docker-py version: 5.0.0
CPython version: 3.9.0
OpenSSL version: OpenSSL 1.1.1h  22 Sep 2020
</code>```

答:
What you're doing is called a 'bind mount' where a directory on the host is mapped to a directory in the container.

The syntax is slightly different if you want to create a volume. Do this instead

```<code>- postgres-data:/var/lib/posgresql/data
</code>```

(i.e. no path information before the volume name)

Body:
I am trying to create a persistent volume storage for a postgres docker container. Because I will have some other services within this docker environment, I am using docker-compose to start the container.

The contents of my docker-compose.yml file are:

version: "3.8"

services:
  db:
    image: postgres:12.3
    volumes:
      - ./postgres-data:/var/lib/posgresql/data
    environment:
      - POSTGRES_NAME=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres

volumes:
  postgres-data:

I run the command:

docker-compose up

Now, based on the documentation, and this example, I expect to have one persistent volume created, with its name including postgres-data (e.g., postgres-volume_postgres-data).

Instead, two volumes are created:

docker volume ls

Output:

DRIVER    VOLUME NAME
local     a53a5b161f0fefca840e2f0cd2a97ad019864dea23c7f23f07c94e6be7ace601
local     postgres-volume_postgres-data

Inspecting the volumes:

docker volume inspect a53a5b161f0fefca840e2f0cd2a97ad019864dea23c7f23f07c94e6be7ace601

Output:

[
    {
        "CreatedAt": "2022-02-07T19:12:04Z",
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/a53a5b161f0fefca840e2f0cd2a97ad019864dea23c7f23f07c94e6be7ace601/_data",
        "Name": "a53a5b161f0fefca840e2f0cd2a97ad019864dea23c7f23f07c94e6be7ace601",
        "Options": null,
        "Scope": "local"
    }
]

Inspecting the second volume:

docker volume inspect postgres-volume_postgres-data

Output:

[
    {
        "CreatedAt": "2022-02-07T19:12:02Z",
        "Driver": "local",
        "Labels": {
            "com.docker.compose.project": "postgres-volume",
            "com.docker.compose.version": "1.29.2",
            "com.docker.compose.volume": "postgres-data"
        },
        "Mountpoint": "/var/lib/docker/volumes/postgres-volume_postgres-data/_data",
        "Name": "postgres-volume_postgres-data",
        "Options": null,
        "Scope": "local"
    }
]

Of these two volumes only the a53a5b161f0fefca840e2f0cd2a97ad019864dea23c7f23f07c94e6be7ace601 is active and all the data seem to be stored within this volume.

The effect is that when I use docker-compose down, all data saved to the database when the container was running are lost, i.e., the data are not persisted, and they are not available after running the docker-compose up again.

What I am doing wrong?

(I am using macOS Big Sur, v.11.4.)

Docker & docker-compose versions:

➜  ~ docker --version
Docker version 20.10.7, build f0df350

➜  ~ docker-compose version
docker-compose version 1.29.2, build 5becea4c
docker-py version: 5.0.0
CPython version: 3.9.0
OpenSSL version: OpenSSL 1.1.1h  22 Sep 2020

Body:
What you're doing is called a 'bind mount' where a directory on the host is mapped to a directory in the container.

The syntax is slightly different if you want to create a volume. Do this instead

- postgres-data:/var/lib/posgresql/data

(i.e. no path information before the volume name)


问:
I'm having issues with my style in laravel
I'm getting crazy with this matter and seems i can't find a solution.
I started a laravel project and i'm unable to get the css working correctly.

I have created a new file named style.css in my resources/css, than i have linked that file to my app.css with @import 'style.css';.

The app.css is linked in my app.blade.php with  <link href="{{ asset('css/app.css') }}" rel="stylesheet">

Everything seems fine to my eyes, but the css in style.css doesn't work.

I've tried any solution that i know, and also looked several web pages and other older projects done but everything seems correct, probably is just because i'm really tired.

Does any one can help me to solve it?

Thank you

答:
The path of the method asset() ends in the public folder

you need to compile app.css by run this command "npm run dev"

if don't install npm before run "npm install" first


问:
How to pass the latitude and longitude values to the ns url as a arguments?
Iam developing one application.In that i use the google api for getting the location information.For that i use the CLLocationManager for getting the location latitude and longitude values.And my pblm is how to pass these latitude and longitude values to nsurl .ANd iam directly given the one location values to the url like below.

```<code> NSURL *URL = [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/search           /json?location=40.7143528,-74.0059731&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM"];
</code>```

I write this one in below method for get and pass the latitude and longitude values.

```<code>   - (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
}
</code>```

So please tell me how to pass the newlocation.Coordinates.latitude and newlocation.Coordinates.longitude to that url in that method.

With others suggestions i changed the code like below.

```<code>    - (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{

    NSString *address = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f, %f&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM", newLocation.lattitude, newLocation.longitude];
    NSURL *url = [NSURL URLFromString:address];
}
</code>```

This also gives the error like Exe_Bad_Access when the first line executed.SO please tell me how to write that one.

答:
```<code>-(void)getLocation{
    locationManager = [[CLLocationManager alloc] init] ;
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager startUpdatingLocation];

}

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation{

    NSString * lat = [[[NSString alloc] initWithFormat:@"%f", newLocation.coordinate.latitude]autorelease];
    NSString * lon = [[[NSString alloc] initWithFormat:@"%f", newLocation.coordinate.longitude]autorelease];

    [locationManager stopUpdatingLocation];

    //set google maps locations
    NSString * googleString = [NSString stringWithFormat:@"http://maps.google.com/maps?q=%@+%@",lat,lon];

}
</code>```

Body:
Iam developing one application.In that i use the google api for getting the location information.For that i use the CLLocationManager for getting the location latitude and longitude values.And my pblm is how to pass these latitude and longitude values to nsurl .ANd iam directly given the one location values to the url like below.

 NSURL *URL = [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/search           /json?location=40.7143528,-74.0059731&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM"];

I write this one in below method for get and pass the latitude and longitude values.

   - (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
}

So please tell me how to pass the newlocation.Coordinates.latitude and newlocation.Coordinates.longitude to that url in that method.

With others suggestions i changed the code like below.

    - (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{

    NSString *address = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f, %f&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM", newLocation.lattitude, newLocation.longitude];
    NSURL *url = [NSURL URLFromString:address];
}

This also gives the error like Exe_Bad_Access when the first line executed.SO please tell me how to write that one.


问:
Compare folder size and run script if the size changed
I am trying to write a code which will carry out something with the newly added file to the folder. So, the way I see it is to calculate the folder size, compare it with the one calculated ±10 mins ago, and then to do something with the newly added file if the size of the folder did change.

```<code>while (True):
    def get_size(start_path='/Users/.../Desktop/files'):
        total_size = 0
        for dirpath, dirnames, filenames in os.walk(start_path):
            for f in filenames:
                fp = os.path.join(dirpath, f)
                # skip if it is symbolic link
                if not os.path.islink(fp):
                    total_size += os.path.getsize(fp)

        return total_size

    print(get_size(), 'bytes')
    time.sleep(10)
</code>```

The code above calculates the size of the folder every 10 seconds. I don't know how to compare it to the previous size though :(

Please, help..

答:
This is a simple problem, that can be sobstituted with a minimum reproducible example this way:

```<code>while True:
    a = input() # How can I check if this is different from the previous input?
</code>```

Create a variable that stores the previous weight, this way:

```<code>old = get_size()
while True:
    new = get_size()
    if new != old:
        # Something changed
    old = new # You can do it since integers are immutable typed
</code>```

I would add a suggestion for you:

```<code>def get_size():
    ...
while True:
    ...
</code>```

This will make you avoid a waste of time and efficiency, since otherwise the get_size function gets redefined each time the while loop executes (every 10 seconds!).

Body:
I am trying to write a code which will carry out something with the newly added file to the folder. So, the way I see it is to calculate the folder size, compare it with the one calculated ±10 mins ago, and then to do something with the newly added file if the size of the folder did change.

while (True):
    def get_size(start_path='/Users/.../Desktop/files'):
        total_size = 0
        for dirpath, dirnames, filenames in os.walk(start_path):
            for f in filenames:
                fp = os.path.join(dirpath, f)
                # skip if it is symbolic link
                if not os.path.islink(fp):
                    total_size += os.path.getsize(fp)

        return total_size

    print(get_size(), 'bytes')
    time.sleep(10)

The code above calculates the size of the folder every 10 seconds. I don't know how to compare it to the previous size though :(

Please, help..

Body:
This is a simple problem, that can be sobstituted with a minimum reproducible example this way:

while True:
    a = input() # How can I check if this is different from the previous input?

Create a variable that stores the previous weight, this way:

old = get_size()
while True:
    new = get_size()
    if new != old:
        # Something changed
    old = new # You can do it since integers are immutable typed

I would add a suggestion for you:

def get_size():
    ...
while True:
    ...

This will make you avoid a waste of time and efficiency, since otherwise the get_size function gets redefined each time the while loop executes (every 10 seconds!).


问:
Python Requests and SSLContext
I'm trying to figure out how to specify an SSLContext with Request.

I have two functions which in theory should do the same, however the one with Requests doesn't work.

```<code>def func_OK(token):
    ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH,cafile='myCA.crt.pem')
    ctx.load_cert_chain(certfile='myprivate.pem')
    url = 'https://my_url.com'
    hdr = {"Content-Type": "application/json","Authorization":"Bearer "+token}
    data = '{"filterList":[{}]}'
    bdata = data.encode('utf-8')
    req = urllib.request.Request(url, headers=hdr)
    resp = urllib.request.urlopen(req, data=bdata, context=ctx)
    content = resp.read()
    data = json.loads(content.decode('utf-8'))
</code>```
```<code>def func_NOK(token):
    import requests
    url = 'https://my_url.com'
    hdr = {"Content-Type": "application/json","Authorization":"Bearer "+token}
    data = '{"filterList":[{}]}'
    bdata = data.encode('utf-8')
    resp = requests.post(url,headers=hdr, data={"filterList":[{}]})
</code>```

The only the difference between the two functions are the sslContext.
In the func_NOK, I try :

resp = requests.post(url,headers=hdr, data={"filterList":[{}]}, verify=False) - it doesn't work

resp = requests.post(url,headers=hdr, data={"filterList":[{}]}, cert=('myCA.crt.pem','myprivate.pem')) - it doesn't work

resp = requests.post(url,headers=hdr, data={"filterList":[{}]}, verify="concat_file.crt") with "concat_file.crt" file a concatenation of 'myCA.crt.pem' and 'myprivate.pem'

In any cases I have an SSL error.
For example, on my last example the error msg is :

```<code>requests.exceptions.ConnectionError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1131)
</code>```

I'm just trying to use an SSLContext with Requests.

答:
I find where my cacert.pem : /home/<soome_path>/pyEnv/myEnv/lib/python3.8/site-packages/certifi/cacert.pem

I concatenated the files :
myCA.crt.pem >> cacert.pem
myprivate.pem>> cacert.pem

then I specified the path using verify :
requests.post(...,verify='/home/<soome_path>/pyEnv/myEnv/lib/python3.8/site-packages/certifi/cacert.pem')

And I don't have the ssl error anymore.
However I retrieve an html msg instead of a json.
Maybe an issue on the parameters that I send to the endpoint.

Title: Python Requests and SSLContext

Body:
I'm trying to figure out how to specify an SSLContext with Request.

I have two functions which in theory should do the same, however the one with Requests doesn't work.

def func_OK(token):
    ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH,cafile='myCA.crt.pem')
    ctx.load_cert_chain(certfile='myprivate.pem')
    url = 'https://my_url.com'
    hdr = {"Content-Type": "application/json","Authorization":"Bearer "+token}
    data = '{"filterList":[{}]}'
    bdata = data.encode('utf-8')
    req = urllib.request.Request(url, headers=hdr)
    resp = urllib.request.urlopen(req, data=bdata, context=ctx)
    content = resp.read()
    data = json.loads(content.decode('utf-8'))

def func_NOK(token):
    import requests
    url = 'https://my_url.com'
    hdr = {"Content-Type": "application/json","Authorization":"Bearer "+token}
    data = '{"filterList":[{}]}'
    bdata = data.encode('utf-8')
    resp = requests.post(url,headers=hdr, data={"filterList":[{}]})

The only the difference between the two functions are the sslContext.
In the func_NOK, I try :

resp = requests.post(url,headers=hdr, data={"filterList":[{}]}, verify=False) - it doesn't work

resp = requests.post(url,headers=hdr, data={"filterList":[{}]}, cert=('myCA.crt.pem','myprivate.pem')) - it doesn't work

resp = requests.post(url,headers=hdr, data={"filterList":[{}]}, verify="concat_file.crt") with "concat_file.crt" file a concatenation of 'myCA.crt.pem' and 'myprivate.pem'

In any cases I have an SSL error.
For example, on my last example the error msg is :

requests.exceptions.ConnectionError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1131)

I'm just trying to use an SSLContext with Requests.


问:
Can you use AWS MGN (Application Migration) without an explicitly created access key and secret key?
I have a situation where I need to migrate an on-prem environment to AWS. The tool of choice is AWS MGN (Application Migration). I am following AWS's documentation on loading and using the agent on the source application:

https://docs.aws.amazon.com/mgn/latest/ug/windows-agent.html

The documentation clearly states the need for an access key and secret key. Our environment is set up with a root account with limited users and the team accesses the AWS environment in other accounts (e.g. dev/test/prod/etc.) via SSO. The MGN service also creates four roles:

AWSApplicationMigrationConversionServerRole

AWSApplicationMigrationMGHRole

AWSApplicationMigrationReplicationServerRole

AWSServiceRoleForApplicationMigrationService

I know you can use 'aws sts assume role' to glean off the keys needed, e.g.:

```<code>AWS_SESSION_TOKEN=$(echo "$test_assume_role_json" | jq -r '.Credentials.SessionToken')
export AWS_SESSION_TOKEN
AWS_ACCESS_KEY_ID=$(echo "$test_assume_role_json" | jq -r '.Credentials.AccessKeyId')
export AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY=$(echo "$test_assume_role_json" | jq -r '.Credentials.SecretAccessKey')
</code>```

These roles are create by AWS and I can't edit them to try and give my SSO user access (I can't 'aws sts assume role' these from the CLI), so assuming these roles directly is not possible. I also cannot create a role that uses AWS-managed policies.

I am not really sure if what I want to do is possible, or if there is a simple solution that I'm just not seeing.

EDIT: I was actually successful in creating a test role with the following policies on the account that I wanted to migrate into:

AdministratorAccess (AWS managed policy)

AWSApplicationMigrationAgentPolicy (AWS managed policy)

AWSApplicationMigrationFullAccess (AWS managed policy)

AWSApplicationMigrationMGHAccess (AWS managed policy)

AWSApplicationMigrationReadOnlyAccess (AWS managed policy)

AWSApplicationMigrationEC2Access (AWS managed policy)

AWSApplicationMigrationConversionServerPolicy (AWS managed policy)

AWSApplicationMigrationReplicationServerPolicy (AWS managed policy)

I then ran assume-role to get the access key and secret key :

```<code>C:\>aws sts assume-role --role-arn "arn:aws:iam::<REDACTED>:role/ApplicationMigrationTester" --role-session-name test --profile test
{
    "Credentials": {
        "AccessKeyId": "<REDACTED>",
        "SecretAccessKey": "<REDACTED>",
        "SessionToken": "<REDACTED>",
        "Expiration": "2021-07-15T22:55:08+00:00"
    },
    "AssumedRoleUser": {
        "AssumedRoleId": "<REDACTED>":test",
        "Arn": "arn:aws:sts::<REDACTED>:assumed-role/ApplicationMigrationTester/test"
    }
}
</code>```

I tried to run the agent again as Administrator using those vaules when prompted:

```<code>C:\>.\AwsReplicationWindowsInstaller.exe
The installation of the AWS Replication Agent has started.
AWS Region Name: us-east-1
AWS Access Key ID: <REDACTED>
AWS Secret Access Key:
Verifying that the source server has enough free disk space to install the AWS Replication Agent.
(a minimum of 2 GB of free disk space is required)
Identifying volumes for replication.
Choose the disks you want to replicate. Your disks are: c:
To replicate some of the disks, type the path of the disks, separated with a comma (for example, C:,D:). To replicate all disks, press Enter:
Disk to replicate identified: c:0 of size 620 GiB
All volumes for replication were successfully identified.
Downloading the AWS Replication Agent onto the source server...
Failed to validate AWS credentials
Installation failed.
Learn more about installation issues in our documentation at https://docs.aws.amazon.com/mgn/latest/ug/Troubleshooting-Agent-Issues.html#Error-Installation-Failed
Press Enter to close...
</code>```

As you can see, it errored out. I put in a ticket to AWS to see if my approach is even currently feasible. When they respond, I will update.

答:
You only should provide the credentials from the command line (powerShell or CMD)</p>
```<code>C:\Downloads>.\AwsReplicationWindowsInstaller.exe --region us-east-1 --aws-access-key-id AKIA4HN2LIGPIERPMPXT --aws-secret-access-key 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
</code>```

Body:
I have a situation where I need to migrate an on-prem environment to AWS. The tool of choice is AWS MGN (Application Migration). I am following AWS's documentation on loading and using the agent on the source application:

https://docs.aws.amazon.com/mgn/latest/ug/windows-agent.html

The documentation clearly states the need for an access key and secret key. Our environment is set up with a root account with limited users and the team accesses the AWS environment in other accounts (e.g. dev/test/prod/etc.) via SSO. The MGN service also creates four roles:

AWSApplicationMigrationConversionServerRole

AWSApplicationMigrationMGHRole

AWSApplicationMigrationReplicationServerRole

AWSServiceRoleForApplicationMigrationService

I know you can use 'aws sts assume role' to glean off the keys needed, e.g.:

AWS_SESSION_TOKEN=$(echo "$test_assume_role_json" | jq -r '.Credentials.SessionToken')
export AWS_SESSION_TOKEN
AWS_ACCESS_KEY_ID=$(echo "$test_assume_role_json" | jq -r '.Credentials.AccessKeyId')
export AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY=$(echo "$test_assume_role_json" | jq -r '.Credentials.SecretAccessKey')

These roles are create by AWS and I can't edit them to try and give my SSO user access (I can't 'aws sts assume role' these from the CLI), so assuming these roles directly is not possible. I also cannot create a role that uses AWS-managed policies.

I am not really sure if what I want to do is possible, or if there is a simple solution that I'm just not seeing.

EDIT: I was actually successful in creating a test role with the following policies on the account that I wanted to migrate into:

AdministratorAccess (AWS managed policy)

AWSApplicationMigrationAgentPolicy (AWS managed policy)

AWSApplicationMigrationFullAccess (AWS managed policy)

AWSApplicationMigrationMGHAccess (AWS managed policy)

AWSApplicationMigrationReadOnlyAccess (AWS managed policy)

AWSApplicationMigrationEC2Access (AWS managed policy)

AWSApplicationMigrationConversionServerPolicy (AWS managed policy)

AWSApplicationMigrationReplicationServerPolicy (AWS managed policy)

I then ran assume-role to get the access key and secret key :

C:\>aws sts assume-role --role-arn "arn:aws:iam::<REDACTED>:role/ApplicationMigrationTester" --role-session-name test --profile test
{
    "Credentials": {
        "AccessKeyId": "<REDACTED>",
        "SecretAccessKey": "<REDACTED>",
        "SessionToken": "<REDACTED>",
        "Expiration": "2021-07-15T22:55:08+00:00"
    },
    "AssumedRoleUser": {
        "AssumedRoleId": "<REDACTED>":test",
        "Arn": "arn:aws:sts::<REDACTED>:assumed-role/ApplicationMigrationTester/test"
    }
}

I tried to run the agent again as Administrator using those vaules when prompted:

C:\>.\AwsReplicationWindowsInstaller.exe
The installation of the AWS Replication Agent has started.
AWS Region Name: us-east-1
AWS Access Key ID: <REDACTED>
AWS Secret Access Key:
Verifying that the source server has enough free disk space to install the AWS Replication Agent.
(a minimum of 2 GB of free disk space is required)
Identifying volumes for replication.
Choose the disks you want to replicate. Your disks are: c:
To replicate some of the disks, type the path of the disks, separated with a comma (for example, C:,D:). To replicate all disks, press Enter:
Disk to replicate identified: c:0 of size 620 GiB
All volumes for replication were successfully identified.
Downloading the AWS Replication Agent onto the source server...
Failed to validate AWS credentials
Installation failed.
Learn more about installation issues in our documentation at https://docs.aws.amazon.com/mgn/latest/ug/Troubleshooting-Agent-Issues.html#Error-Installation-Failed
Press Enter to close...

As you can see, it errored out. I put in a ticket to AWS to see if my approach is even currently feasible. When they respond, I will update.

Body:
You only should provide the credentials from the command line (powerShell or CMD)

C:\Downloads>.\AwsReplicationWindowsInstaller.exe --region us-east-1 --aws-access-key-id AKIA4HN2LIGPIERPMPXT --aws-secret-access-key j5KHRK8GVywxk39JqaPAayCxQbrP2PeHSC2GcuNW


问:
Sass .scss: Nesting and multiple classes?
I'm using Sass (.scss) for my current project.

Following example:

HTML

```<code><div class="container desc">
    <div class="hello">
        Hello World
    </div>
</div>
</code>```

SCSS

.container {
    background:red;
    color:white;

    .hello {
        padding-left:50px;
    }
}
```

<p>This works great. </p>

<p>Can I handle multiple classes while using nested styles.</p>

<p>In the sample above I'm talking about this:</p>

<p><strong>CSS</strong></p>

<pre class="lang-css prettyprint-override"><code>.container.desc {
    background:blue;
}
</code>```

In this case all div.container would normally be red but div.container.desc would be blue.

How can I nest this inside container with Sass?

答:
this worked for me</p>
```<code><div class="container">
  <div class="desc">
    desc
  </div>
  <div class="asc">
    asc
  </div>
</div>

.container{
  &.desc {
    background: blue;
  }
  &.asc {
    background: red;
  }
}
</code>```

Body:
I'm using Sass (.scss) for my current project.

Following example:

HTML

        Hello World

SCSS

.container {
    background:red;
    color:white;

    .hello {
        padding-left:50px;
    }
}

This works great.

Can I handle multiple classes while using nested styles.

In the sample above I'm talking about this:

CSS

.container.desc {
    background:blue;
}

In this case all div.container would normally be red but div.container.desc would be blue.

How can I nest this inside container with Sass?

Body:
this worked for me

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

.container{
  &.desc {
    background: blue;
  }
  &.asc {
    background: red;
  }
}


问:
Powershell with XAML: Handle click event of button inside ListBox datatemplate
I have created a XAML document that contains a listbox.  The DataTemplate for the ListBox.ItemTemplate contains a TextBlock and a Button (ommitting irrelevant properties for brevity)

```<code><DataTemplate>
    <TextBlock Text={Binding AppName} />
    <Button Name="btnRefresh" Content="Refresh"/>
</DataTemplate>
</code>```

I am displaying and handling this XAML with Powershell.  Is there a way to add a click event to the button from Powershell as the controls in the DataTemplate do not get enumerated when I read in the XAML, so I cannot simply reference the variable and append an Add_Click handler to it:

```<code>$reader = (New-Object System.Xml.XmlNodeReader $xaml)
$window = [Windows.Markup.XamlReader]::Load($reader)
$window.FindName("btnRefresh").add_click({...
</code>```

So on clicking the button i'd then need determine which button has been clicked if there are many rows in the ListBox.  Ideally the EventArgs for the click event would pass some data pertaining to the ListBoxItem to which the button is attached.

Just re-iterating that any solutions must be for Powershell, not C#.

Thanks

答:
You don't need to add an event handler to the Button in the ItemTemplate. You could handle the attached ButtonBase.Click event of the ListBox itself, e.g.:

```<code>$listBox.AddHandler([System.Windows.Controls.Primitives.ButtonBase]::ClickEvent,
    $ClickHandler)
</code>```

In the handler you could then get a reference to the clicked button using the OriginalSource property of the RoutedEventArgs.

Body:
I have created a XAML document that contains a listbox.  The DataTemplate for the ListBox.ItemTemplate contains a TextBlock and a Button (ommitting irrelevant properties for brevity)

<DataTemplate>
    <TextBlock Text={Binding AppName} />
    <Button Name="btnRefresh" Content="Refresh"/>
</DataTemplate>

I am displaying and handling this XAML with Powershell.  Is there a way to add a click event to the button from Powershell as the controls in the DataTemplate do not get enumerated when I read in the XAML, so I cannot simply reference the variable and append an Add_Click handler to it:

$reader = (New-Object System.Xml.XmlNodeReader $xaml)
$window = [Windows.Markup.XamlReader]::Load($reader)
$window.FindName("btnRefresh").add_click({...

So on clicking the button i'd then need determine which button has been clicked if there are many rows in the ListBox.  Ideally the EventArgs for the click event would pass some data pertaining to the ListBoxItem to which the button is attached.

Just re-iterating that any solutions must be for Powershell, not C#.

Thanks

Body:
You don't need to add an event handler to the Button in the ItemTemplate. You could handle the attached ButtonBase.Click event of the ListBox itself, e.g.:

$listBox.AddHandler([System.Windows.Controls.Primitives.ButtonBase]::ClickEvent,
    $ClickHandler)

In the handler you could then get a reference to the clicked button using the OriginalSource property of the RoutedEventArgs.