问:
Can i use UUID as datatype for id field in model/pojo class using hibernate search
I am trying to implement search functionality using hibernate search for my project which is in spring boot .

I used hibernate search annotations like @Indexed, @Field.

When i use datatype of id  Field as Long then search is performed and list of results is returned but in my project UUID is used as datatype for id field which is also primary key  .in the case of UUID the result is an empty list.

```<code>@Id
@GeneratedValue
private UUID id;
</code>```

How can i perform search operation using UUID as datatype for id field?

答:
Yes, you can use UUID as a document ID, and it should work out of the box.

If you're not getting any result:

Check you're using a recent version of Hibernate Search (5.11+) and Hibernate ORM (5.4+).

Check that you reindexed your data after changing the type of your ID.

When reindexing, check your logs for indexing failures and report them here.

Test with a very simple query, for example qb.all().createQuery(). If you get results with that query, the problem is with your initial query, not with your identifier.

You can apply @sridhar-karuppusamy's suggestion, but that should only be necessary if you want the database type to be VARCHAR instead of VARBINARY. And that is irrelevant to Hibernate Search.

Body:
I am trying to implement search functionality using hibernate search for my project which is in spring boot .

I used hibernate search annotations like @Indexed, @Field.

When i use datatype of id  Field as Long then search is performed and list of results is returned but in my project UUID is used as datatype for id field which is also primary key  .in the case of UUID the result is an empty list.

@Id
@GeneratedValue
private UUID id;

How can i perform search operation using UUID as datatype for id field?


来源: stackexchange

问:
Changing individual image sources with jQuery
I need to change the image sources of multiple individual images on a site containing many. They do not have IDs I could use to identify each individual image, which is why I need to make the changes based on the current source each image has.

I have not managed to find a working solution to this.

The html looks like this:

```<code><img class="card-image" alt="" src="www.url.com/12987237857.an-individual-photo.jpg">
</code>```

Ive found and tried many variations of this but have not found a way to make this change only a specific img src:

```<code>  $('.card-image').attr('src', $('.card-image').attr('src').replace('original', 'new'));
</code>```

I have done something similar before with hrefs and this worked perfectly:

```<code> $('a[href$="partOfOldURL"]').attr('href', 'newURL');
</code>```

Could someone help me out? Thank you in advance!

答:
You can easily do this using .attr( attributeName, function ) like:

```<code>$(".card-image").attr("src", function(i, val) {
  return val.replace('individual', 'new');
});
</code>```

Demo:

$(".card-image").attr("src", function(i, val) {
  return val.replace('individual', 'new');
});

$(".card-image").each(function() {
  console.log($(this).attr("src"))
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="card-image" alt="" src="www.url.com/12987237857.an-individual-photo.jpg">
<img class="card-image" alt="" src="www.url.com/12985555555.an-individual-photo.jpg"></code>```

You can see in this demo individual text in the src is replaced with new and the updated src is also shown in the console. You can replace any text you want inside the function.

ContentLicense: CC BY-SA 4.0

Body:
I need to change the image sources of multiple individual images on a site containing many. They do not have IDs I could use to identify each individual image, which is why I need to make the changes based on the current source each image has.

I have not managed to find a working solution to this.

The html looks like this:

Ive found and tried many variations of this but have not found a way to make this change only a specific img src:

  $('.card-image').attr('src', $('.card-image').attr('src').replace('original', 'new'));

I have done something similar before with hrefs and this worked perfectly:

 $('a[href$="partOfOldURL"]').attr('href', 'newURL');

Could someone help me out? Thank you in advance!

Body:
You can easily do this using .attr( attributeName, function ) like:

$(".card-image").attr("src", function(i, val) {
  return val.replace('individual', 'new');
});

Demo:

$(".card-image").attr("src", function(i, val) {
  return val.replace('individual', 'new');
});

$(".card-image").each(function() {
  console.log($(this).attr("src"))
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="card-image" alt="" src="www.url.com/12987237857.an-individual-photo.jpg">
<img class="card-image" alt="" src="www.url.com/12985555555.an-individual-photo.jpg">

You can see in this demo individual text in the src is replaced with new and the updated src is also shown in the console. You can replace any text you want inside the function.


问:
swift - right to left horizontal collection view in displayed incorrectly from left to right
I'm displaying a horizontal collection view from right to left and encountering a problem that when displaying the elements, they are displayed from the end (left to right instead):

In the run schema options, the app language is set as right to left pseudo language

If I'm adding the items when starting the app before instead of adding them after and calling reloadData, the problem doesn't occur

Sample project and screenshots are attached

One solution proposed was adding the code below that worked but required me to reverse the order to add the items. I would like to know if there's a better way to do it and also within the API instead of using an overriding extension

```<code>extension UICollectionViewFlowLayout {

open override var flipsHorizontallyInOppositeLayoutDirection: Bool {
    return true
}
</code>```

}

sample project

help would be appreciated

code:

```<code>import UIKit

class HorizontalScrollTestViewController: UIViewController, UICollectionViewDataSource , CellDelegate{

    var items = [String]()

@IBOutlet weak var collectionView: UICollectionView!

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return items.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ReusableCell", for: indexPath) as! CategoryCollectionViewCell

    cell.category.setTitle(items[indexPath.row] , for: UIControl.State.normal)
    cell.delegate = self
    return cell

}

override func viewDidLoad() {
    super.viewDidLoad()

    let dispatchQueue = DispatchQueue(label: "resourcesQueue", qos: .background)
    dispatchQueue.async {
        self.addItems()

        DispatchQueue.main.async {
            self.collectionView.reloadData()
        }

    }
    collectionView.dataSource = self

    collectionView?.register(UINib(nibName: "CategoryCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "ReusableCell")

}

func buttonPressed(_ cell: UICollectionViewCell) {
    if  let row = self.collectionView.indexPath(for: cell)?.row {
        print(items[row])
    }
}

func addItems() {
    self.items.append("test 10")
    self.items.append("test 9")
    self.items.append("test 8")
    self.items.append("test 7")
    self.items.append("test 6")
    self.items.append("test 5")
    self.items.append("test 4")
    self.items.append("test 3")
    self.items.append("test 2")
    self.items.append("test 1")

 }
}
</code>```

example when adding the items after the app started and using reloadData:

expected behavior

答:
Here you just flip your collectionView and collectionViewCell horizontally. this will solve your issue.

With this you can flip your collectionView horizontally. so that your collectionView starts from right. your first element will be at right and last element will be at left.

```<code>collectionView.transform = CGAffineTransform(scaleX: -1, y: 1)
</code>```

OR

```<code>collectionView.transform = CGAffineTransform(a: -1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0)
</code>```

Similarly you have to flip each collectionViewCell also using

```<code>cell.transform = CGAffineTransform(scaleX: -1, y: 1)
</code>```

OR

```<code>cell.transform = CGAffineTransform(a: -1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0)
</code>```

and add element in array in following order

```<code>func addItems() {
        self.items.append("test 1")
        self.items.append("test 2")
        self.items.append("test 3")
        self.items.append("test 4")
        self.items.append("test 5")
        self.items.append("test 6")
        self.items.append("test 7")
        self.items.append("test 8")
        self.items.append("test 9")
        self.items.append("test 10")
    }
</code>```

Download updated project from Here

Body:
I'm displaying a horizontal collection view from right to left and encountering a problem that when displaying the elements, they are displayed from the end (left to right instead):

In the run schema options, the app language is set as right to left pseudo language

If I'm adding the items when starting the app before instead of adding them after and calling reloadData, the problem doesn't occur

Sample project and screenshots are attached

One solution proposed was adding the code below that worked but required me to reverse the order to add the items. I would like to know if there's a better way to do it and also within the API instead of using an overriding extension

extension UICollectionViewFlowLayout {

open override var flipsHorizontallyInOppositeLayoutDirection: Bool {
    return true
}

}

sample project

help would be appreciated

code:

import UIKit

class HorizontalScrollTestViewController: UIViewController, UICollectionViewDataSource , CellDelegate{

    var items = [String]()

@IBOutlet weak var collectionView: UICollectionView!

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return items.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ReusableCell", for: indexPath) as! CategoryCollectionViewCell

    cell.category.setTitle(items[indexPath.row] , for: UIControl.State.normal)
    cell.delegate = self
    return cell

}

override func viewDidLoad() {
    super.viewDidLoad()

    let dispatchQueue = DispatchQueue(label: "resourcesQueue", qos: .background)
    dispatchQueue.async {
        self.addItems()

        DispatchQueue.main.async {
            self.collectionView.reloadData()
        }

    }
    collectionView.dataSource = self

    collectionView?.register(UINib(nibName: "CategoryCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "ReusableCell")

}

func buttonPressed(_ cell: UICollectionViewCell) {
    if  let row = self.collectionView.indexPath(for: cell)?.row {
        print(items[row])
    }
}

func addItems() {
    self.items.append("test 10")
    self.items.append("test 9")
    self.items.append("test 8")
    self.items.append("test 7")
    self.items.append("test 6")
    self.items.append("test 5")
    self.items.append("test 4")
    self.items.append("test 3")
    self.items.append("test 2")
    self.items.append("test 1")

 }
}

example when adding the items after the app started and using reloadData:

expected behavior

Body:
Here you just flip your collectionView and collectionViewCell horizontally. this will solve your issue.

With this you can flip your collectionView horizontally. so that your collectionView starts from right. your first element will be at right and last element will be at left.

collectionView.transform = CGAffineTransform(scaleX: -1, y: 1)

OR

collectionView.transform = CGAffineTransform(a: -1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0)

Similarly you have to flip each collectionViewCell also using

cell.transform = CGAffineTransform(scaleX: -1, y: 1)

OR

cell.transform = CGAffineTransform(a: -1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0)

and add element in array in following order

func addItems() {
        self.items.append("test 1")
        self.items.append("test 2")
        self.items.append("test 3")
        self.items.append("test 4")
        self.items.append("test 5")
        self.items.append("test 6")
        self.items.append("test 7")
        self.items.append("test 8")
        self.items.append("test 9")
        self.items.append("test 10")
    }

Download updated project from Here


问:
Download CSV files with HttpClient in ReactJS
I'm trying to make an API request using HttpClient to download a CSV file. I had to switch from Axios to HttpClient due to ForgeRock authentication that requires a bearer token. I'm having an issue where the response coming back does not have response.data. Where would I find the data to download to CSV?

My code:

```<code>fetchCSV = date => {
    const url = "https://<URLdownloadLink>?runDate="+date;
    const method = "GET";
    HttpClient
      .request({
        url,
        method,
        bypassAuthentication: false,
        responseType: 'blob',
        init: {},
        timeout: 5000
      })
      .then((response) => {
        console.log("data", response)
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'Asset Manager.csv');
        document.body.appendChild(link);
        link.click();
        link.remove();
      })
      .catch(error => {
        console.log("error", error);
      })
  }
</code>```

The response I'm getting back is the below. The response does not have "response.data" as an object key. When I open the CSV it only has "undefined".

This is my response.body:

答:
You are using response.data instead of response.body?
Thats why it says undefined.
Remember CSV is just plain text and response.data is undefined.

fetchCSV = date => {
    const url = "https://<URLdownloadLink>?runDate=" + date;
    const method = "GET";
    HttpClient
        .request({
            url,
            method,
            bypassAuthentication: false,
            responseType: 'blob',
            init: {},
            timeout: 5000
        })
        .then((response) => {
            console.log("data", response)
            const url = window.URL.createObjectURL(new Blob([response.body]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', 'Asset Manager.csv');
            document.body.appendChild(link);
            link.click();
            link.remove();
        })
        .catch(error => {
            console.log("error", error);
        })
}
```

Body:
I'm trying to make an API request using HttpClient to download a CSV file. I had to switch from Axios to HttpClient due to ForgeRock authentication that requires a bearer token. I'm having an issue where the response coming back does not have response.data. Where would I find the data to download to CSV?

My code:

fetchCSV = date => {
    const url = "https://<URLdownloadLink>?runDate="+date;
    const method = "GET";
    HttpClient
      .request({
        url,
        method,
        bypassAuthentication: false,
        responseType: 'blob',
        init: {},
        timeout: 5000
      })
      .then((response) => {
        console.log("data", response)
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'Asset Manager.csv');
        document.body.appendChild(link);
        link.click();
        link.remove();
      })
      .catch(error => {
        console.log("error", error);
      })
  }

The response I'm getting back is the below. The response does not have "response.data" as an object key. When I open the CSV it only has "undefined".

This is my response.body:


问:
Problem with transitive dependency while using BOM
Lets say I have

1. a bom project(named as bom)

2. a jar project(named as A)

3. a war project(named as B)

bom project has jackson-data version as 2.8.5 and 2.8.1 in properties and in dependencymanagement section 2.8.5 for jackson-data.

project A which inherits bom declares jackson-data dependency in it with version 2.8.1.

project B depends on project A and inherits bom. it does not declare the jackson-data in its dependency

now when I look at lib dir of Project B, jackson-data version  is 2.8.5 where as project A is declaring it as 2.8.1.

irrespective of what is declared in dependency it is taking the version declared in bom. is there any way to resolve the transitive dependency of jackson-data in project B as it is declared in project A means a version of 2.8.1 and not 2.8.5 while using the bom?

Below are the poms

 BOM PROJECT

```<code>  <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-
    instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.test</groupId>
<artifactId>bom</artifactId>
<version>1.1</version>
<packaging>pom</packaging>

<properties>
    <jackson-databind.version>2.8.5</jackson-databind.version>
    <jackson-databind.version.A>2.8.1</jackson-databind.version.A>
</properties>

<dependencyManagement>
   <dependencies>
        <dependency>
            <groupId>com.test</groupId>
            <artifactId>A</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson-databind.version}</version>
        </dependency>
   </dependencies>
</dependencyManagement>
</code>```

pom of project A

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.test</groupId>
        <artifactId>bom</artifactId>
        <version>1.1</version>
    </parent>
    <groupId>com.test</groupId>
    <artifactId>A</artifactId>
    <version>1.0</version>

    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.1</version>
        </dependency>

    </dependencies>
</project>
</code>```

Project B

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

<parent>
    <groupId>com.emirates.ibe</groupId>
    <artifactId>bom</artifactId>
    <version>1.1</version>
</parent>
    <groupId>com.test</groupId>
    <artifactId>B</artifactId>
    <version>1.0</version>
    <packaging>war</packaging>

    <dependencies>

        <dependency>
            <groupId>com.test</groupId>
            <artifactId>A</artifactId>
        </dependency>

    </dependencies>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>

            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <warName>B</warName>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

答:
DependencyManagement overrides transitive dependencies. This is what happens here (and this is how it's meant to be).

If you want a different version, either change the dependencyManagement or override in the project in which you use A

Body:
Lets say I have

1. a bom project(named as bom)

2. a jar project(named as A)

3. a war project(named as B)

bom project has jackson-data version as 2.8.5 and 2.8.1 in properties and in dependencymanagement section 2.8.5 for jackson-data.

project A which inherits bom declares jackson-data dependency in it with version 2.8.1.

project B depends on project A and inherits bom. it does not declare the jackson-data in its dependency

now when I look at lib dir of Project B, jackson-data version  is 2.8.5 where as project A is declaring it as 2.8.1.

irrespective of what is declared in dependency it is taking the version declared in bom. is there any way to resolve the transitive dependency of jackson-data in project B as it is declared in project A means a version of 2.8.1 and not 2.8.5 while using the bom?

Below are the poms

 BOM PROJECT

  <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-
    instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.test</groupId>
<artifactId>bom</artifactId>
<version>1.1</version>
<packaging>pom</packaging>

<properties>
    <jackson-databind.version>2.8.5</jackson-databind.version>
    <jackson-databind.version.A>2.8.1</jackson-databind.version.A>
</properties>

<dependencyManagement>
   <dependencies>
        <dependency>
            <groupId>com.test</groupId>
            <artifactId>A</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson-databind.version}</version>
        </dependency>
   </dependencies>
</dependencyManagement>

pom of project A

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.test</groupId>
        <artifactId>bom</artifactId>
        <version>1.1</version>
    </parent>
    <groupId>com.test</groupId>
    <artifactId>A</artifactId>
    <version>1.0</version>

    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.1</version>
        </dependency>

    </dependencies>
</project>

Project B

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

<parent>
    <groupId>com.emirates.ibe</groupId>
    <artifactId>bom</artifactId>
    <version>1.1</version>
</parent>
    <groupId>com.test</groupId>
    <artifactId>B</artifactId>
    <version>1.0</version>
    <packaging>war</packaging>

    <dependencies>

        <dependency>
            <groupId>com.test</groupId>
            <artifactId>A</artifactId>
        </dependency>

    </dependencies>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>

            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <warName>B</warName>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


问:
Awaiting before an if statement
I have built a multi-step wizard that sometimes has step-dependant validation, i.e. checking that an address exists and then navigating away from the wizard if the values do not pass validation. However, not all steps require validation and, as such, it is not possible to return the validation function inside handleSubmit. I originally wrote the following:

```<code>const handleSubmit = async (values) => {
    const { handleValidation } = props
    let success = handleStepValidation
        ? await handleStepValidation(values)
        : true;
    if (success) {
        nextStep();
    }
}
</code>```

However, the above didn't work because it wasn't waiting for the validation to finish before the if statement. I am somewhat new to async/await and I currently have the .then/.catch in each handleStepValidation function because the wizard is a generic wrapper for all steps. I have settled on the following code, but it seems somewhat ugly and I wanted any advice/help on how I could improve it:

```<code>const handleSubmit = async (values) => {
    const { handleValidation } = props
    if (handleValidation && (await handleValidation(values))) {
        nextStep();
    } else {
        nextStep();
    }
}
</code>```

I appreciate any help in advance. Many thanks!

答:
Your first example should work, but can be simplified like this.

```<code>const handleSubmit = async (values) => {
  const { handleValidation } = props;
  if (!handleValidation || (await handleValidation(values))) {
    nextStep();
  }
}
</code>```

If the await isn't waiting, we need to see the implementation of handleValidation.

Title: Awaiting before an if statement

Body:
I have built a multi-step wizard that sometimes has step-dependant validation, i.e. checking that an address exists and then navigating away from the wizard if the values do not pass validation. However, not all steps require validation and, as such, it is not possible to return the validation function inside handleSubmit. I originally wrote the following:

const handleSubmit = async (values) => {
    const { handleValidation } = props
    let success = handleStepValidation
        ? await handleStepValidation(values)
        : true;
    if (success) {
        nextStep();
    }
}

However, the above didn't work because it wasn't waiting for the validation to finish before the if statement. I am somewhat new to async/await and I currently have the .then/.catch in each handleStepValidation function because the wizard is a generic wrapper for all steps. I have settled on the following code, but it seems somewhat ugly and I wanted any advice/help on how I could improve it:

const handleSubmit = async (values) => {
    const { handleValidation } = props
    if (handleValidation && (await handleValidation(values))) {
        nextStep();
    } else {
        nextStep();
    }
}

I appreciate any help in advance. Many thanks!

Body:
Your first example should work, but can be simplified like this.

const handleSubmit = async (values) => {
  const { handleValidation } = props;
  if (!handleValidation || (await handleValidation(values))) {
    nextStep();
  }
}

If the await isn't waiting, we need to see the implementation of handleValidation.


问:
Copy specific word from a file to another file using shell script
i am new to shell scripting.
my folder structure is like below format, in that every folder one file is there  the file  name is  note.json, so i want to copy from note.json specific word like "user", i tried this for single file, it's working but showing unnecessary data and also i needed in loop format (means going to every folder doing the same) can any body help me out?

my folder structure:

drwxr-xr-x   - zeppelin hdfs          0 2020-06-01 16:20 /user/zeppelin/notebook/2FBC2M3K2
drwxr-xr-x   - zeppelin hdfs          0 2020-05-20 18:01 /user/zeppelin/notebook/2FBDEKUGP
drwxr-xr-x   - zeppelin hdfs          0 2020-05-26 20:32 /user/zeppelin/notebook/2FBDXNZRC
drwxr-xr-x   - zeppelin hdfs          0 2020-05-26 21:00 /user/zeppelin/notebook/2FBEAGZEE
drwxr-xr-x   - zeppelin hdfs          0 2020-05-25 14:18 /user/zeppelin/notebook/2FBGXSHZR
drwxr-xr-x   - zeppelin hdfs          0 2020-05-20 14:31 /user/zeppelin/notebook/2FBHCNKJP
drwxr-xr-x   - zeppelin hdfs          0 2020-06-02 17:34 /user/zeppelin/notebook/2FBJCZ212
```

<p>I tried for single folder using below command,</p>

<pre class="lang-none prettyprint-override"><code>$ cat note.json | grep "user"
"user": "Ayan.Paul",
            "data": "org.apache.hive.service.cli.HiveSQLException: Error while compiling statement: FAILED: HiveAccessControlException Permission denied: user [Ayan.Paul] does not have [USE] privilege on [snt_mmedata_upload_prd]\n\tat org.apache.hive.jdbc.Utils.verifySuccess(Utils.java:300)\n\tat org.apache.hive.jdbc.Utils.verifySuccessWithInfo(Utils.java:286)\n\tat org.apache.hive.jdbc.HiveStatement.runAsyncOnServer(HiveStatement.java:324)\n\tat org.apache.hive.jdbc.HiveStatement.execute(HiveStatement.java:265)\n\tat org.apache.commons.dbcp2.DelegatingStatement.execute(DelegatingStatement.java:291)\n\tat org.apache.commons.dbcp2.DelegatingStatement.execute(DelegatingStatement.java:291)\n\tat org.apache.zeppelin.jdbc.JDBCInterpreter.executeSql(JDBCInterpreter.java:718)\n\tat org.apache.zeppelin.jdbc.JDBCInterpreter.interpret(JDBCInterpreter.java:801)\n\tat org.apache.zeppelin.interpreter.LazyOpenInterpreter.interpret(LazyOpenInterpreter.java:103)\n\tat org.apache.zeppelin.interpreter.remote.RemoteInterpreterServer$InterpretJob.jobRun(RemoteInterpreterServer.java:633)\n\tat org.apache.zeppelin.scheduler.Job.run(Job.java:188)\n\tat org.apache.zeppelin.scheduler.ParallelScheduler$JobRunner.run(ParallelScheduler.java:162)\n\tat java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)\n\tat java.util.concurrent.FutureTask.run(FutureTask.java:266)\n\tat java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)\n\tat java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)\n\tat java.lang.Thread.run(Thread.java:745)\nCaused by: org.apache.hive.service.cli.HiveSQLException: Error while compiling statement: FAILED: HiveAccessControlException Permission denied: user [Ayan.Paul] does not have [USE] privilege on [snt_mmedata_upload_prd]\n\tat org.apache.hive.service.cli.operation.Operation.toSQLException(Operation.java:335)\n\tat org.apache.hive.service.cli.operation.SQLOperation.prepare(SQLOperation.java:199)\n\tat org.apache.hive.service.cli.operation.SQLOperation.runInternal(SQLOperation.java:262)\n\tat org.apache.hive.service.cli.operation.Operation.run(Operation.java:247)\n\tat org.apache.hive.service.cli.session.HiveSessionImpl.executeStatementInternal(HiveSessionImpl.java:541)\n\tat org.apache.hive.service.cli.session.HiveSessionImpl.executeStatementAsync(HiveSessionImpl.java:527)\n\tat org.apache.hive.service.cli.CLIService.executeStatementAsync(CLIService.java:315)\n\tat org.apache.hive.service.cli.thrift.ThriftCLIService.ExecuteStatement(ThriftCLIService.java:562)\n\tat org.apache.hive.service.rpc.thrift.TCLIService$Processor$ExecuteStatement.getResult(TCLIService.java:1557)\n\tat org.apache.hive.service.rpc.thrift.TCLIService$Processor$ExecuteStatement.getResult(TCLIService.java:1542)\n\tat org.apache.thrift.ProcessFunction.process(ProcessFunction.java:39)\n\tat org.apache.thrift.TBaseProcessor.process(TBaseProcessor.java:39)\n\tat org.apache.thrift.server.TServlet.doPost(TServlet.java:83)\n\tat org.apache.hive.service.cli.thrift.ThriftHttpServlet.doPost(ThriftHttpServlet.java:208)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:707)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:790)\n\tat org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:848)\n\tat org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:584)\n\tat org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:224)\n\tat org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1180)\n\tat org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:512)\n\tat org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)\n\tat org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112)\n\tat org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)\n\tat org.eclipse.jetty.server.handler.gzip.GzipHandler.handle(GzipHandler.java:493)\n\tat org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)\n\tat org.eclipse.jetty.server.Server.handle(Server.java:534)\n\tat org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320)\n\tat org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)\n\tat org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:283)\n\tat org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:108)\n\tat org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)\n\tat org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303)\n\tat org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148)\n\tat org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136)\n\t... 3 more\nCaused by: java.lang.RuntimeException: org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAccessControlException:Permission denied: user [Ayan.Paul] does not have [USE] privilege on [snt_mmedata_upload_prd]\n\tat org.apache.ranger.authorization.hive.authorizer.RangerHiveAuthorizer.checkPrivileges(RangerHiveAuthorizer.java:483)\n\tat org.apache.hadoop.hive.ql.Driver.doAuthorizationV2(Driver.java:1330)\n\tat org.apache.hadoop.hive.ql.Driver.doAuthorization(Driver.java:1094)\n\tat org.apache.hadoop.hive.ql.Driver.compile(Driver.java:705)\n\tat org.apache.hadoop.hive.ql.Driver.compileInternal(Driver.java:1863)\n\tat org.apache.hadoop.hive.ql.Driver.compileAndRespond(Driver.java:1810)\n\tat org.apache.hadoop.hive.ql.Driver.compileAndRespond(Driver.java:1805)\n\tat org.apache.hadoop.hive.ql.reexec.ReExecDriver.compileAndRespond(ReExecDriver.java:126)\n\
</code>```

答:
As said above, if it is json structured the best and clean way is to use jq.
otherwise, if this line always stay the same you can try:

```<code>cat note.json | grep "\"user\":" | sed 's/\"//g' | sed 's/,//g' | sed 's/ //g'
</code>```

where

grep "\"user\":" - will take the the line you wanted

cut -d":" -f2 - will take from the second column by ":" separator

sed 's/\"//g' - remove "

sed 's/,//g' - remove commas

sed 's/ //g' - will remove spaces just in case ( you don't have to use it)

if you need the loop for it, lets say:

folder_Path='/path/to/myfolder'

```<code>files_in_folder=$(ls ${folder_Path})
for file in ${files_in_folder}
do
    if [[ ${file} == "note.json" ]]
    then
        cat ${file} | grep "\"user\":" | sed 's/\"//g' | sed 's/,//g' | sed 's/ //g' > ${new_file_path}
    fi
</code>```

Body:
i am new to shell scripting.
my folder structure is like below format, in that every folder one file is there  the file  name is  note.json, so i want to copy from note.json specific word like "user", i tried this for single file, it's working but showing unnecessary data and also i needed in loop format (means going to every folder doing the same) can any body help me out?

my folder structure:

drwxr-xr-x   - zeppelin hdfs          0 2020-06-01 16:20 /user/zeppelin/notebook/2FBC2M3K2
drwxr-xr-x   - zeppelin hdfs          0 2020-05-20 18:01 /user/zeppelin/notebook/2FBDEKUGP
drwxr-xr-x   - zeppelin hdfs          0 2020-05-26 20:32 /user/zeppelin/notebook/2FBDXNZRC
drwxr-xr-x   - zeppelin hdfs          0 2020-05-26 21:00 /user/zeppelin/notebook/2FBEAGZEE
drwxr-xr-x   - zeppelin hdfs          0 2020-05-25 14:18 /user/zeppelin/notebook/2FBGXSHZR
drwxr-xr-x   - zeppelin hdfs          0 2020-05-20 14:31 /user/zeppelin/notebook/2FBHCNKJP
drwxr-xr-x   - zeppelin hdfs          0 2020-06-02 17:34 /user/zeppelin/notebook/2FBJCZ212

I tried for single folder using below command,

$ cat note.json | grep "user"
"user": "Ayan.Paul",
            "data": "org.apache.hive.service.cli.HiveSQLException: Error while compiling statement: FAILED: HiveAccessControlException Permission denied: user [Ayan.Paul] does not have [USE] privilege on [snt_mmedata_upload_prd]\n\tat org.apache.hive.jdbc.Utils.verifySuccess(Utils.java:300)\n\tat org.apache.hive.jdbc.Utils.verifySuccessWithInfo(Utils.java:286)\n\tat org.apache.hive.jdbc.HiveStatement.runAsyncOnServer(HiveStatement.java:324)\n\tat org.apache.hive.jdbc.HiveStatement.execute(HiveStatement.java:265)\n\tat org.apache.commons.dbcp2.DelegatingStatement.execute(DelegatingStatement.java:291)\n\tat org.apache.commons.dbcp2.DelegatingStatement.execute(DelegatingStatement.java:291)\n\tat org.apache.zeppelin.jdbc.JDBCInterpreter.executeSql(JDBCInterpreter.java:718)\n\tat org.apache.zeppelin.jdbc.JDBCInterpreter.interpret(JDBCInterpreter.java:801)\n\tat org.apache.zeppelin.interpreter.LazyOpenInterpreter.interpret(LazyOpenInterpreter.java:103)\n\tat org.apache.zeppelin.interpreter.remote.RemoteInterpreterServer$InterpretJob.jobRun(RemoteInterpreterServer.java:633)\n\tat org.apache.zeppelin.scheduler.Job.run(Job.java:188)\n\tat org.apache.zeppelin.scheduler.ParallelScheduler$JobRunner.run(ParallelScheduler.java:162)\n\tat java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)\n\tat java.util.concurrent.FutureTask.run(FutureTask.java:266)\n\tat java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)\n\tat java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)\n\tat java.lang.Thread.run(Thread.java:745)\nCaused by: org.apache.hive.service.cli.HiveSQLException: Error while compiling statement: FAILED: HiveAccessControlException Permission denied: user [Ayan.Paul] does not have [USE] privilege on [snt_mmedata_upload_prd]\n\tat org.apache.hive.service.cli.operation.Operation.toSQLException(Operation.java:335)\n\tat org.apache.hive.service.cli.operation.SQLOperation.prepare(SQLOperation.java:199)\n\tat org.apache.hive.service.cli.operation.SQLOperation.runInternal(SQLOperation.java:262)\n\tat org.apache.hive.service.cli.operation.Operation.run(Operation.java:247)\n\tat org.apache.hive.service.cli.session.HiveSessionImpl.executeStatementInternal(HiveSessionImpl.java:541)\n\tat org.apache.hive.service.cli.session.HiveSessionImpl.executeStatementAsync(HiveSessionImpl.java:527)\n\tat org.apache.hive.service.cli.CLIService.executeStatementAsync(CLIService.java:315)\n\tat org.apache.hive.service.cli.thrift.ThriftCLIService.ExecuteStatement(ThriftCLIService.java:562)\n\tat org.apache.hive.service.rpc.thrift.TCLIService$Processor$ExecuteStatement.getResult(TCLIService.java:1557)\n\tat org.apache.hive.service.rpc.thrift.TCLIService$Processor$ExecuteStatement.getResult(TCLIService.java:1542)\n\tat org.apache.thrift.ProcessFunction.process(ProcessFunction.java:39)\n\tat org.apache.thrift.TBaseProcessor.process(TBaseProcessor.java:39)\n\tat org.apache.thrift.server.TServlet.doPost(TServlet.java:83)\n\tat org.apache.hive.service.cli.thrift.ThriftHttpServlet.doPost(ThriftHttpServlet.java:208)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:707)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:790)\n\tat org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:848)\n\tat org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:584)\n\tat org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:224)\n\tat org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1180)\n\tat org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:512)\n\tat org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)\n\tat org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112)\n\tat org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)\n\tat org.eclipse.jetty.server.handler.gzip.GzipHandler.handle(GzipHandler.java:493)\n\tat org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)\n\tat org.eclipse.jetty.server.Server.handle(Server.java:534)\n\tat org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320)\n\tat org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)\n\tat org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:283)\n\tat org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:108)\n\tat org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)\n\tat org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303)\n\tat org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148)\n\tat org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136)\n\t... 3 more\nCaused by: java.lang.RuntimeException: org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAccessControlException:Permission denied: user [Ayan.Paul] does not have [USE] privilege on [snt_mmedata_upload_prd]\n\tat org.apache.ranger.authorization.hive.authorizer.RangerHiveAuthorizer.checkPrivileges(RangerHiveAuthorizer.java:483)\n\tat org.apache.hadoop.hive.ql.Driver.doAuthorizationV2(Driver.java:1330)\n\tat org.apache.hadoop.hive.ql.Driver.doAuthorization(Driver.java:1094)\n\tat org.apache.hadoop.hive.ql.Driver.compile(Driver.java:705)\n\tat org.apache.hadoop.hive.ql.Driver.compileInternal(Driver.java:1863)\n\tat org.apache.hadoop.hive.ql.Driver.compileAndRespond(Driver.java:1810)\n\tat org.apache.hadoop.hive.ql.Driver.compileAndRespond(Driver.java:1805)\n\tat org.apache.hadoop.hive.ql.reexec.ReExecDriver.compileAndRespond(ReExecDriver.java:126)\n\

Body:
As said above, if it is json structured the best and clean way is to use jq.
otherwise, if this line always stay the same you can try:

cat note.json | grep "\"user\":" | sed 's/\"//g' | sed 's/,//g' | sed 's/ //g'

where

grep "\"user\":" - will take the the line you wanted

cut -d":" -f2 - will take from the second column by ":" separator

sed 's/\"//g' - remove "

sed 's/,//g' - remove commas

sed 's/ //g' - will remove spaces just in case ( you don't have to use it)

if you need the loop for it, lets say:

folder_Path='/path/to/myfolder'

files_in_folder=$(ls ${folder_Path})
for file in ${files_in_folder}
do
    if [[ ${file} == "note.json" ]]
    then
        cat ${file} | grep "\"user\":" | sed 's/\"//g' | sed 's/,//g' | sed 's/ //g' > ${new_file_path}
    fi


问:
Creating multiple implementations of a gherkin feature file
Suppose I have a feature file listing a number of scenarios (the actual contents of the feature file are irrelevant).

I would like to reuse the same feature file and provide a number of implementations:

Unit test suite implementation.

This implementation would mock away external aspects such as the DB/repositories.

This implementation would be fast to run.

Acceptance integration test suite implementation.

This would be run in a staging environment and would not mock anything (except perhaps external services where appropriate).

This implementation would be slow to run (because it requires all infrastructure to be up and running).

I have tried:

Placing the feature files in their own sub-project in a mono-repo.

Have other sub-projects depend on the feature files.

Implementing the tests.

Although this works I can no longer jump from the feature file to the step definitions (because they are in a different module) in IntelliJ (which lessens the appeal).

Has anyone else had any experience of doing something similar? Or would you recommend against doing this?

答:
We have done something similar.

What you could do is specify 2 different runners, RunCucumberTest and RunCucumberIT, where the first would be used to run unit tests and should point to the step definitions for the unit tests and the second would be used to run integration tests and should point to the step definitions for the integration tests. In the @CucumberOptions you can specify which step definitions (glue) the runner should use; just make sure to separate the "unit test" step definitions and the "integration test" step definitions in separate files/directories.

If there are any step definitions that don't depend on the distinction between unit and integration test, those could be in a "shared" step definitions file/directory, and called by both runners.

Files ending in *Test should be picked up in unit testing phase by Surefire.
Files ending in *IT should be picked up in unit testing phase by Failsafe.

Hope this helps.


问:
Cannot perform subprocess.run inside a snap
In my snap (coded in python), I try to perform some sudo commands but it didn’t work. Here is an example of a command that didn’t work:

```<code>command = "sudo netmgr -i country_code set:" + countryCode
subprocess.run([command])
</code>```

And when I run the snap in my device it won’t work and I got this error:

```<code>> Traceback (most recent call last): File
> “/snap/iotr-configuration/x17/bin/iotr-configuration”, line 11, in
> load_entry_point(‘iotr-configure==0.0.3’, ‘console_scripts’,
> ‘iotr-configuration’)() File
> “/snap/iotr-configuration/x17/lib/python3.5/site-packages/src/app.py”,
> line 53, in main configuration_program() File
> “/snap/iotr-configuration/x17/lib/python3.5/site-packages/src/app.py”,
> line 37, in configuration_program
> confNIC.set_nic_settings(“fd05:a40b:b47d:7340::4”, “1250”) File
> “/snap/iotr-configuration/x17/lib/python3.5/site-packages/src/configureNic.py”,
> line 16, in set_nic_settings subprocess.run([command]) File
> “/snap/iotr-configuration/x17/usr/lib/python3.5/subprocess.py”, line
> 693, in run with Popen(*popenargs, **kwargs) as process: File
> “/snap/iotr-configuration/x17/usr/lib/python3.5/subprocess.py”, line
> 947, in init restore_signals, start_new_session) File
> “/snap/iotr-configuration/x17/usr/lib/python3.5/subprocess.py”, line
> 1551, in _execute_child raise child_exception_type(errno_num, err_msg)
> FileNotFoundError: [Errno 2] No such file or directory: ‘sudo netmgr
> -i country_code set:1250’
</code>```

This function exist because when I type it directly in the terminal, it works…

Can you help me on this issue ?

答:
You're calling subprocess.run in the wrong way. You should either pass it a the command as a single string (like you're doing here) but then set shell=True, or break the command into several arguments, as in:

```<code>command = ["sudo", "netmgr", "-i", "country_code", "set:" + countryside]
subprocess.run(command)
</code>```

See the FAQ part of the documentation:

args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.

Body:
In my snap (coded in python), I try to perform some sudo commands but it didn’t work. Here is an example of a command that didn’t work:

command = "sudo netmgr -i country_code set:" + countryCode
subprocess.run([command])

And when I run the snap in my device it won’t work and I got this error:

> Traceback (most recent call last): File
> “/snap/iotr-configuration/x17/bin/iotr-configuration”, line 11, in
> load_entry_point(‘iotr-configure==0.0.3’, ‘console_scripts’,
> ‘iotr-configuration’)() File
> “/snap/iotr-configuration/x17/lib/python3.5/site-packages/src/app.py”,
> line 53, in main configuration_program() File
> “/snap/iotr-configuration/x17/lib/python3.5/site-packages/src/app.py”,
> line 37, in configuration_program
> confNIC.set_nic_settings(“fd05:a40b:b47d:7340::4”, “1250”) File
> “/snap/iotr-configuration/x17/lib/python3.5/site-packages/src/configureNic.py”,
> line 16, in set_nic_settings subprocess.run([command]) File
> “/snap/iotr-configuration/x17/usr/lib/python3.5/subprocess.py”, line
> 693, in run with Popen(*popenargs, **kwargs) as process: File
> “/snap/iotr-configuration/x17/usr/lib/python3.5/subprocess.py”, line
> 947, in init restore_signals, start_new_session) File
> “/snap/iotr-configuration/x17/usr/lib/python3.5/subprocess.py”, line
> 1551, in _execute_child raise child_exception_type(errno_num, err_msg)
> FileNotFoundError: [Errno 2] No such file or directory: ‘sudo netmgr
> -i country_code set:1250’

This function exist because when I type it directly in the terminal, it works…

Can you help me on this issue ?

Body:
You're calling subprocess.run in the wrong way. You should either pass it a the command as a single string (like you're doing here) but then set shell=True, or break the command into several arguments, as in:

command = ["sudo", "netmgr", "-i", "country_code", "set:" + countryside]
subprocess.run(command)

See the FAQ part of the documentation:

args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.


问:
Python 3 - Hangman game using .txt doc word bank
Im trying to make a hangman using a word bank stored on a .txt document but I'm so confused and just going round in circles.

Can anyone point me in the right direction? My code so far is below. Cheers!

```<code>#Word list
from random import choice

word = with open("words.txt") as f:
    word_list = f.read().splitlines()

#title
print("Welcome to Hangman! You have 7 lives to guess.")

#word generator
hidden_word = random.sample(words,1)

if(hidden_word[0]):
    print("The length of the word is: " , len(hidden_word[0]))

#parameters
guesses=0
guessed = []
word = []

#Game
for x in range(len(hidden_word[0])):
    word.append(' * ')

while guesses < 7:
    guess = input("Please enter your next guess: ""\n")

    if(guess in hidden_word[0]):
        print("The letter is correct.")
        for index, letter in enumerate(hidden_word[0]):
            if letter == guess:
                word[index] = guess
        guessed.append(guess)

    else:
            print("That letter is incorrect.")
            guesses=guesses+1
            guessed.append(guess)

    print("Please enter your next guess:")
    print("So far, you have answered - %s"%''.join(word))
    print()

    if ''.join(word) == hidden_word[0]:
        break

#Game finish
if guesses==7:
    print("You lose. The word was:" , hidden_word[0])
else:
    print("Congratulations, you won!")
</code>```

答:
I think you have made some mistakes while importing random , and while you use with you should not declare it to a variable
This should do it</p>

```<code>import random

with open("words.txt") as f:
    word_list = f.read().splitlines()

#title
print("Welcome to Hangman! You have 7 lives to guess.")

#word generator
hidden_word = random.sample(word_list,1)

if(hidden_word[0]):
    print("The length of the word is: " , len(hidden_word[0]))

#parameters
guesses=0
guessed = []
word = []

#Game
for x in range(len(hidden_word[0])):
    word.append(' * ')

while guesses < 7:
    guess = input("Please enter your next guess: ""\n")

    if(guess in hidden_word[0]):
        print("The letter is correct.")
        for index, letter in enumerate(hidden_word[0]):
            if letter == guess:
                word[index] = guess
        guessed.append(guess)

    else:
            print("That letter is incorrect.")
            guesses=guesses+1
            guessed.append(guess)

    print("Please enter your next guess:")
    print("So far, you have answered - %s"%''.join(word))
    print()

    if ''.join(word) == hidden_word[0]:
        break

#Game finish
if guesses==7:
    print("You lose. The word was:" , hidden_word[0])
else:
    print("Congratulations, you won!")
</code>```

Body:
Im trying to make a hangman using a word bank stored on a .txt document but I'm so confused and just going round in circles.

Can anyone point me in the right direction? My code so far is below. Cheers!

#Word list
from random import choice

word = with open("words.txt") as f:
    word_list = f.read().splitlines()

#title
print("Welcome to Hangman! You have 7 lives to guess.")

#word generator
hidden_word = random.sample(words,1)

if(hidden_word[0]):
    print("The length of the word is: " , len(hidden_word[0]))

#parameters
guesses=0
guessed = []
word = []

#Game
for x in range(len(hidden_word[0])):
    word.append(' * ')

while guesses < 7:
    guess = input("Please enter your next guess: ""\n")

    if(guess in hidden_word[0]):
        print("The letter is correct.")
        for index, letter in enumerate(hidden_word[0]):
            if letter == guess:
                word[index] = guess
        guessed.append(guess)

    else:
            print("That letter is incorrect.")
            guesses=guesses+1
            guessed.append(guess)

    print("Please enter your next guess:")
    print("So far, you have answered - %s"%''.join(word))
    print()

    if ''.join(word) == hidden_word[0]:
        break

#Game finish
if guesses==7:
    print("You lose. The word was:" , hidden_word[0])
else:
    print("Congratulations, you won!")

Body:
I think you have made some mistakes while importing random , and while you use with you should not declare it to a variable
This should do it

import random

with open("words.txt") as f:
    word_list = f.read().splitlines()

#title
print("Welcome to Hangman! You have 7 lives to guess.")

#word generator
hidden_word = random.sample(word_list,1)

if(hidden_word[0]):
    print("The length of the word is: " , len(hidden_word[0]))

#parameters
guesses=0
guessed = []
word = []

#Game
for x in range(len(hidden_word[0])):
    word.append(' * ')

while guesses < 7:
    guess = input("Please enter your next guess: ""\n")

    if(guess in hidden_word[0]):
        print("The letter is correct.")
        for index, letter in enumerate(hidden_word[0]):
            if letter == guess:
                word[index] = guess
        guessed.append(guess)

    else:
            print("That letter is incorrect.")
            guesses=guesses+1
            guessed.append(guess)

    print("Please enter your next guess:")
    print("So far, you have answered - %s"%''.join(word))
    print()

    if ''.join(word) == hidden_word[0]:
        break

#Game finish
if guesses==7:
    print("You lose. The word was:" , hidden_word[0])
else:
    print("Congratulations, you won!")


问:
RegEx Ranges with .00 number format
I want to build ranges from numeric values.
Values can be any value: 1.00, 2.00, 3.00 ... 674.00, ... 891.00 ...

Ranges: 1-10, 11-25, 26-50, 51-100, 101-200, 201-350, 351-600 , >601

I am struggling with the format of the numbers. the ".00" is killing me. I already did some research and tried:

```<code>([1-9]\.00|1[0]\.00)
</code>```

to fit to the range "1-10", but this puts every number to this range.

Does anyone have an idea how to solve it?
Thank you for your support.

答:
sorry for the image thing. now text:
range 26-50
regex ^(2[6-9]|[34][0-9]|50)$

range 26.00-50.00
regex ^(2[6-9].00|[34][0-9].00|50.00)$

this now works. I use the regex within Adobe Analytics zu group numbers into ranges.

Title: RegEx Ranges with .00 number format

Body:
I want to build ranges from numeric values.
Values can be any value: 1.00, 2.00, 3.00 ... 674.00, ... 891.00 ...

Ranges: 1-10, 11-25, 26-50, 51-100, 101-200, 201-350, 351-600 , >601

I am struggling with the format of the numbers. the ".00" is killing me. I already did some research and tried:

([1-9]\.00|1[0]\.00)

to fit to the range "1-10", but this puts every number to this range.

Does anyone have an idea how to solve it?
Thank you for your support.


问:
Stripprefix Middleware in NGINX Ingress controller
We have deployed Traefik 2.2 on our Kubernetes cluster with following ingress-route created to access our application. This configuration is working fine for us and is currently the same for our Production system as well.

apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: application-xyz

spec:
  tls: {}
  entryPoints:
    - web
    - websecure
  routes:

    - match: "HostRegexp(`application-xyz.com`) && PathPrefix(`/`)"

      kind: Rule
      priority: 1
      services:
        - name: application-xyz-service
          port: 80

    - match: "PathPrefix(`/application-xyz/`)"
      kind: Rule
      services:
        - name: application-xyz-service
          port: 80
      middlewares:
        - name: application-xyz-stripprefix
---
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: application-xyz-stripprefix
  namespace: frontend
spec:
  stripPrefix:
    prefixes:
      - /application-xyz/
    forceSlash: false
```

Question 1:
We are now planning to migrate from Traefik to Nginx Ingress Controller. Is there any way we can replicate the same on Nginx similar to Traefik configuration. I'm unsure if I'm comparing this in the right way or not. Would be grateful if we can get any pointers.

Question 2:
We wish to achieve stripprefix functionality in Nginx but didn't find any helpful documentation. Any leads in this regard is highly appreciated.

答: This issue is now fixed. We haven't deployed some of the application dependencies which put us in wrong direction. The pods were showing Running status for and the application was waiting for the dependencies to load and didn't receive any requests to serve. Thank you HelloWorld for suggesting the right approach.</p>

Body:
We have deployed Traefik 2.2 on our Kubernetes cluster with following ingress-route created to access our application. This configuration is working fine for us and is currently the same for our Production system as well.

apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: application-xyz

spec:
  tls: {}
  entryPoints:
    - web
    - websecure
  routes:

    - match: "HostRegexp(`application-xyz.com`) && PathPrefix(`/`)"

      kind: Rule
      priority: 1
      services:
        - name: application-xyz-service
          port: 80

    - match: "PathPrefix(`/application-xyz/`)"
      kind: Rule
      services:
        - name: application-xyz-service
          port: 80
      middlewares:
        - name: application-xyz-stripprefix
---
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: application-xyz-stripprefix
  namespace: frontend
spec:
  stripPrefix:
    prefixes:
      - /application-xyz/
    forceSlash: false

Question 1:
We are now planning to migrate from Traefik to Nginx Ingress Controller. Is there any way we can replicate the same on Nginx similar to Traefik configuration. I'm unsure if I'm comparing this in the right way or not. Would be grateful if we can get any pointers.

Question 2:
We wish to achieve stripprefix functionality in Nginx but didn't find any helpful documentation. Any leads in this regard is highly appreciated.


问:
Is there a way to run QAF BDD test on AWS device farm?
I'm trying to execute QAF BDD test using AWS device farm (Appium test using TestNG) but unfortunately it wont trigger the execution on testcase even there is no error. The same working fine while execute it locally.

The testng.xml configurations:

```<code><suite name="QAF Demo" verbose="0">
    <test name="Launch_App" enabled="true">
        <groups>
            <run>
                <include name="SMOKE"/>
            </run>
        </groups>
        <classes>
            <class name="com.qmetry.qaf.automation.step.client.text.BDDTestFactory"/>
        </classes>
    </test>
</suite>
</code>```

BDD file:

```<code>SCENARIO: SampleTest
META-DATA: {"description":"Sample Test Scenario","groups":["SMOKE"]}

    Given print message

END
</code>```

The log from AWS :

```<code>Start Appium TestNG test
[DeviceFarm] java -Dappium.screenshots.dir=$DEVICEFARM_SCREENSHOT_PATH org.testng.TestNG -testjar *-tests.jar -d $DEVICEFARM_LOG_DIR/test-output -verbose 10
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
[TestRunner] Running the tests in 'Launch_App' with parallel mode:false
[RunInfo] Adding method selector: org.testng.internal.XmlMethodSelector@7cf10a6f priority: 10
include groups [SMOKE]
 exclude groups: [] Scanarios location:
[TestClass] Creating TestClass for [ClassImpl class=com.qmetry.qaf.automation.step.client.text.BDDTestFactory]
[TestNG] Running:
  /tmp/scratchE1xraV.scratch/test-packagel0A01c/testng.xml

[SuiteRunner] Created 1 TestRunners
[TestRunner] Running test Launch_App on 1  classes,  included groups:[SMOKE ] excluded groups:[]
===== Test class
com.qmetry.qaf.automation.step.client.text.BDDTestFactory
======
[TestNG] RUNNING: Suite: "Launch_App" containing "0" Tests (config: /tmp/scratchE1xraV.scratch/test-packagel0A01c/testng.xml)
===== Invoked methods
=====
Creating /tmp/customer_log_directoryz6SHdY/test-output/QAF Demo/Launch_App.html
Creating /tmp/customer_log_directoryz6SHdY/test-output/QAF Demo/Launch_App.xml

===============================================
    Launch_App
    Tests run: 0, Failures: 0, Skips: 0
===============================================

[TestNG]
[TestNG] ===============================================
[TestNG]     Launch_App
[TestNG]     Tests run: 0, Failures: 0, Skips: 0
[TestNG] ===============================================

===============================================
QAF Demo
Total tests run: 0, Failures: 0, Skips: 0
===============================================
</code>```

Is it due to custom method selector used by QAF?

答:
To integrate QAF with AWS Device Farm you can follow below steps.

As per AWS mentioned do required configuration in your project. Refer working with Appium on AWS Device Farm Documentation.

Add below folders in your assembly zip files. You can add these folders by updating your assembly/zip.xml.

<fileSet>
    <directory>${project.basedir}</directory>
    <outputDirectory>./</outputDirectory>
    <includes>
      <include>/resources/</include>
      <include>/scenarios/</include>
      <include>/config/</include>
    </includes>
</fileSet>
```

<ol start="3">
<li><p>Now build zip using <code>mvn clean package -DskipTests=true</code> command.</p></li>
<li><p>Follow the same reference link to upload your test package zip.</p></li>
<li><p>Provide path of testng xml in your configuration yml file.</p></li>
</ol>

<pre class="lang-sh prettyprint-override"><code>java -Dappium.screenshots.dir=$DEVICEFARM_SCREENSHOT_PATH org.testng.TestNG "config/testrun_config.xml" -d $DEVICEFARM_LOG_DIR/test-output -verbose 10
</code>```

Move QAF Results to build artifacts folder to fetch QAF result.

```<code>post_test:
    commands:
      - cd $DEVICEFARM_TEST_PACKAGE_PATH
      - cp -R test-results $DEVICEFARM_LOG_DIR
      - cp -R img $DEVICEFARM_LOG_DIR
      - cp -R img $DEVICEFARM_SCREENSHOT_PATH
</code>```

Body:
I'm trying to execute QAF BDD test using AWS device farm (Appium test using TestNG) but unfortunately it wont trigger the execution on testcase even there is no error. The same working fine while execute it locally.

The testng.xml configurations:

<suite name="QAF Demo" verbose="0">
    <test name="Launch_App" enabled="true">
        <groups>
            <run>
                <include name="SMOKE"/>
            </run>
        </groups>
        <classes>
            <class name="com.qmetry.qaf.automation.step.client.text.BDDTestFactory"/>
        </classes>
    </test>
</suite>

BDD file:

SCENARIO: SampleTest
META-DATA: {"description":"Sample Test Scenario","groups":["SMOKE"]}

    Given print message

END

The log from AWS :

Start Appium TestNG test
[DeviceFarm] java -Dappium.screenshots.dir=$DEVICEFARM_SCREENSHOT_PATH org.testng.TestNG -testjar *-tests.jar -d $DEVICEFARM_LOG_DIR/test-output -verbose 10
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
[TestRunner] Running the tests in 'Launch_App' with parallel mode:false
[RunInfo] Adding method selector: org.testng.internal.XmlMethodSelector@7cf10a6f priority: 10
include groups [SMOKE]
 exclude groups: [] Scanarios location:
[TestClass] Creating TestClass for [ClassImpl class=com.qmetry.qaf.automation.step.client.text.BDDTestFactory]
[TestNG] Running:
  /tmp/scratchE1xraV.scratch/test-packagel0A01c/testng.xml

[SuiteRunner] Created 1 TestRunners
[TestRunner] Running test Launch_App on 1  classes,  included groups:[SMOKE ] excluded groups:[]
===== Test class
com.qmetry.qaf.automation.step.client.text.BDDTestFactory
======
[TestNG] RUNNING: Suite: "Launch_App" containing "0" Tests (config: /tmp/scratchE1xraV.scratch/test-packagel0A01c/testng.xml)
===== Invoked methods
=====
Creating /tmp/customer_log_directoryz6SHdY/test-output/QAF Demo/Launch_App.html
Creating /tmp/customer_log_directoryz6SHdY/test-output/QAF Demo/Launch_App.xml

===============================================
    Launch_App
    Tests run: 0, Failures: 0, Skips: 0
===============================================

[TestNG]
[TestNG] ===============================================
[TestNG]     Launch_App
[TestNG]     Tests run: 0, Failures: 0, Skips: 0
[TestNG] ===============================================

===============================================
QAF Demo
Total tests run: 0, Failures: 0, Skips: 0
===============================================

Is it due to custom method selector used by QAF?

Body:
To integrate QAF with AWS Device Farm you can follow below steps.

As per AWS mentioned do required configuration in your project. Refer working with Appium on AWS Device Farm Documentation.

Add below folders in your assembly zip files. You can add these folders by updating your assembly/zip.xml.

<fileSet>
    <directory>${project.basedir}</directory>
    <outputDirectory>./</outputDirectory>
    <includes>
      <include>/resources/</include>
      <include>/scenarios/</include>
      <include>/config/</include>
    </includes>
</fileSet>

Now build zip using mvn clean package -DskipTests=true command.

Follow the same reference link to upload your test package zip.

Provide path of testng xml in your configuration yml file.

java -Dappium.screenshots.dir=$DEVICEFARM_SCREENSHOT_PATH org.testng.TestNG "config/testrun_config.xml" -d $DEVICEFARM_LOG_DIR/test-output -verbose 10

Move QAF Results to build artifacts folder to fetch QAF result.

post_test:
    commands:
      - cd $DEVICEFARM_TEST_PACKAGE_PATH
      - cp -R test-results $DEVICEFARM_LOG_DIR
      - cp -R img $DEVICEFARM_LOG_DIR
      - cp -R img $DEVICEFARM_SCREENSHOT_PATH


问:
strtod accepts "e" but also "d" -- why?
I find this strange.

While it makes sense that strtod accepts 'e' as one of the characters (exactly one to be precise) in the input string I find that it also accepts 'd'.

Can someone please explain?

```<code>#include < stdio.h >
#include < stdlib.h >
int main ()
{
char *s[] = {"1a1", "1e1", "1d1", "1f1"};
char * pEnd;
double d0, d1, d2, d3;
d0 = strtod (s[0],&pEnd);
d1 = strtod (s[1],NULL);
d2 = strtod (s[2],NULL);
d3 = strtod (s[3],NULL);
printf ("::: [%f] [%f] [%f] [%f] \n", d0, d1, d2, d3);
return 0;
}
</code>```

答:
Which platform and compiler? In both Linux and Mac OS X I get this result:

::: [1.000000] [10.000000] [1.000000] [1.000000]

which means only e worked. Note that you didn't check for errors...

ContentLicense: CC BY-SA 3.0

Title: strtod accepts "e" but also "d" -- why?

Body:
I find this strange.

While it makes sense that strtod accepts 'e' as one of the characters (exactly one to be precise) in the input string I find that it also accepts 'd'.

Can someone please explain?

#include < stdio.h >
#include < stdlib.h >
int main ()
{
char *s[] = {"1a1", "1e1", "1d1", "1f1"};
char * pEnd;
double d0, d1, d2, d3;
d0 = strtod (s[0],&pEnd);
d1 = strtod (s[1],NULL);
d2 = strtod (s[2],NULL);
d3 = strtod (s[3],NULL);
printf ("::: [%f] [%f] [%f] [%f] \n", d0, d1, d2, d3);
return 0;
}


问:
C# Linq OrderBy based on condition
I have a foreach loop that I want to change:

foreach (var line in lines.OrderBy(x=> x.ColA))

If a condition is met, then instead of ordering by ColA, I want to order by ColB.

I know this could be done like the following:

```<code>var orderLines = new List<OrderLines>();
if (condition)
    orderLines = lines.OrderBy(x => x.ColB).ToList();
else
    orderLines = lines.OrderBy(x => x.ColA).ToList(); ;

foreach (var line in orderLines)
</code>```

But I am sure there is a more elegant solution.

答:
Several solutions.

(1) Don't do the ToList() before your foreach, only create the IEnumerable.

```<code>IEnumerable<OrderLines> orderLines = condition ?
    lines.OrderBy(orderLine => orderLine.ColB) :
    lines.OrderBy(orderLine => orderLine.ColA);

foreach(OrderLine orderlLine in orderLines) {...}
</code>```

(2) If you will be using this on several locations, consider to create an extension method. This way your method looks like any other LINQ method.
See extension methods demystified

```<code>public static IEnumerable<OrderLine> OrderBy(
    this IEnumerable<OrderLine> source,
    bool condition)
{
    return condition ?
    lines.OrderBy(orderLine => orderLine.ColB) :
    lines.OrderBy(orderLine => orderLine.ColA);
}
</code>```

Usage:

If operator checks chexBox1, sort by colB, else sort by colA:

```<code>IEnumerable<OrderLine> lines = ...
foreach(var sortedOrderLine in lines.OrderBy(this.CheckBox1.IsChecked))
{
    ...
}
</code>```

Because it is an extension method of IEnumerable<OrderLine>, you can even intertwine it with other LINQ methods:

```<code>var result = lines.Where(orderLine => orderLine.Date.Year >= 2020)
                  .OrderBy(this.checkBox1.IsChecked)
                  .Select(orderLine => new
                  {
                       Id = orderLine.Id,
                       Price = orderLine.Price,
                  });
</code>```

But all in all, it doesn't save you a lot of code. The only advantage would be if you would use it in a lot of methods. In that case, a change in how you want to OrderBy condition would have to be changed in only one place. But again: if you expect to use it in one place, moving it to a separate method might not help readers to understand what happens.

Title: C# Linq OrderBy based on condition

Body:
I have a foreach loop that I want to change:

foreach (var line in lines.OrderBy(x=> x.ColA))

If a condition is met, then instead of ordering by ColA, I want to order by ColB.

I know this could be done like the following:

var orderLines = new List<OrderLines>();
if (condition)
    orderLines = lines.OrderBy(x => x.ColB).ToList();
else
    orderLines = lines.OrderBy(x => x.ColA).ToList(); ;

foreach (var line in orderLines)

But I am sure there is a more elegant solution.

Body:
Several solutions.

(1) Don't do the ToList() before your foreach, only create the IEnumerable.

IEnumerable<OrderLines> orderLines = condition ?
    lines.OrderBy(orderLine => orderLine.ColB) :
    lines.OrderBy(orderLine => orderLine.ColA);

foreach(OrderLine orderlLine in orderLines) {...}

(2) If you will be using this on several locations, consider to create an extension method. This way your method looks like any other LINQ method.
See extension methods demystified

public static IEnumerable<OrderLine> OrderBy(
    this IEnumerable<OrderLine> source,
    bool condition)
{
    return condition ?
    lines.OrderBy(orderLine => orderLine.ColB) :
    lines.OrderBy(orderLine => orderLine.ColA);
}

Usage:

If operator checks chexBox1, sort by colB, else sort by colA:

IEnumerable<OrderLine> lines = ...
foreach(var sortedOrderLine in lines.OrderBy(this.CheckBox1.IsChecked))
{
    ...
}

Because it is an extension method of IEnumerable<OrderLine>, you can even intertwine it with other LINQ methods:

var result = lines.Where(orderLine => orderLine.Date.Year >= 2020)
                  .OrderBy(this.checkBox1.IsChecked)
                  .Select(orderLine => new
                  {
                       Id = orderLine.Id,
                       Price = orderLine.Price,
                  });

But all in all, it doesn't save you a lot of code. The only advantage would be if you would use it in a lot of methods. In that case, a change in how you want to OrderBy condition would have to be changed in only one place. But again: if you expect to use it in one place, moving it to a separate method might not help readers to understand what happens.


问:
fancy-regex crate multiple matches
I'm using the fancy-regex crate since I need lookaheads in my Regex but it seems like it's not getting all of the matches in a string like I can with the regex crate which fancy-regex is built upon:

What I'm trying:

use fancy_regex::Regex;

let value = "Rect2(Vector2(0, 0), Vector2(0, 0))";

let re = Regex::new(r"\(([^()]*)\)").expect("Unable to create regex for values in parenthesis");
let results = re.captures(value).expect("Error running regex").expect("No matches found");

// Since 0 gets the all matches I print them individually.
// Prints 0, 0
println!("{:?}", results.get(1).unwrap());
// Error, no groups
println!("{:?}", results.get(2).unwrap());
```

<p>Now if I try using the regex crate, which works for this regex because this particular one doesn't use lookahead like my other one, it gets all of the catpures.</p>

```use regex::Regex;

let value = "Rect2(Vector2(0, 0), Vector2(300, 500))";

let re = Regex::new(r"\(([^()]*)\)").expect("Unable to create regex for values in parenthesis");
let results = re.find_iter(value);

for i in results {
   // Prints 0, 0 first and then 300, 500 next time around.
   println!("{:?}", i);
}
```

I can't seem to find anything in fancy-regex that has the same functionality even though its built on the regex crate. All I can find is captures.iter() but I get only the first match with that too.

I made a demo of the regex crate here but since fancy_regex is not one of the 100 top crates I couldn't do the same for it.

答:
Note that your fancy_regex code looks for two captures in a single match, which is doomed to fail since your expression only contains one capture group. What you want (and what you're doing with regex) is a way to iterate through the matches, but it looks like fancy_regex does not have an easy way to do it. So you will need to do it manually:

```<code>let mut start = 0;
while let Some (m) = re.captures_from_pos (values, start).unwrap() {
   println!("{:?}", m.get (1).unwrap());
   start = m.get (0).unwrap().start() + 1; // Or you can use `end` to avoid overlapping matches
}
</code>```

Title: fancy-regex crate multiple matches

Body:
I'm using the fancy-regex crate since I need lookaheads in my Regex but it seems like it's not getting all of the matches in a string like I can with the regex crate which fancy-regex is built upon:

What I'm trying:

use fancy_regex::Regex;

let value = "Rect2(Vector2(0, 0), Vector2(0, 0))";

let re = Regex::new(r"\(([^()]*)\)").expect("Unable to create regex for values in parenthesis");
let results = re.captures(value).expect("Error running regex").expect("No matches found");

// Since 0 gets the all matches I print them individually.
// Prints 0, 0
println!("{:?}", results.get(1).unwrap());
// Error, no groups
println!("{:?}", results.get(2).unwrap());

Now if I try using the regex crate, which works for this regex because this particular one doesn't use lookahead like my other one, it gets all of the catpures.

use regex::Regex;

let value = "Rect2(Vector2(0, 0), Vector2(300, 500))";

let re = Regex::new(r"\(([^()]*)\)").expect("Unable to create regex for values in parenthesis");
let results = re.find_iter(value);

for i in results {
   // Prints 0, 0 first and then 300, 500 next time around.
   println!("{:?}", i);
}

I can't seem to find anything in fancy-regex that has the same functionality even though its built on the regex crate. All I can find is captures.iter() but I get only the first match with that too.

I made a demo of the regex crate here but since fancy_regex is not one of the 100 top crates I couldn't do the same for it.

Body:
Note that your fancy_regex code looks for two captures in a single match, which is doomed to fail since your expression only contains one capture group. What you want (and what you're doing with regex) is a way to iterate through the matches, but it looks like fancy_regex does not have an easy way to do it. So you will need to do it manually:

let mut start = 0;
while let Some (m) = re.captures_from_pos (values, start).unwrap() {
   println!("{:?}", m.get (1).unwrap());
   start = m.get (0).unwrap().start() + 1; // Or you can use `end` to avoid overlapping matches
}


答:
You can use attribute selector [] as with proper condition.

As your tag is img and want to update src use $('img[src$="partOfOldURL"]'). And .attr('src', 'newURL');

Use ^ to match element with href start with partOfOldURL

```<code>$('img[src^="partOfOldURL"]').attr('src', 'newURL');
</code>```

Use $ to match element with href end with partOfOldURL

```<code>$('img[src$="partOfOldURL"]').attr('src', 'newURL');
</code>```

Use * to match element with href contains partOfOldURL

```<code>$('img[src*="partOfOldURL"]').attr('src', 'newURL');
</code>```

Please review jQuery selectors to learn more.

Title: Changing individual image sources with jQuery

Body:
I need to change the image sources of multiple individual images on a site containing many. They do not have IDs I could use to identify each individual image, which is why I need to make the changes based on the current source each image has.

I have not managed to find a working solution to this.

The html looks like this:

Ive found and tried many variations of this but have not found a way to make this change only a specific img src:

  $('.card-image').attr('src', $('.card-image').attr('src').replace('original', 'new'));

I have done something similar before with hrefs and this worked perfectly:

 $('a[href$="partOfOldURL"]').attr('href', 'newURL');

Could someone help me out? Thank you in advance!

Body:
You can use attribute selector [] as with proper condition.

As your tag is img and want to update src use $('img[src$="partOfOldURL"]'). And .attr('src', 'newURL');

Use ^ to match element with href start with partOfOldURL

$('img[src^="partOfOldURL"]').attr('src', 'newURL');

Use $ to match element with href end with partOfOldURL

$('img[src$="partOfOldURL"]').attr('src', 'newURL');

Use * to match element with href contains partOfOldURL

$('img[src*="partOfOldURL"]').attr('src', 'newURL');

Please review jQuery selectors to learn more.


问:
Error 500 when replacing file in Azure Blob Storage
Good day, I'm having an error where when I replace a file, it returns "500 internal server error". But when I upload a new file everything is okay.

Here is my code:

```<code>public async Task UploadContentBlobAsync(IFormFile formFile, string fileName)
{
    var blobClient = _containerClient.GetBlobClient(fileName);
    await blobClient.UploadAsync(formFile.OpenReadStream());
}
</code>```

accoring to this source Azure will just replace my fie to be uploaded to the existing file, but that doesn't happen to my case.

答:
I am using Azure.Storage.Blobs 12.4.3, I create a method and pass the request as a parameter. The following code works and no error will be reported during the replacement of blob content:

```<code>string connectionString = "DefaultEndpointsProtocol=https;AccountName=0730bowmanwindow;AccountKey=xxxxxx;EndpointSuffix=core.windows.net";

string containerName = "video";

string fileName = "1.png";

BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);

BlobClient blobClient = containerClient.GetBlobClient(fileName);

await blobClient.UploadAsync(req.Body, true);
</code>```

(I put the picture in the binary format and put it in the request.)

In the package I use, the Boolean value of parameter of the UploadAsync method about whether to override blob is false, so I must provide a true, otherwise it will report an error.

You can make an experiment to see if it can be executed correctly according to the package version and code provided by me. If not, please provide detail error information.:)

Body:
Good day, I'm having an error where when I replace a file, it returns "500 internal server error". But when I upload a new file everything is okay.

Here is my code:

public async Task UploadContentBlobAsync(IFormFile formFile, string fileName)
{
    var blobClient = _containerClient.GetBlobClient(fileName);
    await blobClient.UploadAsync(formFile.OpenReadStream());
}

accoring to this source Azure will just replace my fie to be uploaded to the existing file, but that doesn't happen to my case.

Body:
I am using Azure.Storage.Blobs 12.4.3, I create a method and pass the request as a parameter. The following code works and no error will be reported during the replacement of blob content:

string connectionString = "DefaultEndpointsProtocol=https;AccountName=0730bowmanwindow;AccountKey=xxxxxx;EndpointSuffix=core.windows.net";

string containerName = "video";

string fileName = "1.png";

BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);

BlobClient blobClient = containerClient.GetBlobClient(fileName);

await blobClient.UploadAsync(req.Body, true);

(I put the picture in the binary format and put it in the request.)

In the package I use, the Boolean value of parameter of the UploadAsync method about whether to override blob is false, so I must provide a true, otherwise it will report an error.

You can make an experiment to see if it can be executed correctly according to the package version and code provided by me. If not, please provide detail error information.:)


问:
How could I make the program track the days completed on my habit tracker?

I want to create a feature where the program will track the number of days the user has completed their habit. I attempted to do it below, but it only printed the integer 1, instead of adding up the days properly.

```<code>import click

names_file = open("names.txt", "r+")
habits_file = open("habits.txt", "r+")
habits_time = open("time.txt", "r+")
days_completed = + 1

# Welcome Message
print("Welcome to Habit Tracker by Synclare")

# User Info
if click.confirm('Are you a new user?', True):
   user_name = input("Welcome. What's your name? ")
   names_file.write(user_name)

   habit = input("\nEnter a habit: ")
   habits_file.write(habit)

   time = input("For how long do you want to do this habit?")
   habits_time.write(time)

   print("Habit created.")

   else:
           print("\nWelcome back, " + names_file.readline() + ".")
           if click.confirm('\nWould you like to view your current habits?', True):
           read_habit = habits_file.read()
           read_time = habits_time.read()
           print(read_habit + ": " + habits_time.read())

              if click.confirm("\nHave you completed today's habit?", True):
                  print("You have completed " + str(days_completed) + "/" + read_time)
</code>```

答:
Alongside the fact that you aren't storing the days_completed, you are also using:

days_completed = +1

Which does not update the variable (i.e. does not add 1 to days_completed). Use:

days_completed += 1

Or:

days_completed = days_completed + 1

This statement for now, only sets days_completed to +1 (i.e. 1).

Body:
I want to create a feature where the program will track the number of days the user has completed their habit. I attempted to do it below, but it only printed the integer 1, instead of adding up the days properly.

import click

names_file = open("names.txt", "r+")
habits_file = open("habits.txt", "r+")
habits_time = open("time.txt", "r+")
days_completed = + 1

# Welcome Message
print("Welcome to Habit Tracker by Synclare")

# User Info
if click.confirm('Are you a new user?', True):
   user_name = input("Welcome. What's your name? ")
   names_file.write(user_name)

   habit = input("\nEnter a habit: ")
   habits_file.write(habit)

   time = input("For how long do you want to do this habit?")
   habits_time.write(time)

   print("Habit created.")

   else:
           print("\nWelcome back, " + names_file.readline() + ".")
           if click.confirm('\nWould you like to view your current habits?', True):
           read_habit = habits_file.read()
           read_time = habits_time.read()
           print(read_habit + ": " + habits_time.read())

              if click.confirm("\nHave you completed today's habit?", True):
                  print("You have completed " + str(days_completed) + "/" + read_time)


问:
How do I get an nvidia driver in my docker ubuntu image?
I need to run a cuda binary on kubernetes.  I've set up the nodes to use the kubernetes nvidia device plugin with nvidia-docker2.  Here is my Dockerfile:

```<code>FROM ubuntu:18.04
COPY addarrays /addarrays
ENTRYPOINT [ "/addarrays" ]
</code>```

When I run the docker image through nvidia-docker2 or kubernetes it gives this error:

```<code>Cuda failure addarrays.cu:9: 'CUDA driver version is insufficient for CUDA runtime version'
Cuda failure addarrays.cu:9: 'CUDA driver version is insufficient for CUDA runtime version'
Cuda failure addarrays.cu:9: 'CUDA driver version is insufficient for CUDA runtime version'
Cuda failure addarrays.cu:9: 'CUDA driver version is insufficient for CUDA runtime version'
Cuda failure addarrays.cu:9: 'CUDA driver version is insufficient for CUDA runtime version'
Cuda failure addarrays.cu:9: 'CUDA driver version is insufficient for CUDA runtime version'
addarrays: addarrays.cu:62: int main(): Assertion `hostArrayTmp[i] == hostArrayDest[i]' failed.
</code>```

It looks like my docker image needs an nvidia driver.  I've modified the Dockerfile like this:

```<code>FROM ubuntu:18.04
RUN apt install software-properties-common
RUN add-apt-repository ppa:graphics-drivers
RUN apt update
RUN apt install nvidia-driver-440
COPY addarrays /addarrays
ENTRYPOINT [ "/addarrays" ]
</code>```

The software-properties-common is needed to install add-apt-repository, but it fails with this message:

```<code>E: Unable to locate package software-properties-common
</code>```

What do I need to do to get an nvidia driver installed in my docker image?

答:
You have to do the apt update first. On install commands you should use the -y flag. Also you should concatenate the commands into a single run command.

```<code>FROM ubuntu:18.04

RUN apt update && \
    apt install software-properties-common -y && \
    add-apt-repository ppa:graphics-drivers && \
    apt install nvidia-driver-440 -y

COPY addarrays /addarrays

ENTRYPOINT [ "/addarrays" ]
</code>```

Body:
I need to run a cuda binary on kubernetes.  I've set up the nodes to use the kubernetes nvidia device plugin with nvidia-docker2.  Here is my Dockerfile:

FROM ubuntu:18.04
COPY addarrays /addarrays
ENTRYPOINT [ "/addarrays" ]

When I run the docker image through nvidia-docker2 or kubernetes it gives this error:

Cuda failure addarrays.cu:9: 'CUDA driver version is insufficient for CUDA runtime version'
Cuda failure addarrays.cu:9: 'CUDA driver version is insufficient for CUDA runtime version'
Cuda failure addarrays.cu:9: 'CUDA driver version is insufficient for CUDA runtime version'
Cuda failure addarrays.cu:9: 'CUDA driver version is insufficient for CUDA runtime version'
Cuda failure addarrays.cu:9: 'CUDA driver version is insufficient for CUDA runtime version'
Cuda failure addarrays.cu:9: 'CUDA driver version is insufficient for CUDA runtime version'
addarrays: addarrays.cu:62: int main(): Assertion `hostArrayTmp[i] == hostArrayDest[i]' failed.

It looks like my docker image needs an nvidia driver.  I've modified the Dockerfile like this:

FROM ubuntu:18.04
RUN apt install software-properties-common
RUN add-apt-repository ppa:graphics-drivers
RUN apt update
RUN apt install nvidia-driver-440
COPY addarrays /addarrays
ENTRYPOINT [ "/addarrays" ]

The software-properties-common is needed to install add-apt-repository, but it fails with this message:

E: Unable to locate package software-properties-common

What do I need to do to get an nvidia driver installed in my docker image?

Body:
You have to do the apt update first. On install commands you should use the -y flag. Also you should concatenate the commands into a single run command.

FROM ubuntu:18.04

RUN apt update && \
    apt install software-properties-common -y && \
    add-apt-repository ppa:graphics-drivers && \
    apt install nvidia-driver-440 -y

COPY addarrays /addarrays

ENTRYPOINT [ "/addarrays" ]


问:
Adding validation using mediatR pipeline behaviour
As part of pipeline behavior, tried to set validation while creating customer

```<code>    public class ValidationBehavoir<TRequest, TResponse> : IPipelineBehavior<TRequest, TRequest>
        where TRequest : IRequest<TResponse>
    {

        private readonly IEnumerable<IValidator<TRequest>> _validators;

        public ValidationBehavoir(IEnumerable<IValidator<TRequest>> validators)
        {
            _validators = validators;
        }
        public async Task<TRequest> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TRequest> next)
        {

            var context = new ValidationContext(request);
            var failures = _validators.Select(x => x.Validate(context)).SelectMany(x => x.Errors).ToList();

            if(failures.Any())
            {
                throw new ValidationException(failures);
            }

            return await next();
        }
    }
</code>```

Here are the services added while setting DI

```<code>            services.AddMediatR(typeof(Program));
            services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavoir<,>));
            services.AddMediatR(typeof(CreateCustomerCommand).GetTypeInfo().Assembly);
            services.AddMediatR(typeof(GetCustomersQuery).GetTypeInfo().Assembly);

But still, getting below error?
System.ArgumentException: Implementation type 'CustomerApis.PipelineBehaviors.ValidationBehavoir`2[Customers.Service.Command.CreateCustomerCommand,Customers.Domain.Entities.Customer]' can't be converted to service type 'MediatR.IPipelineBehavior`2[Customers.Service.Command.CreateCustomerCommand,Customers.Domain.Entities.Customer]'
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ConstructorCallSite..ctor(ResultCache cache, Type serviceType, ConstructorInfo constructorInfo, ServiceCallSite[] parameterCallSites)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateOpenGeneric(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateEnumerable(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.<>c__DisplayClass7_0.<GetCallSite>b__0(Type type)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
</code>```

Can someone please help me here?

答:
public class ValidationBehavoir : IPipelineBehavior
            where TRequest : IRequest
    {

```<code>    private readonly IEnumerable<IValidator<TRequest>> _validators;

    public ValidationBehavoir(IEnumerable<IValidator<TRequest>> validators)
    {
        _validators = validators;
    }

    public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
    {
        var context = new ValidationContext(request);
        var failures = _validators.Select(x => x.Validate(context)).SelectMany(x => x.Errors).ToList();

        if (failures.Any())
        {
            throw new ValidationException(failures);
        }

        return await next();
    }
}
</code>```

to

public class ValidationBehavoir : IPipelineBehavior
            where TRequest : IRequest
    {

```<code>    private readonly IEnumerable<IValidator<TRequest>> _validators;

    public ValidationBehavoir(IEnumerable<IValidator<TRequest>> validators)
    {
        _validators = validators;
    }

    public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
    {
        var context = new ValidationContext(request);
        var failures = _validators.Select(x => x.Validate(context)).SelectMany(x => x.Errors).ToList();

        if (failures.Any())
        {
            throw new ValidationException(failures);
        }

        return await next();
    }
}
</code>```

Body:
As part of pipeline behavior, tried to set validation while creating customer

    public class ValidationBehavoir<TRequest, TResponse> : IPipelineBehavior<TRequest, TRequest>
        where TRequest : IRequest<TResponse>
    {

        private readonly IEnumerable<IValidator<TRequest>> _validators;

        public ValidationBehavoir(IEnumerable<IValidator<TRequest>> validators)
        {
            _validators = validators;
        }
        public async Task<TRequest> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TRequest> next)
        {

            var context = new ValidationContext(request);
            var failures = _validators.Select(x => x.Validate(context)).SelectMany(x => x.Errors).ToList();

            if(failures.Any())
            {
                throw new ValidationException(failures);
            }

            return await next();
        }
    }

Here are the services added while setting DI

            services.AddMediatR(typeof(Program));
            services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavoir<,>));
            services.AddMediatR(typeof(CreateCustomerCommand).GetTypeInfo().Assembly);
            services.AddMediatR(typeof(GetCustomersQuery).GetTypeInfo().Assembly);

But still, getting below error?
System.ArgumentException: Implementation type 'CustomerApis.PipelineBehaviors.ValidationBehavoir`2[Customers.Service.Command.CreateCustomerCommand,Customers.Domain.Entities.Customer]' can't be converted to service type 'MediatR.IPipelineBehavior`2[Customers.Service.Command.CreateCustomerCommand,Customers.Domain.Entities.Customer]'
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ConstructorCallSite..ctor(ResultCache cache, Type serviceType, ConstructorInfo constructorInfo, ServiceCallSite[] parameterCallSites)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateOpenGeneric(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateEnumerable(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.<>c__DisplayClass7_0.<GetCallSite>b__0(Type type)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)

Can someone please help me here?

Body:
public class ValidationBehavoir : IPipelineBehavior
            where TRequest : IRequest
    {

    private readonly IEnumerable<IValidator<TRequest>> _validators;

    public ValidationBehavoir(IEnumerable<IValidator<TRequest>> validators)
    {
        _validators = validators;
    }

    public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
    {
        var context = new ValidationContext(request);
        var failures = _validators.Select(x => x.Validate(context)).SelectMany(x => x.Errors).ToList();

        if (failures.Any())
        {
            throw new ValidationException(failures);
        }

        return await next();
    }
}

to

public class ValidationBehavoir : IPipelineBehavior
            where TRequest : IRequest
    {

    private readonly IEnumerable<IValidator<TRequest>> _validators;

    public ValidationBehavoir(IEnumerable<IValidator<TRequest>> validators)
    {
        _validators = validators;
    }

    public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
    {
        var context = new ValidationContext(request);
        var failures = _validators.Select(x => x.Validate(context)).SelectMany(x => x.Errors).ToList();

        if (failures.Any())
        {
            throw new ValidationException(failures);
        }

        return await next();
    }
}