问:
How to access to items in dictionaries within a list in python?
I have a column in a dataframe and each row is a list which is a collection of many dictionaries with the same keys. I want to get all the items from a same key inside the dictionaries.

I have this list:

s = [{'category': 'Public',
      'name': 'Newspaper',
      'person': 'A'},

     {'category': 'Music',
      'name': 'Andre',
      'person': 'B'},

     {'category': 'Music',
      'name': 'Indian',
      'person': 'A'},

     {'category': 'Artist',
      'name': 'Rihe',
      'person': 'D'},

     {'category': 'Interest',
      'name': 'Sport',
      'person': 'B'}]

```

<p>I've tried using a loop and itemgetter but it takes a lot of time due to the large data. I'm looking for a more efficient way to do it.</p>

<pre class="lang-py prettyprint-override"><code>from operator import itemgetter
   category = []
   name_page = []
   getter_category = itemgetter('category')
   getter_name = itemgetter('name')
   for element  in s:
      name_page.append(getter_name(element))
      category.append(getter_category(element))
</code>```

I want something more efficient like:

s['category'] = ['Public','Music','Music','Artist','Interest']
s['name'] = ['Newspaper','Andre','Indian','Rihe','Sport']
s['person'] = ['A','B','A','D','B']
```

答:
I don't want to use dictionaries. I've found the easiest way and it's using dataframes.</p>

```<code>s = pd.DataFrame(s)

-------------------------
|category  | name  | person|
-------------------------
|Public    | Music | Music |
---------------------------
|Newspaper | Andre | Indian|
----------------------------

s['category'].to_list()    =    ['Public','Music','Music','Artist','Interest']
</code>```

Body:
I have a column in a dataframe and each row is a list which is a collection of many dictionaries with the same keys. I want to get all the items from a same key inside the dictionaries.

I have this list:

s = [{'category': 'Public',
      'name': 'Newspaper',
      'person': 'A'},

     {'category': 'Music',
      'name': 'Andre',
      'person': 'B'},

     {'category': 'Music',
      'name': 'Indian',
      'person': 'A'},

     {'category': 'Artist',
      'name': 'Rihe',
      'person': 'D'},

     {'category': 'Interest',
      'name': 'Sport',
      'person': 'B'}]

I've tried using a loop and itemgetter but it takes a lot of time due to the large data. I'm looking for a more efficient way to do it.

from operator import itemgetter
   category = []
   name_page = []
   getter_category = itemgetter('category')
   getter_name = itemgetter('name')
   for element  in s:
      name_page.append(getter_name(element))
      category.append(getter_category(element))

I want something more efficient like:

s['category'] = ['Public','Music','Music','Artist','Interest']
s['name'] = ['Newspaper','Andre','Indian','Rihe','Sport']
s['person'] = ['A','B','A','D','B']

Body:
I don't want to use dictionaries. I've found the easiest way and it's using dataframes.

s = pd.DataFrame(s)

-------------------------
|category  | name  | person|
-------------------------
|Public    | Music | Music |
---------------------------
|Newspaper | Andre | Indian|
----------------------------

s['category'].to_list()    =    ['Public','Music','Music','Artist','Interest']


来源: stackexchange

问:
Serve Images in Next-Gen Formats
My ranking from Google Page Speed insights is being severely penalised because of:

"Serve Images in Next-Gen Formats" more info on Google's help page here.

However, according to this, this and this those formats are supported very few browsers.

What do you do in this scenario? What

答: You can use a tool like https://www.imagecompress.org/ to convert your current image formats, and follow the example to update your old tags https://www.imagecompress.org/examples.</p>

ContentLicense: CC BY-SA 4.0

Title: Serve Images in Next-Gen Formats


问:
What are some best practices for a creating a constructor that takes a boolean isX and depending on that value would need a boolean for isY?
In this hypothetical problem I'm creating a class to represent Sausage which can be:
A. Fresh and Packaged
B. Fresh and Not Packaged
C. Not Fresh and Not Packaged

Note: It can't be Not Fresh and Packaged.

I'm looking for the best practice to create constructor with this in mind.

The way I tried is below, but I think there should be a better solutions.

public class Sausage {
    Meat meat;
    boolean isFresh;
    boolean isPackaged;

    public Sausage(Meat meat, Boolean isFresh, Boolean isPackaged) {
        this.meat = meat;
        if (!isFresh) {
            this.isFresh = false;
            this.isPackaged = false;
        }
        else if (isPackaged) {
            this.isFresh = true;
            this.isPackaged = true;
        }
        else {
            this.isFresh = true;
            this.isPackaged = false;
        }
    }
}
```

I'm looking for a cleaner way to provide this functionality.

答:
You can represent the possible states as an enumeration type:

enum SausageType {
    FreshPackaged,
    FreshUnpackaged,
    NotFresh;
}
```

Then change your constructor to take a SausageType instead of two Booleans.

The advantage of this method is that it is not possible to call the constructor with the wrong combination of states, it is obvious to users of your class what the possible values are, and you do not need to remember to keep brittle runtime checking of arguments up to date with changing requirements.

Body:
In this hypothetical problem I'm creating a class to represent Sausage which can be:
A. Fresh and Packaged
B. Fresh and Not Packaged
C. Not Fresh and Not Packaged

Note: It can't be Not Fresh and Packaged.

I'm looking for the best practice to create constructor with this in mind.

The way I tried is below, but I think there should be a better solutions.

public class Sausage {
    Meat meat;
    boolean isFresh;
    boolean isPackaged;

    public Sausage(Meat meat, Boolean isFresh, Boolean isPackaged) {
        this.meat = meat;
        if (!isFresh) {
            this.isFresh = false;
            this.isPackaged = false;
        }
        else if (isPackaged) {
            this.isFresh = true;
            this.isPackaged = true;
        }
        else {
            this.isFresh = true;
            this.isPackaged = false;
        }
    }
}

I'm looking for a cleaner way to provide this functionality.

Body:
You can represent the possible states as an enumeration type:

enum SausageType {
    FreshPackaged,
    FreshUnpackaged,
    NotFresh;
}

Then change your constructor to take a SausageType instead of two Booleans.

The advantage of this method is that it is not possible to call the constructor with the wrong combination of states, it is obvious to users of your class what the possible values are, and you do not need to remember to keep brittle runtime checking of arguments up to date with changing requirements.


问:
Calling a Sub (containing a Do until loop) within a IF/Else Statement
I have a do until loop I keep having to repeat within an IF/ELSE statement.I want to call a sub (containing the do until loop) inside IF/Else If/Then statements instead. Please help

This code works but I want to condense each do until loop into a sub I can call with varying Tf and gain values:

```<code>Dim tmin As Double
Dim hgmin As Double
Dim tf As Double
Dim hmix As Double
Dim hg As Double
Dim i As Double
tmin = -70               'Lowest temperature of fluid on chart (Fahreinhet)
hgmin = 79.66            'Lowest enthalpy(saturated vapor)

tf = InputBox("Enter Lower Temperature [Fahrenheit]")   'Lower temperature of system

i = tmin
hg = hgmin
If tf <= -9 Then
     Do Until i = tf
        hg = hg + 0.15
        i = i + 1
    Loop
ElseIf tf >= -9 And tf <= 60 Then
    Do Until i = -9
        hg = hg + 0.15
        i = i + 1
    Loop
    Do Until i = tf
        hg = hg + 0.125
        i = i + 1
    Loop
End If
msgbox(hg)
End Sub
</code>```

Code below does not work, either loop stuck or gives me value of hmin rather than hmin + (gain * amount of iterations from tmin to Tf).

```<code>Sub main()
    Dim Tf As Double
    Dim i As Double, hg As Double, tmin As Double, hmin As Double

    Tf= InputBox("Enter Lower Temperature Value")
    hmin = 79.66

    hg = hmin
    tmin = -70
    i = tmin

    If Tf <= -9 Then
        Call subby(Tf, 0.15)

    ElseIf Tf >= -9 And Tf <= 60 Then
        Call subby(-9, 0.15)
        Call subby(Tf, 0.125)
    End If
    msgbox(hg)

End Sub

Sub subby(T As Double, gain As Double)
    Dim i As Double, hg As Double, tmin As Double, hmin As Double
    tmin = -70
    hmin = 79.66

    hg = hmin
    i = tmin
    Do Until i = T
        hg = hg + gain
        i = i + 1
    Loop

End Sub
</code>```

I want the below code attempting the method to call another sub into the main sub IF/Else statement to match the above code values for hg.

答:
The problem with your attempt at moving to a sub is that the your variables are not visible in that sub.  I see that you tried to "fix" it by declaring those variables as locals, but then the main variables don't get changed right?

One workaround is to insert a MODULE, then declare your variables there as PUBLIC:

```<code>Public tmin As Double
Public hgmin As Double
Public tf As Double
Public hmix As Double
Public hg As Double
Public i As Double
</code>```

From the docs:

Variables declared by using the Public statement are available to all
  procedures in all modules in all applications

Be sure to get rid of those duplicate variable declarations, both inside your subby() and in main().  They should only be declared in the module.

An alternative would be to pass ALL of the variables that need to be accessed and changed into the method.  You have to decide which is easier, or better for your situation.

Body:
I have a do until loop I keep having to repeat within an IF/ELSE statement.I want to call a sub (containing the do until loop) inside IF/Else If/Then statements instead. Please help

This code works but I want to condense each do until loop into a sub I can call with varying Tf and gain values:

Dim tmin As Double
Dim hgmin As Double
Dim tf As Double
Dim hmix As Double
Dim hg As Double
Dim i As Double
tmin = -70               'Lowest temperature of fluid on chart (Fahreinhet)
hgmin = 79.66            'Lowest enthalpy(saturated vapor)

tf = InputBox("Enter Lower Temperature [Fahrenheit]")   'Lower temperature of system

i = tmin
hg = hgmin
If tf <= -9 Then
     Do Until i = tf
        hg = hg + 0.15
        i = i + 1
    Loop
ElseIf tf >= -9 And tf <= 60 Then
    Do Until i = -9
        hg = hg + 0.15
        i = i + 1
    Loop
    Do Until i = tf
        hg = hg + 0.125
        i = i + 1
    Loop
End If
msgbox(hg)
End Sub

Code below does not work, either loop stuck or gives me value of hmin rather than hmin + (gain * amount of iterations from tmin to Tf).

Sub main()
    Dim Tf As Double
    Dim i As Double, hg As Double, tmin As Double, hmin As Double

    Tf= InputBox("Enter Lower Temperature Value")
    hmin = 79.66

    hg = hmin
    tmin = -70
    i = tmin

    If Tf <= -9 Then
        Call subby(Tf, 0.15)

    ElseIf Tf >= -9 And Tf <= 60 Then
        Call subby(-9, 0.15)
        Call subby(Tf, 0.125)
    End If
    msgbox(hg)

End Sub

Sub subby(T As Double, gain As Double)
    Dim i As Double, hg As Double, tmin As Double, hmin As Double
    tmin = -70
    hmin = 79.66

    hg = hmin
    i = tmin
    Do Until i = T
        hg = hg + gain
        i = i + 1
    Loop

End Sub

I want the below code attempting the method to call another sub into the main sub IF/Else statement to match the above code values for hg.

Body:
The problem with your attempt at moving to a sub is that the your variables are not visible in that sub.  I see that you tried to "fix" it by declaring those variables as locals, but then the main variables don't get changed right?

One workaround is to insert a MODULE, then declare your variables there as PUBLIC:

Public tmin As Double
Public hgmin As Double
Public tf As Double
Public hmix As Double
Public hg As Double
Public i As Double

From the docs:

Variables declared by using the Public statement are available to all
  procedures in all modules in all applications

Be sure to get rid of those duplicate variable declarations, both inside your subby() and in main().  They should only be declared in the module.

An alternative would be to pass ALL of the variables that need to be accessed and changed into the method.  You have to decide which is easier, or better for your situation.


问:
Need assistance with a for loop in Tic Tac Toe game
My program is exiting without iterating. It automatically goes to "YOU WON". Without the champion function the program runs fine. Its probably some obvious error Im missing. If anyone could please I would greatly appreciate it.</p>

```<code>#include <iostream>
#include <string>

#define GRID_SIZE 3

class TicTacToe {
private:
    char map[GRID_SIZE][GRID_SIZE];

public:

    void champion() {
        const char *possiblities[8]{
                "123"
                "456"
                "789"
                "147"
                "159"
                "258"
                "369"
                "753"
        };

        for (int i = 0; i < 8; i++) {
            bool winner = true;
            char previous_pos = '0';
            const char *possible_moves = possiblities[i];

            for (int index = 0; index < GRID_SIZE; index++) {
                char character = possible_moves[i];
                int entered_num = character - '0';
                int grid_space = entered_num - 1;
                int row = index / GRID_SIZE;
                int col = index % GRID_SIZE;

                char grid_coordinate = map[row][col];

                if (previous_pos == '0') {
                    previous_pos = grid_coordinate;
                } else if
                        (previous_pos == grid_coordinate) {
                    continue;
                } else {
                    winner = false;
                    break;
                }
            }
            if (winner = true) {
                std::cout << "YOU WON" << std::endl;
                exit(0);
                break;
            }

        }

    }

    void playgame() {
        std::string input;

        while (true) {
            std::cout << "Go player one" << std::endl;
            getline(std::cin, input);
            if (input != " ") {
                char entered = input.c_str()[0];

                if (entered >= '1' && entered <= '9') {
                    int entered_num = entered - '0';
                    int index = entered_num - 1;
                    int row = index / 3;
                    int col = index % 3;
                    char grid_position = map[row][col];

                    if (grid_position == 'X' || grid_position == 'O') {
                        std::cout << "Space taken. Try again" << std::endl;
                    } else {
                        map[row][col] = (char) 'X';
                        break;
                    }

                } else {
                    std::cout << "Only numbers 1 - 9" << std::endl;
                }
            } else {
                std::cout << "Have to enter something, try again" << std::endl;
            }

        }
    }

    void generateGrid() {
        int number = 1;

        for (int x = 0; x < GRID_SIZE; x++) {
            for (int y = 0; y < GRID_SIZE; y++) {
                map[x][y] = std::to_string(number).c_str()[0];
                number += 1;
            }
        }
    }

    void tictacToeMap() {

        std::cout << std::endl;

        for (int x = 0; x < GRID_SIZE; x++) {
            for (int y = 0; y < GRID_SIZE; y++) {
                std::printf(" %c ", map[x][y]);
            }
            std::cout << std::endl;
        }

    }

    TicTacToe() {
        generateGrid();
        while (true) {
            tictacToeMap();
            playgame();
            champion();

        }
    }
};

int main() {

    TicTacToe tic;
    tic.playgame();

    return 0;

}
</code>```

答:
First, do what Max Meijer said, by replacing if(winner = true) with if(winner == true). But the program is still broken. The problem is that in your string array, you are not separating each string with a comma, so when my debugger hits const char *possible_moves, it ends up just assigning the entire array concatenated together. So just separate each string in the possibilities array with a comma, like so:

```<code>const char *possiblities[8]{
                "123",
                "456",
                "789",
                "147",
                "159",
                "258",
                "369",
                "753"
        };
</code>```

Body:
My program is exiting without iterating. It automatically goes to "YOU WON". Without the champion function the program runs fine. Its probably some obvious error Im missing. If anyone could please I would greatly appreciate it.

#include <iostream>
#include <string>

#define GRID_SIZE 3

class TicTacToe {
private:
    char map[GRID_SIZE][GRID_SIZE];

public:

    void champion() {
        const char *possiblities[8]{
                "123"
                "456"
                "789"
                "147"
                "159"
                "258"
                "369"
                "753"
        };

        for (int i = 0; i < 8; i++) {
            bool winner = true;
            char previous_pos = '0';
            const char *possible_moves = possiblities[i];

            for (int index = 0; index < GRID_SIZE; index++) {
                char character = possible_moves[i];
                int entered_num = character - '0';
                int grid_space = entered_num - 1;
                int row = index / GRID_SIZE;
                int col = index % GRID_SIZE;

                char grid_coordinate = map[row][col];

                if (previous_pos == '0') {
                    previous_pos = grid_coordinate;
                } else if
                        (previous_pos == grid_coordinate) {
                    continue;
                } else {
                    winner = false;
                    break;
                }
            }
            if (winner = true) {
                std::cout << "YOU WON" << std::endl;
                exit(0);
                break;
            }

        }

    }

    void playgame() {
        std::string input;

        while (true) {
            std::cout << "Go player one" << std::endl;
            getline(std::cin, input);
            if (input != " ") {
                char entered = input.c_str()[0];

                if (entered >= '1' && entered <= '9') {
                    int entered_num = entered - '0';
                    int index = entered_num - 1;
                    int row = index / 3;
                    int col = index % 3;
                    char grid_position = map[row][col];

                    if (grid_position == 'X' || grid_position == 'O') {
                        std::cout << "Space taken. Try again" << std::endl;
                    } else {
                        map[row][col] = (char) 'X';
                        break;
                    }

                } else {
                    std::cout << "Only numbers 1 - 9" << std::endl;
                }
            } else {
                std::cout << "Have to enter something, try again" << std::endl;
            }

        }
    }

    void generateGrid() {
        int number = 1;

        for (int x = 0; x < GRID_SIZE; x++) {
            for (int y = 0; y < GRID_SIZE; y++) {
                map[x][y] = std::to_string(number).c_str()[0];
                number += 1;
            }
        }
    }

    void tictacToeMap() {

        std::cout << std::endl;

        for (int x = 0; x < GRID_SIZE; x++) {
            for (int y = 0; y < GRID_SIZE; y++) {
                std::printf(" %c ", map[x][y]);
            }
            std::cout << std::endl;
        }

    }

    TicTacToe() {
        generateGrid();
        while (true) {
            tictacToeMap();
            playgame();
            champion();

        }
    }
};

int main() {

    TicTacToe tic;
    tic.playgame();

    return 0;

}

Body:
First, do what Max Meijer said, by replacing if(winner = true) with if(winner == true). But the program is still broken. The problem is that in your string array, you are not separating each string with a comma, so when my debugger hits const char *possible_moves, it ends up just assigning the entire array concatenated together. So just separate each string in the possibilities array with a comma, like so:

const char *possiblities[8]{
                "123",
                "456",
                "789",
                "147",
                "159",
                "258",
                "369",
                "753"
        };


问:
Don't Click button inside in TableView
I have added one Button into tableview button is not clicked. The button is not clicked on the top of TableView. What should I do to make the button clickable? I need to make the CircleMenu button clickable. The button is now on top of tableView3. Do I need to add the button to the tableView?

```<code>override func viewDidLoad() {
        super.viewDidLoad()
        let button = CircleMenu(
                        frame: CGRect(x: view.frame.width/2 - 10, y: view.frame.height - 270, width: 50, height: 50),
                        normalIcon:"icon_menu",
                        selectedIcon:"icon_close",
                        buttonsCount: 3,
                        duration: 4,
                        distance: 85)
                    button.backgroundColor = UIColor.flatSkyBlue
                    button.delegate = self
                    button.layer.cornerRadius = button.frame.size.width / 2.0
                  view.addSubview(button)

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if tableView == self.tableView1 {

        if !chipnumber2.text!.isEmpty {
            let cell:DeviceTableViewCell2 = tableView1.dequeueReusableCell(withIdentifier: cellIdNew, for: indexPath) as! DeviceTableViewCell2

            let deviceItem: Device3New = itemsNew[indexPath.row]

            let tap1 = UITapGestureRecognizer(target: self, action: #selector(tittleNewTapped(_:)))
            let tap2 = UITapGestureRecognizer(target: self, action: #selector(tittleNewTapped2(_:)))

                return cell
            }
        }

        if tableView == self.tableView2 {
            if !chipnumber.text!.isEmpty {
                let cell:DeviceTableViewCell2 = tableView2.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! DeviceTableViewCell2

                let deviceItem: Device3 = items[indexPath.row]

cell.backgroundColor = GradientColor(UIGradientStyle.leftToRight, frame: self.view.frame, colors: [UIColor.flatPowderBlueDark, UIColor.flatSand])
                return cell

            }

        }
        if tableView == self.tableView3 {
            if !chipnumber3.text!.isEmpty {
                let cell:DeviceTableViewCell2 = tableView3.dequeueReusableCell(withIdentifier: cellIdNew2, for: indexPath) as! DeviceTableViewCell2

                cell.backgroundColor = GradientColor(UIGradientStyle.leftToRight, frame: self.view.frame, colors: [UIColor.flatPowderBlueDark, UIColor.flatSand])
                return cell

            }

        }

        return UITableViewCell()

    }
}
</code>```

答:
Just add a target to the button:

```<code>button.addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)
</code>```

And then a selector method:

```<code>@objc func buttonClicked(_ sender: UIButton) {
    print("clicked!")
}
</code>```

(Edit: Possible duplicate?)

Title: Don't Click button inside in TableView

Body:
I have added one Button into tableview button is not clicked. The button is not clicked on the top of TableView. What should I do to make the button clickable? I need to make the CircleMenu button clickable. The button is now on top of tableView3. Do I need to add the button to the tableView?

override func viewDidLoad() {
        super.viewDidLoad()
        let button = CircleMenu(
                        frame: CGRect(x: view.frame.width/2 - 10, y: view.frame.height - 270, width: 50, height: 50),
                        normalIcon:"icon_menu",
                        selectedIcon:"icon_close",
                        buttonsCount: 3,
                        duration: 4,
                        distance: 85)
                    button.backgroundColor = UIColor.flatSkyBlue
                    button.delegate = self
                    button.layer.cornerRadius = button.frame.size.width / 2.0
                  view.addSubview(button)

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if tableView == self.tableView1 {

        if !chipnumber2.text!.isEmpty {
            let cell:DeviceTableViewCell2 = tableView1.dequeueReusableCell(withIdentifier: cellIdNew, for: indexPath) as! DeviceTableViewCell2

            let deviceItem: Device3New = itemsNew[indexPath.row]

            let tap1 = UITapGestureRecognizer(target: self, action: #selector(tittleNewTapped(_:)))
            let tap2 = UITapGestureRecognizer(target: self, action: #selector(tittleNewTapped2(_:)))

                return cell
            }
        }

        if tableView == self.tableView2 {
            if !chipnumber.text!.isEmpty {
                let cell:DeviceTableViewCell2 = tableView2.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! DeviceTableViewCell2

                let deviceItem: Device3 = items[indexPath.row]

cell.backgroundColor = GradientColor(UIGradientStyle.leftToRight, frame: self.view.frame, colors: [UIColor.flatPowderBlueDark, UIColor.flatSand])
                return cell

            }

        }
        if tableView == self.tableView3 {
            if !chipnumber3.text!.isEmpty {
                let cell:DeviceTableViewCell2 = tableView3.dequeueReusableCell(withIdentifier: cellIdNew2, for: indexPath) as! DeviceTableViewCell2

                cell.backgroundColor = GradientColor(UIGradientStyle.leftToRight, frame: self.view.frame, colors: [UIColor.flatPowderBlueDark, UIColor.flatSand])
                return cell

            }

        }

        return UITableViewCell()

    }
}

Body:
Just add a target to the button:

button.addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)

And then a selector method:

@objc func buttonClicked(_ sender: UIButton) {
    print("clicked!")
}

(Edit: Possible duplicate?)


问:
df.apply(sorted, axis=1) removes column names?
Working through Pandas Cookbook.  Counting the Total Number of Flights Between Cities.

```<code>import pandas as pd
import numpy as np
# import matplotlib.pyplot as plt

print('NumPy: {}'.format(np.__version__))
print('Pandas: {}'.format(pd.__version__))
print('-----')

desired_width = 320
pd.set_option('display.width', desired_width)
pd.options.display.max_rows = 50
pd.options.display.max_columns = 14
# pd.options.display.float_format = '{:,.2f}'.format

file = "e:\\packt\\data_analysis_and_exploration_with_pandas\\section07\\data\\flights.csv"
flights = pd.read_csv(file)
print(flights.head(10))
print()

# This returns the total number of rows for each group.
flights_ct = flights.groupby(['ORG_AIR', 'DEST_AIR']).size()
print(flights_ct.head(10))
print()

# Get the number of flights between Atlanta and Houston in both directions.
print(flights_ct.loc[[('ATL', 'IAH'), ('IAH', 'ATL')]])
print()

# Sort the origin and destination cities:
# flights_sort = flights.sort_values(by=['ORG_AIR', 'DEST_AIR'], axis=1)
flights_sort = flights[['ORG_AIR', 'DEST_AIR']].apply(sorted, axis=1)
print(flights_sort.head(10))
print()

# Passing just the first row.
print(sorted(flights.loc[0, ['ORG_AIR', 'DEST_AIR']]))
print()

# Once each row is independently sorted, the column name are no longer correct.
# We will rename them to something generic, then again find the total number of flights between all cities.
rename_dict = {'ORG_AIR': 'AIR1', 'DEST_AIR': 'AIR2'}
flights_sort = flights_sort.rename(columns=rename_dict)
flights_ct2 = flights_sort.groupby(['AIR1', 'AIR2']).size()
print(flights_ct2.head(10))
print()
</code>```

When I get to this line of code my output differs from the authors:

```<code>```flights_sort = flights[['ORG_AIR', 'DEST_AIR']].apply(sorted, axis=1)```
</code>```

My output does not contain any column names.  As a result, when I get to:

```<code>```flights_ct2 = flights_sort.groupby(['AIR1', 'AIR2']).size()```
</code>```

it throws a KeyError.  This makes sense, as I am trying to rename columns when no column names exist.

My question is, why are the column names gone?  All other output matches the authors output exactly:

```<code>Connected to pydev debugger (build 191.7141.48)
NumPy: 1.16.3
Pandas: 0.24.2
-----
   MONTH  DAY  WEEKDAY AIRLINE ORG_AIR DEST_AIR  SCHED_DEP  DEP_DELAY  AIR_TIME  DIST  SCHED_ARR  ARR_DELAY  DIVERTED  CANCELLED
0      1    1        4      WN     LAX      SLC       1625       58.0      94.0   590       1905       65.0         0          0
1      1    1        4      UA     DEN      IAD        823        7.0     154.0  1452       1333      -13.0         0          0
2      1    1        4      MQ     DFW      VPS       1305       36.0      85.0   641       1453       35.0         0          0
3      1    1        4      AA     DFW      DCA       1555        7.0     126.0  1192       1935       -7.0         0          0
4      1    1        4      WN     LAX      MCI       1720       48.0     166.0  1363       2225       39.0         0          0
5      1    1        4      UA     IAH      SAN       1450        1.0     178.0  1303       1620      -14.0         0          0
6      1    1        4      AA     DFW      MSY       1250       84.0      64.0   447       1410       83.0         0          0
7      1    1        4      F9     SFO      PHX       1020       -7.0      91.0   651       1315       -6.0         0          0
8      1    1        4      AA     ORD      STL       1845       -5.0      44.0   258       1950       -5.0         0          0
9      1    1        4      UA     IAH      SJC        925        3.0     215.0  1608       1136      -14.0         0          0

ORG_AIR  DEST_AIR
ATL      ABE         31
         ABQ         16
         ABY         19
         ACY          6
         AEX         40
         AGS         83
         ALB         33
         ANC          2
         ASE          1
         ATW         10
dtype: int64

ORG_AIR  DEST_AIR
ATL      IAH         121
IAH      ATL         148
dtype: int64

*** No columns names ***  Why?

0    [LAX, SLC]
1    [DEN, IAD]
2    [DFW, VPS]
3    [DCA, DFW]
4    [LAX, MCI]
5    [IAH, SAN]
6    [DFW, MSY]
7    [PHX, SFO]
8    [ORD, STL]
9    [IAH, SJC]
dtype: object
</code>```

The author's output. Note the columns names are present.

答:
sorted returns a list object and obliterates the columns:

```<code>In [11]: df = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"])

In [12]: df.apply(sorted, axis=1)
Out[12]:
0    [1, 2]
1    [3, 4]
dtype: object

In [13]: type(df.apply(sorted, axis=1).iloc[0])
Out[13]: list
</code>```

It's possible that this wouldn't have been the case in earlier pandas... but it would still be bad code.

You can do this by passing the columns explicitly:

```<code>In [14]: df.apply(lambda x: pd.Series(sorted(x), df.columns), axis=1)
Out[14]:
   A  B
0  1  2
1  3  4
</code>```

A more efficient way to do this is to sort the sort the underlying numpy array:

```<code>In [21]: df = pd.DataFrame([[1, 2], [3, 1]], columns=["A", "B"])

In [22]: df
Out[22]:
   A  B
0  1  2
1  3  1

In [23]: arr = df[["A", "B"]].values

In [24]: arr.sort(axis=1)

In [25]: df[["A", "B"]] = arr

In [26]: df
Out[26]:
   A  B
0  1  2
1  1  3
</code>```

As you can see this sorts each row.

Body:
Working through Pandas Cookbook.  Counting the Total Number of Flights Between Cities.

import pandas as pd
import numpy as np
# import matplotlib.pyplot as plt

print('NumPy: {}'.format(np.__version__))
print('Pandas: {}'.format(pd.__version__))
print('-----')

desired_width = 320
pd.set_option('display.width', desired_width)
pd.options.display.max_rows = 50
pd.options.display.max_columns = 14
# pd.options.display.float_format = '{:,.2f}'.format

file = "e:\\packt\\data_analysis_and_exploration_with_pandas\\section07\\data\\flights.csv"
flights = pd.read_csv(file)
print(flights.head(10))
print()

# This returns the total number of rows for each group.
flights_ct = flights.groupby(['ORG_AIR', 'DEST_AIR']).size()
print(flights_ct.head(10))
print()

# Get the number of flights between Atlanta and Houston in both directions.
print(flights_ct.loc[[('ATL', 'IAH'), ('IAH', 'ATL')]])
print()

# Sort the origin and destination cities:
# flights_sort = flights.sort_values(by=['ORG_AIR', 'DEST_AIR'], axis=1)
flights_sort = flights[['ORG_AIR', 'DEST_AIR']].apply(sorted, axis=1)
print(flights_sort.head(10))
print()

# Passing just the first row.
print(sorted(flights.loc[0, ['ORG_AIR', 'DEST_AIR']]))
print()

# Once each row is independently sorted, the column name are no longer correct.
# We will rename them to something generic, then again find the total number of flights between all cities.
rename_dict = {'ORG_AIR': 'AIR1', 'DEST_AIR': 'AIR2'}
flights_sort = flights_sort.rename(columns=rename_dict)
flights_ct2 = flights_sort.groupby(['AIR1', 'AIR2']).size()
print(flights_ct2.head(10))
print()

When I get to this line of code my output differs from the authors:

```flights_sort = flights[['ORG_AIR', 'DEST_AIR']].apply(sorted, axis=1)```

My output does not contain any column names.  As a result, when I get to:

```flights_ct2 = flights_sort.groupby(['AIR1', 'AIR2']).size()```

it throws a KeyError.  This makes sense, as I am trying to rename columns when no column names exist.

My question is, why are the column names gone?  All other output matches the authors output exactly:

Connected to pydev debugger (build 191.7141.48)
NumPy: 1.16.3
Pandas: 0.24.2
-----
   MONTH  DAY  WEEKDAY AIRLINE ORG_AIR DEST_AIR  SCHED_DEP  DEP_DELAY  AIR_TIME  DIST  SCHED_ARR  ARR_DELAY  DIVERTED  CANCELLED
0      1    1        4      WN     LAX      SLC       1625       58.0      94.0   590       1905       65.0         0          0
1      1    1        4      UA     DEN      IAD        823        7.0     154.0  1452       1333      -13.0         0          0
2      1    1        4      MQ     DFW      VPS       1305       36.0      85.0   641       1453       35.0         0          0
3      1    1        4      AA     DFW      DCA       1555        7.0     126.0  1192       1935       -7.0         0          0
4      1    1        4      WN     LAX      MCI       1720       48.0     166.0  1363       2225       39.0         0          0
5      1    1        4      UA     IAH      SAN       1450        1.0     178.0  1303       1620      -14.0         0          0
6      1    1        4      AA     DFW      MSY       1250       84.0      64.0   447       1410       83.0         0          0
7      1    1        4      F9     SFO      PHX       1020       -7.0      91.0   651       1315       -6.0         0          0
8      1    1        4      AA     ORD      STL       1845       -5.0      44.0   258       1950       -5.0         0          0
9      1    1        4      UA     IAH      SJC        925        3.0     215.0  1608       1136      -14.0         0          0

ORG_AIR  DEST_AIR
ATL      ABE         31
         ABQ         16
         ABY         19
         ACY          6
         AEX         40
         AGS         83
         ALB         33
         ANC          2
         ASE          1
         ATW         10
dtype: int64

ORG_AIR  DEST_AIR
ATL      IAH         121
IAH      ATL         148
dtype: int64

*** No columns names ***  Why?

0    [LAX, SLC]
1    [DEN, IAD]
2    [DFW, VPS]
3    [DCA, DFW]
4    [LAX, MCI]
5    [IAH, SAN]
6    [DFW, MSY]
7    [PHX, SFO]
8    [ORD, STL]
9    [IAH, SJC]
dtype: object

The author's output. Note the columns names are present.

Body:
sorted returns a list object and obliterates the columns:

In [11]: df = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"])

In [12]: df.apply(sorted, axis=1)
Out[12]:
0    [1, 2]
1    [3, 4]
dtype: object

In [13]: type(df.apply(sorted, axis=1).iloc[0])
Out[13]: list

It's possible that this wouldn't have been the case in earlier pandas... but it would still be bad code.

You can do this by passing the columns explicitly:

In [14]: df.apply(lambda x: pd.Series(sorted(x), df.columns), axis=1)
Out[14]:
   A  B
0  1  2
1  3  4

A more efficient way to do this is to sort the sort the underlying numpy array:

In [21]: df = pd.DataFrame([[1, 2], [3, 1]], columns=["A", "B"])

In [22]: df
Out[22]:
   A  B
0  1  2
1  3  1

In [23]: arr = df[["A", "B"]].values

In [24]: arr.sort(axis=1)

In [25]: df[["A", "B"]] = arr

In [26]: df
Out[26]:
   A  B
0  1  2
1  1  3

As you can see this sorts each row.


问:
“Non Zero Exit Status” R 3.6.0 "Biobase"
I need to install different packages on R. The OS is ubuntu for windows. When I try "BiocManager::install("Biobase") I get the following error:

```<code>** R
** data
** inst
** byte-compile and prepare package for lazy loading
** help
*** installing help indices
** building package indices
** installing vignettes
** testing if installed package can be loaded from temporary location
** checking absolute paths in shared objects and dynamic libraries
mv: cannot move '/home/mark/R/x86_64-pc-linux-gnu-library/3.6/00LOCK-Biobase/00new/Biobase' to '/home/mark/R/x86_64-pc-linux-gnu-library/3.6/Biobase': Permission denied
ERROR:   moving to final location failed
</code>```

There seems to be something wrong with the permission to move certain files.. I already tried giving permission to write for everyone into the /3.6 directory, This didn't change anything.

Any solutions?

答:
Apparently, this is a new feature in 3.6.  But this should solve your problem:

Sys.setenv(R_INSTALL_STAGED = FALSE)

Body:
I need to install different packages on R. The OS is ubuntu for windows. When I try "BiocManager::install("Biobase") I get the following error:

** R
** data
** inst
** byte-compile and prepare package for lazy loading
** help
*** installing help indices
** building package indices
** installing vignettes
** testing if installed package can be loaded from temporary location
** checking absolute paths in shared objects and dynamic libraries
mv: cannot move '/home/mark/R/x86_64-pc-linux-gnu-library/3.6/00LOCK-Biobase/00new/Biobase' to '/home/mark/R/x86_64-pc-linux-gnu-library/3.6/Biobase': Permission denied
ERROR:   moving to final location failed

There seems to be something wrong with the permission to move certain files.. I already tried giving permission to write for everyone into the /3.6 directory, This didn't change anything.

Any solutions?


问:
Cannot access Qliksense url outside Azure Vnet
I am new to Qliksense and Azure. We have installed Qliksense in Azure Virtual machine. Trying to access the Qliksense hub/QMC URL (https://xxx.intranet.myclient.com/hub) from the internet/outside the azure Network, but was unsuccessful. The url is working well in the intranet.

Azure VM has a private ip address.

Created inbound rules in NSG(Network Security group) at Azure to open ports 443,80, 4244.
2.Created firewall inbound rule in VM server to open ports 80, 443, 4244, 4243, 4248, 4242

Added the url to the host white list at the virtual proxy side in Qlik QMC

May I know what wrong am doing or what I am missing here?

答:
Firstly, If you want to access qlik url to work from the internet, you need a public IP address attached to the Azure VM or load balancer service like Azure application gateway in front of Azure VM with a public IP address. Refer to this. If you have no public IP address, you can directly deploy one and attach to the VM network interface on the Azure portal. Try to restart the Azure VM or refresh VM.

Then, make sure you have a DNS map which is pointing FQDN xxx.intranet.myclient.com to your VM public IP address. You can try to access the Qliksense hub/QMC URL like https://PublicIPaddress/hub first.

Also, you can run the command netstat -anbo as the administrator in the CMD to check if the port is listening on Qliksense service. Try to telnet or Test-NetConnection the Qliksense URL before you access the Qliksense URL on the remote machine.

If the above all are no effect, you can look at this. Let me know if this works.


问:
Can't understand &(sizeof 2[a])[a]
I've got some code that outputs bcdefg and I can't understand why.

I google searched but I couldn't find anything.

```<code>const char a[]="Abcdefg";
printf("%s",&(sizeof 2[a])[a]);
</code>```

Why is the output bcdefg, and not Abcdefg?

答:
Referring to the code excerpt:

```<code>printf("%s",&(sizeof 2[a])[a]);
</code>```

First, most people don't realize it, but the [] operator it actually commutative.  a[b] is equivalent to *(a + b), which is equivalent to *(b + a), which is equivalent to b[a].

So 2[a] is equivalent to a[2].  Since a has type const char [], the size of an element is the same as sizeof(char), which is 1.

So we now have:

```<code>printf("%s",&1[a]);
</code>```

Well, 1[a] is equivalent to a[1], or *(a + 1).  Applying the address-of operator gives &a[1], or a + 1 (note that &*x is just x).

So we have:

```<code>printf("%s", a + 1);
</code>```

This just prints the string pointed to by a + 1, i.e. everything after the first character of a.

If you just reorder the [] operators without doing anything else, you can see that it's equivalent to:

```<code>printf("%s", &a[sizeof a[2]]);
</code>```

Title: Can't understand &(sizeof 2[a])[a]

Body:
I've got some code that outputs bcdefg and I can't understand why.

I google searched but I couldn't find anything.

const char a[]="Abcdefg";
printf("%s",&(sizeof 2[a])[a]);

Why is the output bcdefg, and not Abcdefg?

Body:
Referring to the code excerpt:

printf("%s",&(sizeof 2[a])[a]);

First, most people don't realize it, but the [] operator it actually commutative.  a[b] is equivalent to *(a + b), which is equivalent to *(b + a), which is equivalent to b[a].

So 2[a] is equivalent to a[2].  Since a has type const char [], the size of an element is the same as sizeof(char), which is 1.

So we now have:

printf("%s",&1[a]);

Well, 1[a] is equivalent to a[1], or *(a + 1).  Applying the address-of operator gives &a[1], or a + 1 (note that &*x is just x).

So we have:

printf("%s", a + 1);

This just prints the string pointed to by a + 1, i.e. everything after the first character of a.

If you just reorder the [] operators without doing anything else, you can see that it's equivalent to:

printf("%s", &a[sizeof a[2]]);


问:
How to make a Vuetify rule async and await with a ajax call
I am using Vuetify form validation to check an input field, and I'm trying to figure out if it's possible to call a ajax get call and make it await so that I can use the result in a rule?

I've attempted it below, but it doesn't seem to work!

```<code>export default {
  data() {
    return {
      rules: {
        isLocationNew: value => {

          if (value == '' || value == null || value.length <= 1) {
            this.validLocation = false;
            return 'Invalid length.';
          }

          this.validLocation = true;

          var hasName = this.newLocationNameSearch(value);
          if (hasName) {
            return 'Location name already exists.';
          } else {
            return true;
          }
        }
      },

      // down in methods
      methods: {
        async newLocationNameSearch(text) {
          if (text == '' || text == null || text.length <= 1) {
            return false;
          }

          await axios.get('/api/Locations/HasLocationName', {
            params: {
              text: text,
              jobsiteId: this.jobsiteId
            }
          }).then(response => {
            return response.data;
          }).catch(function(error) {
            console.log(error)
          })

        }
      }
</code>```

答:
```<code>methods: {
  fetchUserData: async function() {
      const response = await fetch(
            "https://jsonplaceholder.typicode.com/users"
      );
      this.users = await response.json();
}
</code>```

You can use it like this example.

Body:
I am using Vuetify form validation to check an input field, and I'm trying to figure out if it's possible to call a ajax get call and make it await so that I can use the result in a rule?

I've attempted it below, but it doesn't seem to work!

export default {
  data() {
    return {
      rules: {
        isLocationNew: value => {

          if (value == '' || value == null || value.length <= 1) {
            this.validLocation = false;
            return 'Invalid length.';
          }

          this.validLocation = true;

          var hasName = this.newLocationNameSearch(value);
          if (hasName) {
            return 'Location name already exists.';
          } else {
            return true;
          }
        }
      },

      // down in methods
      methods: {
        async newLocationNameSearch(text) {
          if (text == '' || text == null || text.length <= 1) {
            return false;
          }

          await axios.get('/api/Locations/HasLocationName', {
            params: {
              text: text,
              jobsiteId: this.jobsiteId
            }
          }).then(response => {
            return response.data;
          }).catch(function(error) {
            console.log(error)
          })

        }
      }

Body:
methods: {
  fetchUserData: async function() {
      const response = await fetch(
            "https://jsonplaceholder.typicode.com/users"
      );
      this.users = await response.json();
}

You can use it like this example.


问:
C# : We application : Where to store generated PDF files?
I am developing web application (Hosted on azure cloud service) which is generating PDF. Those PDFs, have to be store at some place because it will get downloaded later. So where to store those files ?

Right now storing it in 'Content' folder of project but issue is when I publish site again 'Content' folder gets empty.

So, having issue with storing files. What is the best way to store it ? To store it in DB or anywhere in cloud services. Can not use azure storage, client don't want to use it.

Please help me with issue.

答:
Using storage is best practice, and it has a lower cost per GB than most other options in Azure. If the costs at scale are a problem, there are options to move files from hot to cool storage to reduce the per GB cost as data builds up.

You do need to store them in some sort of persistent storage, which Cloud Services does not offer. A database would work, as would deploying the application to a regular VM rather than Cloud Services. App Services has persistent storage, as the files are stored in Azure Storage and not on the VM, if that is an option. There are plenty of other options, and any sort of file share will work.


问:
Unable to bind DataTemplateColumn element to another DataTemplateColumn
I am trying to  set an element in each DataGrid row by setting another element in the same row.

If IsChecked of the ToggleButton is True, image in the ContentControl will become visible.

I have cannibalised this example to try to get this to work. This example seems similiar too and I hope I am not duplicating anything.

This is the code snippet from my implementation of the DataGrid:

```<code><Grid>
    <StackPanel>
        <Grid Margin="0" Grid.Column="0" Grid.Row="3">
            <DataGrid
              ItemsSource="{Binding Path=. , Mode=OneWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}"
              AutoGenerateColumns="False"
              Height="Auto"
              HorizontalAlignment="Left"
              VerticalAlignment="Top"
              ScrollViewer.CanContentScroll="True"
              ScrollViewer.VerticalScrollBarVisibility="Visible"
              x:Name="Filter_grid"
              Grid.Row="1">
                <DataGrid.Columns >
                    <DataGridTextColumn Header="CAN ID"  Binding="{Binding Information.CAN_ID}" Width="50" />
                    <DataGridTextColumn Header="Messagen Name" Binding="{Binding Information.CAN_ID_description}" Width="300" />
                    <DataGridTextColumn Binding="{Binding Information.Status}" Width="50" />
                    <DataGridTemplateColumn Header = "Filter ON" Width="SizeToCells" IsReadOnly="True">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <ContentControl Content="{Binding Information.Tick}">
                                    <ContentControl.Style>
                                        <Style TargetType = "ContentControl" >
                                            <Setter Property="Visibility" Value="Hidden"/>
                                            <Style.Triggers>
                                                <DataTrigger  Binding = "{Binding  Path=IsChecked, ElementName=Filter_on}" Value="True">
                                                    <Setter Property = "Visibility" Value="Visible"/>
                                                </DataTrigger>
                                            </Style.Triggers>
                                        </Style>
                                    </ContentControl.Style>
                                </ContentControl>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                    <DataGridTemplateColumn x:Name="F_column" Header ="Select">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <ToggleButton  x:Name="Filter_on" Content="Switch" />
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                </DataGrid.Columns>
            </DataGrid>
        </Grid>
    </StackPanel>
</Grid>
</code>```

I am unable to get the ElementName to find the ToggleBox and get Cannot find source for binding with reference 'ElementName=Filter_on'.

I have tried doing similiar with

<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridTemplateColumn}}, Path=F_column.Filter_on}" Value="True">, or using x:Reference which throws me an exception I can't decipher.

答:
First things first: you should never do this. XAML is very flexible and allows you to do some terribly clever things, but just because you can doesn't mean you should. The correct solution in this case is to create a view model for each row element with a boolean property that both the button and your data trigger can bind to. Apart from being more flexible it's also much easier to test, debug and log etc.

That said, what you are asking is technically possible. DataGrids are actually quite complex due to various optimizations they employ etc, so you still need to use an intermediate property, but since you don't want to use a view model you'll have to use the Tag property in the button's DataGridCell instead (which can be used for arbitrary user data):

Bind the button's IsChecked property to do a one-way-to-source binding to it's parent DataGridCell's Tag property.

Bind the DataTrigger to find the parent DataGridCellsPanel, and then bind directly to the appropriate child's Tag property i.e. Children[1].Tag.

Put it together and you get this:

```<code><DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
    <DataGrid.Columns>

        <DataGridTemplateColumn Header = "Filter ON" Width="SizeToCells" IsReadOnly="True">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ContentControl>
                        <ContentControl.Style>
                            <Style TargetType = "ContentControl" >
                                <Setter Property="Visibility" Value="Hidden"/>
                                <Style.Triggers>
                                    <DataTrigger  Binding = "{Binding Path=Children[1].Tag, RelativeSource={RelativeSource AncestorType={x:Type DataGridCellsPanel}}}" Value="True">
                                        <Setter Property = "Visibility" Value="Visible"/>
                                    </DataTrigger>
                                </Style.Triggers>
                            </Style>
                        </ContentControl.Style>
                        <TextBlock Text="Content goes here" />
                    </ContentControl>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

        <DataGridTemplateColumn x:Name="F_column" Header ="Select">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ToggleButton x:Name="Filter_on" Content="Switch" IsChecked="{Binding Path=Tag, RelativeSource={RelativeSource AncestorType=DataGridCell}, Mode=OneWayToSource}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

    </DataGrid.Columns>

</DataGrid>
</code>```

But seriously...just use a view model.

Body:
I am trying to  set an element in each DataGrid row by setting another element in the same row.

If IsChecked of the ToggleButton is True, image in the ContentControl will become visible.

I have cannibalised this example to try to get this to work. This example seems similiar too and I hope I am not duplicating anything.

This is the code snippet from my implementation of the DataGrid:

<Grid>
    <StackPanel>
        <Grid Margin="0" Grid.Column="0" Grid.Row="3">
            <DataGrid
              ItemsSource="{Binding Path=. , Mode=OneWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}"
              AutoGenerateColumns="False"
              Height="Auto"
              HorizontalAlignment="Left"
              VerticalAlignment="Top"
              ScrollViewer.CanContentScroll="True"
              ScrollViewer.VerticalScrollBarVisibility="Visible"
              x:Name="Filter_grid"
              Grid.Row="1">
                <DataGrid.Columns >
                    <DataGridTextColumn Header="CAN ID"  Binding="{Binding Information.CAN_ID}" Width="50" />
                    <DataGridTextColumn Header="Messagen Name" Binding="{Binding Information.CAN_ID_description}" Width="300" />
                    <DataGridTextColumn Binding="{Binding Information.Status}" Width="50" />
                    <DataGridTemplateColumn Header = "Filter ON" Width="SizeToCells" IsReadOnly="True">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <ContentControl Content="{Binding Information.Tick}">
                                    <ContentControl.Style>

                                        </Style>
                                    </ContentControl.Style>
                                </ContentControl>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                    <DataGridTemplateColumn x:Name="F_column" Header ="Select">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <ToggleButton  x:Name="Filter_on" Content="Switch" />
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                </DataGrid.Columns>
            </DataGrid>
        </Grid>
    </StackPanel>
</Grid>

I am unable to get the ElementName to find the ToggleBox and get Cannot find source for binding with reference 'ElementName=Filter_on'.

I have tried doing similiar with

<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridTemplateColumn}}, Path=F_column.Filter_on}" Value="True">, or using x:Reference which throws me an exception I can't decipher.

Body:
First things first: you should never do this. XAML is very flexible and allows you to do some terribly clever things, but just because you can doesn't mean you should. The correct solution in this case is to create a view model for each row element with a boolean property that both the button and your data trigger can bind to. Apart from being more flexible it's also much easier to test, debug and log etc.

That said, what you are asking is technically possible. DataGrids are actually quite complex due to various optimizations they employ etc, so you still need to use an intermediate property, but since you don't want to use a view model you'll have to use the Tag property in the button's DataGridCell instead (which can be used for arbitrary user data):

Bind the button's IsChecked property to do a one-way-to-source binding to it's parent DataGridCell's Tag property.

Bind the DataTrigger to find the parent DataGridCellsPanel, and then bind directly to the appropriate child's Tag property i.e. Children[1].Tag.

Put it together and you get this:

<DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
    <DataGrid.Columns>

        <DataGridTemplateColumn Header = "Filter ON" Width="SizeToCells" IsReadOnly="True">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ContentControl>
                        <ContentControl.Style>
                            <Style TargetType = "ContentControl" >
                                <Setter Property="Visibility" Value="Hidden"/>
                                <Style.Triggers>
                                    <DataTrigger  Binding = "{Binding Path=Children[1].Tag, RelativeSource={RelativeSource AncestorType={x:Type DataGridCellsPanel}}}" Value="True">
                                        <Setter Property = "Visibility" Value="Visible"/>
                                    </DataTrigger>
                                </Style.Triggers>
                            </Style>
                        </ContentControl.Style>
                        <TextBlock Text="Content goes here" />
                    </ContentControl>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

        <DataGridTemplateColumn x:Name="F_column" Header ="Select">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ToggleButton x:Name="Filter_on" Content="Switch" IsChecked="{Binding Path=Tag, RelativeSource={RelativeSource AncestorType=DataGridCell}, Mode=OneWayToSource}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

    </DataGrid.Columns>

</DataGrid>

But seriously...just use a view model.


问:
Laravel String To Lower
I'm trying to convert a string to lowercase in a views page (index.blade.php)

The following is what I would like to achieve.

```<code><img src="images/teamnamesml.jpg logo">
</code>```

This is my attempt

```<code><img src="images/{{ Str::lower($matchup->visitorTeam) }}sml.jpg">
</code>```

I get this error

```<code>FatalErrorException in ed1bb29e73e623d0f837c841ed066275 line 71:
Class 'Str' not found
</code>```

Do I have to import the class Illuminate\Support\Str to a specific file?

答: Consider using mb_strtolower to be able to convert any character that has 'alphabetic' property, such as Č, Ć etc.

ContentLicense: CC BY-SA 3.0

Title: Laravel String To Lower

Body:
I'm trying to convert a string to lowercase in a views page (index.blade.php)

The following is what I would like to achieve.

This is my attempt

visitorTeam) }}sml.jpg">

I get this error

FatalErrorException in ed1bb29e73e623d0f837c841ed066275 line 71:
Class 'Str' not found

Do I have to import the class Illuminate\Support\Str to a specific file?


问:
Load pdf file to jar already built
I'm trying to get some specific data from a pdf and save it in a database. The idea is that in my program when you press a button, with selenium, the program downloads the pdf and uploads it to the jar in order to read it.

I tried many libraries to read pdfs but all seems to be stuck in the same place: when I try to load the pdf.

If I compile the program in IntelliJ it works perfect, the problem is when I compile it to .jar. It gets stuck when loading and does not show an error. Tried everything I could but nothing works.

Heres how my code looks right now:

```<code>              try {

                    PdfReader reader = new PdfReader("out/artifacts/WAsNEWWINDOWS_jar/bills/facturaClaro.pdf");
                    System.out.println("This PDF has "+reader.getNumberOfPages()+" pages.");
                    String page = PdfTextExtractor.getTextFromPage(reader, 2);
                    System.out.println("Page Content:\n\n"+page+"\n\n");
                    System.out.println("Is this document tampered: "+reader.isTampered());
                    System.out.println("Is this document encrypted: "+reader.isEncrypted());
                } catch (IOException e) {
                    e.printStackTrace();
                }
</code>```

The coding like this works perfect in IntelliJ, and when I compile it to .jar I change the location of the file like this:

```<code>PdfReader reader = new PdfReader("bills/facturaClaro.pdf");
</code>```

Any contribution can help me. Thank you so much!

EDIT: I would like to clarify that for now I'm not downloading the pdf, I just copy the pdf file in the same directory as the .jar.

UPDATE: apparently it was throwing an exception:

```<code>
java.lang.NoClassDefFoundError: com/itextpdf/text/pdf/PdfReader
    at BillReader.readClaro(BillReader.java:195)
    at WebScrapper.startBillReaderClaro(WebScrapper.java:467)
    at Controller$20.call(Controller.java:4182)
    at Controller$20.call(Controller.java:4179)
    at javafx.concurrent.Task$TaskCallable.call(Task.java:1423)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassNotFoundException: com.itextpdf.text.pdf.PdfReader
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 7 more
</code>```

I search for a solution but nothing works. Please help me! Thank you

EDIT: my pom.xml looks like this btw, no repetition of dependencies

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

    <groupId>WAs</groupId>
    <artifactId>seleWA</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>com.zenjava</groupId>
                <artifactId>javafx-maven-plugin</artifactId>
                <version>8.8.3</version>
                <configuration>
                    <appName>SimManager</appName>
                    <vendor>YourCompany</vendor>
                    <mainClass>SimManager</mainClass>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>sample.Main</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/java/excel</directory>
                <includes>
                    <include>*.*</include>
                </includes>
            </resource>
        </resources>
    </build>
    <repositories>
        <repository>
            <id>jitpack.io</id>
            <url>https://jitpack.io</url>
        </repository>
        <repository>
            <id>jcenter</id>
            <url>https://jcenter.bintray.com/</url>
        </repository>
    </repositories>
    <dependencies>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.13.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.16</version>
        </dependency>

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

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.5.0-b01</version>
        </dependency>

        <dependency>
            <groupId>org.jfree</groupId>
            <artifactId>jfreechart</artifactId>
            <version>1.0.19</version>
        </dependency>

        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox-app</artifactId>
            <version>2.0.15</version>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>com.liferay</groupId>
            <artifactId>com.liferay.document.library.service</artifactId>
            <version>1.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.simplejavamail</groupId>
            <artifactId>simple-java-mail</artifactId>
            <version>5.0.8</version>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.8</version>
        </dependency>

        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>

            <artifactId>quartz-jobs</artifactId>
            <version>2.2.1</version>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20090211</version>
        </dependency>

        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>3.1.1</version>
            <scope>compile</scope>
        </dependency>

        <!--<dependency>
            <groupId>com.github.Lamba92</groupId>
            <artifactId>kresourceloader</artifactId>
        </dependency>-->

        <dependency>
            <groupId>com.lynden</groupId>
            <artifactId>GMapsFX</artifactId>
            <version>2.10.0</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.6</version>
        </dependency>

        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15</artifactId>
            <version>1.44</version>
        </dependency>

        <dependency>
            <groupId>com.ibm.icu</groupId>
            <artifactId>icu4j</artifactId>
            <version>3.8</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13</version>
            <scope>compile</scope>
        </dependency>

    </dependencies>

</project>
</code>```

project structure libraries
libraries

答:
I could solve it !. I just analyzed the .jar with the command:

```<code>jar tvf WAsNEWWINDOWS.jar
</code>```

and I realize that indeed, the necessary class was not there. As I had already seen the libraries in the project structure in IntelliJ, I looked at the artifacts extracted, and I could see that iText was not there, so I added it as "extracted directory" and searched where the iText .jar was and thats it! . Compile the jar again and there wasn't any error and it works perfect !. I leave an image where you need to add the .jar:

intellij extract directory

Title: Load pdf file to jar already built

Body:
I'm trying to get some specific data from a pdf and save it in a database. The idea is that in my program when you press a button, with selenium, the program downloads the pdf and uploads it to the jar in order to read it.

I tried many libraries to read pdfs but all seems to be stuck in the same place: when I try to load the pdf.

If I compile the program in IntelliJ it works perfect, the problem is when I compile it to .jar. It gets stuck when loading and does not show an error. Tried everything I could but nothing works.

Heres how my code looks right now:

              try {

                    PdfReader reader = new PdfReader("out/artifacts/WAsNEWWINDOWS_jar/bills/facturaClaro.pdf");
                    System.out.println("This PDF has "+reader.getNumberOfPages()+" pages.");
                    String page = PdfTextExtractor.getTextFromPage(reader, 2);
                    System.out.println("Page Content:\n\n"+page+"\n\n");
                    System.out.println("Is this document tampered: "+reader.isTampered());
                    System.out.println("Is this document encrypted: "+reader.isEncrypted());
                } catch (IOException e) {
                    e.printStackTrace();
                }

The coding like this works perfect in IntelliJ, and when I compile it to .jar I change the location of the file like this:

PdfReader reader = new PdfReader("bills/facturaClaro.pdf");

Any contribution can help me. Thank you so much!

EDIT: I would like to clarify that for now I'm not downloading the pdf, I just copy the pdf file in the same directory as the .jar.

UPDATE: apparently it was throwing an exception:

java.lang.NoClassDefFoundError: com/itextpdf/text/pdf/PdfReader
    at BillReader.readClaro(BillReader.java:195)
    at WebScrapper.startBillReaderClaro(WebScrapper.java:467)
    at Controller$20.call(Controller.java:4182)
    at Controller$20.call(Controller.java:4179)
    at javafx.concurrent.Task$TaskCallable.call(Task.java:1423)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassNotFoundException: com.itextpdf.text.pdf.PdfReader
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 7 more

I search for a solution but nothing works. Please help me! Thank you

EDIT: my pom.xml looks like this btw, no repetition of dependencies

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

    <groupId>WAs</groupId>
    <artifactId>seleWA</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>com.zenjava</groupId>
                <artifactId>javafx-maven-plugin</artifactId>
                <version>8.8.3</version>
                <configuration>
                    <appName>SimManager</appName>
                    <vendor>YourCompany</vendor>
                    <mainClass>SimManager</mainClass>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>sample.Main</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/java/excel</directory>
                <includes>
                    <include>*.*</include>
                </includes>
            </resource>
        </resources>
    </build>
    <repositories>
        <repository>
            <id>jitpack.io</id>
            <url>https://jitpack.io</url>
        </repository>
        <repository>
            <id>jcenter</id>
            <url>https://jcenter.bintray.com/</url>
        </repository>
    </repositories>
    <dependencies>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.13.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.16</version>
        </dependency>

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

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.5.0-b01</version>
        </dependency>

        <dependency>
            <groupId>org.jfree</groupId>
            <artifactId>jfreechart</artifactId>
            <version>1.0.19</version>
        </dependency>

        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox-app</artifactId>
            <version>2.0.15</version>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>com.liferay</groupId>
            <artifactId>com.liferay.document.library.service</artifactId>
            <version>1.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.simplejavamail</groupId>
            <artifactId>simple-java-mail</artifactId>
            <version>5.0.8</version>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.8</version>
        </dependency>

        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>

            <artifactId>quartz-jobs</artifactId>
            <version>2.2.1</version>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20090211</version>
        </dependency>

        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>3.1.1</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>com.lynden</groupId>
            <artifactId>GMapsFX</artifactId>
            <version>2.10.0</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.6</version>
        </dependency>

        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15</artifactId>
            <version>1.44</version>
        </dependency>

        <dependency>
            <groupId>com.ibm.icu</groupId>
            <artifactId>icu4j</artifactId>
            <version>3.8</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13</version>
            <scope>compile</scope>
        </dependency>

    </dependencies>

</project>

project structure libraries
libraries

Body:
I could solve it !. I just analyzed the .jar with the command:

jar tvf WAsNEWWINDOWS.jar

and I realize that indeed, the necessary class was not there. As I had already seen the libraries in the project structure in IntelliJ, I looked at the artifacts extracted, and I could see that iText was not there, so I added it as "extracted directory" and searched where the iText .jar was and thats it! . Compile the jar again and there wasn't any error and it works perfect !. I leave an image where you need to add the .jar:

intellij extract directory


问:
appending the most common element in a CELL to a column pandas
This is related to a question I asked earlier, I'm posting this new one as I think its sufficiently unique and persistently difficult. I have a data frame of the form:

```<code>keyword       string                 match

A             "Varied String..."     ['string','string','test','string']
              "Varied String..."     ['string','string']
              "Varied String..."     ['test']
B             "Varied String..."     ['string,'string','test']
</code>```

Which was created via this code (which was written by @anky_91):

```<code>df1.groupby(df2.Type.ffill()).matches.apply(lambda x: ''.join(mode(list(chain.from_iterable(x)))[0]))
</code>```

My issue at this point, this creates a new column matches which is perfectly normal, however while I do want the mode, I only want the most frequent unique value. So instead of the match column being populated with a list mode, I'm trying to get it to just be the most frequent value of the mode so:

```<code> keyword           string               match

    A             "Varied String..."    'string'
    B             "Varied String..."    'string'
</code>```

I tried doing this:

df = freq_df['matches'].agg(lambda x: x.value_counts().index[0])

Which returns, the same thing unchanged. I then try,

df['matches'].value_counts()

Which returns inaccurate counts so I'm not sure whats going on with that.

Let me know if this is clear or not!

答:
Instead of using Series.str.findall() to retrieve matches into lists, you can use Series.str.extractall() to retrieve each matched word onto its own row which could make your task easier (below using your sample data in the previous post and removed the double quotes from the string column).

```<code># list of keywords
keyword_list=['string', 'test']

# regex pettern to retrieve only words matched from keywork_list
ptn = r'\b(' + '|'.join(keyword_list) + r')\b'

# get the list of matched words (assume `keyword` is already on index), if not, use the following
# s = df.set_index('keyword').string.str.extractall(ptn).reset_index(level=1, drop=True)[0]
s = df.string.str.extractall(ptn).reset_index(level=1, drop=True)[0]
print(s)
#keyword
#A      test
#A    string
#A      test
#A    string
#A    string
#A    string
#A      test
#A    string
#B      test
#B    string
#B      test
#B    string
#B      test
#Name: 0, dtype: object
</code>```

Next you can retrieve the top item by value_counts() for each keyword

```<code>s.groupby('keyword').apply(lambda x: x.value_counts().nlargest(1))
#keyword
#A        string    5
#B        test      3
#Name: 0, dtype: int64
</code>```

or just keyword and string without the count:

```<code>s.groupby('keyword').apply(lambda x: x.value_counts().idxmax())
#keyword
#A    string
#B      test
#Name: 0, dtype: object
</code>```

Body:
This is related to a question I asked earlier, I'm posting this new one as I think its sufficiently unique and persistently difficult. I have a data frame of the form:

keyword       string                 match

A             "Varied String..."     ['string','string','test','string']
              "Varied String..."     ['string','string']
              "Varied String..."     ['test']
B             "Varied String..."     ['string,'string','test']

Which was created via this code (which was written by @anky_91):

df1.groupby(df2.Type.ffill()).matches.apply(lambda x: ''.join(mode(list(chain.from_iterable(x)))[0]))

My issue at this point, this creates a new column matches which is perfectly normal, however while I do want the mode, I only want the most frequent unique value. So instead of the match column being populated with a list mode, I'm trying to get it to just be the most frequent value of the mode so:

 keyword           string               match

    A             "Varied String..."    'string'
    B             "Varied String..."    'string'

I tried doing this:

df = freq_df['matches'].agg(lambda x: x.value_counts().index[0])

Which returns, the same thing unchanged. I then try,

df['matches'].value_counts()

Which returns inaccurate counts so I'm not sure whats going on with that.

Let me know if this is clear or not!

Body:
Instead of using Series.str.findall() to retrieve matches into lists, you can use Series.str.extractall() to retrieve each matched word onto its own row which could make your task easier (below using your sample data in the previous post and removed the double quotes from the string column).

# list of keywords
keyword_list=['string', 'test']

# regex pettern to retrieve only words matched from keywork_list
ptn = r'\b(' + '|'.join(keyword_list) + r')\b'

# get the list of matched words (assume `keyword` is already on index), if not, use the following
# s = df.set_index('keyword').string.str.extractall(ptn).reset_index(level=1, drop=True)[0]
s = df.string.str.extractall(ptn).reset_index(level=1, drop=True)[0]
print(s)
#keyword
#A      test
#A    string
#A      test
#A    string
#A    string
#A    string
#A      test
#A    string
#B      test
#B    string
#B      test
#B    string
#B      test
#Name: 0, dtype: object

Next you can retrieve the top item by value_counts() for each keyword

s.groupby('keyword').apply(lambda x: x.value_counts().nlargest(1))
#keyword
#A        string    5
#B        test      3
#Name: 0, dtype: int64

or just keyword and string without the count:

s.groupby('keyword').apply(lambda x: x.value_counts().idxmax())
#keyword
#A    string
#B      test
#Name: 0, dtype: object


问:
Jenkinsfile - how to pass build argument to docker
As per this link we can pass image name & dockerfile location to build an image in following way

```<code>docker.build("my-image:${env.BUILD_ID}", "-f ${dockerfile} ./dockerfiles")
</code>```

I want to pass proxy settings to build command, Is there any way to pass it, similar to how we can pass in simple docker command.

```<code>docker build -t my-image --build-arg HTTP_PROXY=http://192.168.0.1:3128 ./dockerfiles
</code>```

答:
This works for me:</p>

```<code>def image = docker.build("myregistry.io/firstkey/secondkey/image:2.2.0-$BUILD_NUMBER", "--build-arg http_proxy=http://www-proxy.mycompany.com:80 --build-arg https_proxy=http://www-proxy.mycompay.com:80 --network host -f Dockerfile .")
</code>```

Body:
As per this link we can pass image name & dockerfile location to build an image in following way

docker.build("my-image:${env.BUILD_ID}", "-f ${dockerfile} ./dockerfiles")

I want to pass proxy settings to build command, Is there any way to pass it, similar to how we can pass in simple docker command.

docker build -t my-image --build-arg HTTP_PROXY=http://192.168.0.1:3128 ./dockerfiles

Body:
This works for me:

def image = docker.build("myregistry.io/firstkey/secondkey/image:2.2.0-$BUILD_NUMBER", "--build-arg http_proxy=http://www-proxy.mycompany.com:80 --build-arg https_proxy=http://www-proxy.mycompay.com:80 --network host -f Dockerfile .")


问:
How to replace with for loop statement by matching different files in shell/bash script
With my shell script i'm trying to match 2 different files and replace the occurencies in File1 with the lines of File2:

```<code>File1 occurency 1 <-- File2 row 1
File1 occurency 2 <-- File2 row 2
File1 occurency 3 <-- File2 row 3
...
</code>```

The number of rows in File 2 is equal to occurencies in File 1 because initialy they were taken from File 1

File1 - is a Json file

```<code>...
"@type" : "Review",
"@id":"https://google.com/social/profile/xxxxxxx.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",

"@type" : "Review",
"@id":"https://google.com/social/profile/xxxxxxx.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",
 ...
</code>```

File2 - is a formated "json like" file

```<code>"profilePhoto":"https://someurl.ltd/aaaa_90.jpg"
"profilePhoto":"https://someurl.ltd/bbbb_90.jpg"
"profilePhoto":"https://someurl.ltd/cccc_90.jpg"
 ....
</code>```

Actually the part of script that have to make this job looks like

```<code>IFS=$'\n'
set -f
for i in $(cat < File2.txt); do

sed -i "s|.*social.*|$i|g" File1.json

done
</code>```

This script replace all occurencies in File1 with the first line of File2, so on second loop there is no more matching to find.
output example

```<code>...
"@type" : "Review",
"profilePhoto":"https://someurl.ltd/cccc_90.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",

"@type" : "Review",
"profilePhoto":"https://someurl.ltd/cccc_90.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",
 ...
</code>```

I need instead the output like this

```<code>...
"@type" : "Review",
*"profilePhoto":"https://someurl.ltd/**aaaa**_90.jpg"*
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",

"@type" : "Review",
*"profilePhoto":"https://someurl.ltd/**bbbb**_90.jpg"*
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",
 ...
</code>```

Thank you in advance for any help.

答:
Edit:

After reviewing what your desired output a lot closer i came up with this

```<code>for i in $(sed 's/^/*/;s|ltd/|&**|;s|_|**&|;s/$/*/' File2.txt); do awk -i inplace -v i="$i" 'NR==1,/.*social.*/{sub(/.*social.*/, i)} 1' File1.json; done
</code>```

Once you limit the substitution in File1.json to only the first occurrence you can let the loop work for you.

To break it down

```<code># Instead of cat file I tackled substitution for each line in File2.txt as $i
for i in $(sed 's/^/*/;s|ltd/|&**|;s|_|**&|;s/$/*/' File2.txt); do

    # Here awk sub only first occurrence to not overwrite whole file
    # Second loop will handle the next occurrence with second line from File2.txt
    # And third ect.. ect..
    awk -i inplace -v i="$i" 'NR==1,/.*social.*/{sub(/.*social.*/, i)} 1' File1.json
done
</code>```

Everything below is if your version of awk does not support -i inplace then you will have to do this

```<code>awk -v i="$i" 'NR==1,/.*social.*/{sub(/.*social.*/, i)} 1 { rec = rec $0 RS } END { close(FILENAME); printf "%s", rec > FILENAME }' File1.json
</code>```

So the whole thing will look like

```<code> # Instead of cat file I tackled substitution for each line in File2.txt as $i
for i in $(sed 's/^/*/;s|ltd/|&**|;s|_|**&|;s/$/*/' File2.txt); do

    # Here awk sub only first occurrence to not overwrite whole file
    # Second loop will handle the next occurrence with second line from File2.txt
    # And third ect.. ect..
    awk -v i="$i" 'NR==1,/.*social.*/{sub(/.*social.*/, i)} 1 { rec = rec $0 RS } END { close(FILENAME); printf "%s", rec > FILENAME }' File1.json
done
</code>```

Finally if you neither of the above awk commands work you can result to temp files.

```<code>awk -v i="$i" 'NR==1,/.*social.*/{sub(/.*social.*/, i)} 1' File1.json > tmpfile && mv tmpfile File1.json
</code>```

so the whole thing will look like this

```<code>for i in `cat File2.txt`; do

 awk -v i="$i" 'NR==1,/.*social.*/{sub(/.*social.*/, i)} 1' File1.json > tmpfile && mv tmpfile File1.json

done
</code>```

Body:
With my shell script i'm trying to match 2 different files and replace the occurencies in File1 with the lines of File2:

File1 occurency 1 <-- File2 row 1
File1 occurency 2 <-- File2 row 2
File1 occurency 3 <-- File2 row 3
...

The number of rows in File 2 is equal to occurencies in File 1 because initialy they were taken from File 1

File1 - is a Json file

...
"@type" : "Review",
"@id":"https://google.com/social/profile/xxxxxxx.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",

"@type" : "Review",
"@id":"https://google.com/social/profile/xxxxxxx.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",
 ...

File2 - is a formated "json like" file

"profilePhoto":"https://someurl.ltd/aaaa_90.jpg"
"profilePhoto":"https://someurl.ltd/bbbb_90.jpg"
"profilePhoto":"https://someurl.ltd/cccc_90.jpg"
 ....

Actually the part of script that have to make this job looks like

IFS=$'\n'
set -f
for i in $(cat < File2.txt); do

sed -i "s|.*social.*|$i|g" File1.json

done

This script replace all occurencies in File1 with the first line of File2, so on second loop there is no more matching to find.
output example

...
"@type" : "Review",
"profilePhoto":"https://someurl.ltd/cccc_90.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",

"@type" : "Review",
"profilePhoto":"https://someurl.ltd/cccc_90.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",
 ...

I need instead the output like this

...
"@type" : "Review",
*"profilePhoto":"https://someurl.ltd/**aaaa**_90.jpg"*
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",

"@type" : "Review",
*"profilePhoto":"https://someurl.ltd/**bbbb**_90.jpg"*
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",
 ...

Thank you in advance for any help.

Body:
Edit:

After reviewing what your desired output a lot closer i came up with this

for i in $(sed 's/^/*/;s|ltd/|&**|;s|_|**&|;s/$/*/' File2.txt); do awk -i inplace -v i="$i" 'NR==1,/.*social.*/{sub(/.*social.*/, i)} 1' File1.json; done

Once you limit the substitution in File1.json to only the first occurrence you can let the loop work for you.

To break it down

# Instead of cat file I tackled substitution for each line in File2.txt as $i
for i in $(sed 's/^/*/;s|ltd/|&**|;s|_|**&|;s/$/*/' File2.txt); do

    # Here awk sub only first occurrence to not overwrite whole file
    # Second loop will handle the next occurrence with second line from File2.txt
    # And third ect.. ect..
    awk -i inplace -v i="$i" 'NR==1,/.*social.*/{sub(/.*social.*/, i)} 1' File1.json
done

Everything below is if your version of awk does not support -i inplace then you will have to do this

awk -v i="$i" 'NR==1,/.*social.*/{sub(/.*social.*/, i)} 1 { rec = rec $0 RS } END { close(FILENAME); printf "%s", rec > FILENAME }' File1.json

So the whole thing will look like

 # Instead of cat file I tackled substitution for each line in File2.txt as $i
for i in $(sed 's/^/*/;s|ltd/|&**|;s|_|**&|;s/$/*/' File2.txt); do

    # Here awk sub only first occurrence to not overwrite whole file
    # Second loop will handle the next occurrence with second line from File2.txt
    # And third ect.. ect..
    awk -v i="$i" 'NR==1,/.*social.*/{sub(/.*social.*/, i)} 1 { rec = rec $0 RS } END { close(FILENAME); printf "%s", rec > FILENAME }' File1.json
done

Finally if you neither of the above awk commands work you can result to temp files.

awk -v i="$i" 'NR==1,/.*social.*/{sub(/.*social.*/, i)} 1' File1.json > tmpfile && mv tmpfile File1.json

so the whole thing will look like this

for i in `cat File2.txt`; do

 awk -v i="$i" 'NR==1,/.*social.*/{sub(/.*social.*/, i)} 1' File1.json > tmpfile && mv tmpfile File1.json

done