问:
Create user in Kubernetes for kubectl
I need to create users to assign them permissions with RBAC, I create them as follows:

```<code>echo -n "lucia" | base64
bHVjaWE=
echo -n "pass" | base64
cGFzcw==

apiVersion: v1
kind: Secret
metadata:
  name: lucia-secret
type: Opaque
data:
  username: bHVjaWE=
  password: cGFzcw==
</code>```

Or create with:

```<code>kubectl create secret generic lucia-secret --from-literal=username='lucia',password='pass'
</code>```

I don't know how to continue

```<code>USER_NICK=lucia

kubectl config set-credentials $USER_NICK \
    --username=lucia \
    --password=pass

kubectl get secret lucia-secret -o json | jq -r '.data["ca.crt"]' | base64 -d > ca.crt

endpoint=`kubectl config view -o jsonpath="{.clusters[?(@.name == \"$name\")].cluster.server}"`

kubectl config set-cluster cluster-for-lucia \
  --embed-certs=true \
  --server=$endpoint \
  --certificate-authority=./ca.crt

kubectl config set-context context-lucia \
  --cluster=cluster-for-lucia \
  --user=$USER_NICK \
  --namespace=default
</code>```

ca.crt is null

Thank you for your help!

答:
In this guide you can find how to configure a user for your cluster: https://docs.bitnami.com/kubernetes/how-to/configure-rbac-in-your-kubernetes-cluster/#use-case-1-create-user-with-limited-namespace-access

Long story short:

Create certificates for the user

Create a certificate sign request

Sign the certificate with the cluster certificate authority

Create a configuration for your user

Add RBAC rules for this user or its group

Regarding the ca.crt, you need to find it in your master host.

Edited: In the case of GKE, check here https://cloud.google.com/container-engine/docs/iam-integration

Title: Create user in Kubernetes for kubectl

Body:
I need to create users to assign them permissions with RBAC, I create them as follows:

echo -n "lucia" | base64
bHVjaWE=
echo -n "pass" | base64
cGFzcw==

apiVersion: v1
kind: Secret
metadata:
  name: lucia-secret
type: Opaque
data:
  username: bHVjaWE=
  password: cGFzcw==

Or create with:

kubectl create secret generic lucia-secret --from-literal=username='lucia',password='pass'

I don't know how to continue

USER_NICK=lucia

kubectl config set-credentials $USER_NICK \
    --username=lucia \
    --password=pass

kubectl get secret lucia-secret -o json | jq -r '.data["ca.crt"]' | base64 -d > ca.crt

endpoint=`kubectl config view -o jsonpath="{.clusters[?(@.name == \"$name\")].cluster.server}"`

kubectl config set-cluster cluster-for-lucia \
  --embed-certs=true \
  --server=$endpoint \
  --certificate-authority=./ca.crt

kubectl config set-context context-lucia \
  --cluster=cluster-for-lucia \
  --user=$USER_NICK \
  --namespace=default

ca.crt is null

Thank you for your help!


来源: stackexchange

问:
python command line programming examples, recipes
There has been a need for python command line utilities at work lately and I have no experience in writing cli's. Regardless, I must still pop them out.

My biggest hurdle is the structure of these programs. Also, the method in getting and verifying input from the user. I have been ending up with very looong while loops and I just dont think that is the most efficient approach.

Could someone provide links to open source cli programs that I may pick to gain a bit of an understanding? Or, books, tutorials, etc that I could get my hands on. I have dug around but have had little success (my google skills must be lacking).

答:
Random hints:

the optionparser module is good for parsing complex options

many python modules indeed are cli programs. See there (for example, see python2.6/json/tool.py which you can run with python -m json.tool)

It is a good idea to use

```<code> def main(arguments):
     etc.

 if __name__ == '__main__':
     # only if we are executed rather than imported as a module:
     import sys
     main(sys.argv)
</code>```

Such that the parts of yor app can be reused by simply importing them

ContentLicense: CC BY-SA 2.5

Body:
Random hints:

the optionparser module is good for parsing complex options

many python modules indeed are cli programs. See there (for example, see python2.6/json/tool.py which you can run with python -m json.tool)

It is a good idea to use

 def main(arguments):
     etc.

 if __name__ == '__main__':
     # only if we are executed rather than imported as a module:
     import sys
     main(sys.argv)

Such that the parts of yor app can be reused by simply importing them


问:
How can I close a buffer without closing the window?
Vim's multilayered views (Windows, Buffers and Tabs) left me a little confused. Let's say I split the display (:sp) and then select a different buffer to display in each window. Now I want to close one of the buffers, yet I don't want the window to close (After the closing it can display the next buffer on the list or an empty buffer, it doesn't matter). How can I do this?</p>

答:
Here is a very readable vimscript function, which handles all cases well,

behave similar to built-in:bd (if only one window, just invoke it!),

issue a warning and do nothing if buffer modifed.

if no other buffer, create one, via :enew.

if alternate buffer exist and in buffer-list, switch to it, else go next, via:bn.

more reasonable behavior for multiple-window layout

not closing any window,

always stay on the original window.

for each window that displays current buffer, do as listed above, then delete old current buffer.

```
nnoremap <Leader>b :call DeleteCurBufferNotCloseWindow()<CR>

func! DeleteCurBufferNotCloseWindow() abort
    if &modified
        echohl ErrorMsg
        echom "E89: no write since last change"
        echohl None
    elseif winnr('$') == 1
        bd
    else  " multiple window
        let oldbuf = bufnr('%')
        let oldwin = winnr()
        while 1   " all windows that display oldbuf will remain open
            if buflisted(bufnr('#'))
                b#
            else
                bn
                let curbuf = bufnr('%')
                if curbuf == oldbuf
                    enew    " oldbuf is the only buffer, create one
                endif
            endif
            let win = bufwinnr(oldbuf)
            if win == -1
                break
            else        " there are other window that display oldbuf
                exec win 'wincmd w'
            endif
        endwhile
        " delete oldbuf and restore window to oldwin
        exec oldbuf 'bd'
        exec oldwin 'wincmd w'
    endif
endfunc
```

ContentLicense: CC BY-SA 4.0

Body:
Here is a very readable vimscript function, which handles all cases well,

behave similar to built-in:bd (if only one window, just invoke it!),

issue a warning and do nothing if buffer modifed.

if no other buffer, create one, via :enew.

if alternate buffer exist and in buffer-list, switch to it, else go next, via:bn.

more reasonable behavior for multiple-window layout

not closing any window,

always stay on the original window.

for each window that displays current buffer, do as listed above, then delete old current buffer.

nnoremap <Leader>b :call DeleteCurBufferNotCloseWindow()<CR>

func! DeleteCurBufferNotCloseWindow() abort
    if &modified
        echohl ErrorMsg
        echom "E89: no write since last change"
        echohl None
    elseif winnr('$') == 1
        bd
    else  " multiple window
        let oldbuf = bufnr('%')
        let oldwin = winnr()
        while 1   " all windows that display oldbuf will remain open
            if buflisted(bufnr('#'))
                b#
            else
                bn
                let curbuf = bufnr('%')
                if curbuf == oldbuf
                    enew    " oldbuf is the only buffer, create one
                endif
            endif
            let win = bufwinnr(oldbuf)
            if win == -1
                break
            else        " there are other window that display oldbuf
                exec win 'wincmd w'
            endif
        endwhile
        " delete oldbuf and restore window to oldwin
        exec oldbuf 'bd'
        exec oldwin 'wincmd w'
    endif
endfunc

ContentLicense: CC BY-SA 3.0


问:
PHP Laravel Variable Scope in functions
I have the following code in a Laravel controller, but the given parameter variable $idea is undefined in the 'whereIn' function. How can I access $idea there? Thank you!</p>

```<code>public static function getIdea($idea = null) {
    if ($idea != "") {
        return DB::table('test')->select('foo')
            ->whereIn('bar', function($query)
              {
                  $query->select('foobar')
                        ->from('bar2')
                        ->where('foo2', '=', $idea)
                        ->get();
              })
            ->get();
    }
}
</code>```

答:
Use the use keyword! See Example #3 Inheriting variables from the parent scope on anonymous functions

```<code>public static function getIdea($idea = null) {
    if ($idea != "") {
        return DB::table('test')->select('foo')
            ->whereIn('bar', function($query) use ($idea)
              {
                  $query->select('foobar')
                        ->from('bar2')
                        ->where('foo2', '=', $idea)
                        ->get();
              })
            ->get();
    }
}
</code>```

Title: PHP Laravel Variable Scope in functions

Body:
I have the following code in a Laravel controller, but the given parameter variable $idea is undefined in the 'whereIn' function. How can I access $idea there? Thank you!

public static function getIdea($idea = null) {
    if ($idea != "") {
        return DB::table('test')->select('foo')
            ->whereIn('bar', function($query)
              {
                  $query->select('foobar')
                        ->from('bar2')
                        ->where('foo2', '=', $idea)
                        ->get();
              })
            ->get();
    }
}

Body:
Use the use keyword! See Example #3 Inheriting variables from the parent scope on anonymous functions

public static function getIdea($idea = null) {
    if ($idea != "") {
        return DB::table('test')->select('foo')
            ->whereIn('bar', function($query) use ($idea)
              {
                  $query->select('foobar')
                        ->from('bar2')
                        ->where('foo2', '=', $idea)
                        ->get();
              })
            ->get();
    }
}


问:
JavaFX How to add elements eg. Buttons dynamically created from items stored in the database Mysql?
There is this video in youtube https://www.youtube.com/watch?v=Idtm2Y6I23w
Whereby the person has dynamically populated buttons created from the items that are stored in the database.For instance in this picture

It has some categories that includes Tables,Stock,Reports and Users
When a user clicks on the Table category it displays Buttons dynamically created from items stored in the database mysql. For instance this is the result image:

How does one get to develop like that?
Is there a for loop statements that is going to be used?

EDIT

This is how i did it.This is the source code.

```<code>public class OrderController implements Initializable {

    @FXML
    private ListView<Button> listvieww;

    @FXML
    private HBox hboxx;

    List<String> listOfSomething = null;
//@FXML
//    private Pane panedynamic;
    private DBConnection database = new DBConnection();
    private Connection connection;
    private Statement statement;
    private ResultSet resultSet;

    private ObservableList<Button> buttons = FXCollections.observableArrayList();

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
    hboxx.getChildren().add(buttons)
    }

    @FXML
    void acttable(ActionEvent event) {

        // TODO
        String sqlQuery = "SELECT * FROM restauranttables;";
        try {
            connection = database.getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sqlQuery);
            while (resultSet.next()) {
                String current = resultSet.getString("tablename");
                ObservableList<String> list = FXCollections.observableArrayList(current);
                Button b = new Button(list.toString());
                buttons.add(b);

            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    @FXML
    void actlogout(ActionEvent event) {

    }

    @FXML
    void actnew(ActionEvent event) {

    }

    @FXML
    void actorder(ActionEvent event) {

    }

    @FXML
    void actreports(ActionEvent event) {

    }

    @FXML
    void actstock(ActionEvent event) {

    }

    @FXML
    void actusers(ActionEvent event) {

    }

}
</code>```

this is how my scene builder looks like

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import com.jfoenix.controls.JFXButton?>
<?import com.jfoenix.controls.JFXTextField?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.layout.StackPane?>

<AnchorPane id="AnchorPane" prefHeight="600.0" prefWidth="1080.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controllers.OrderController">
    <children>
        <AnchorPane layoutX="55.0" layoutY="29.0" prefHeight="600.0" prefWidth="1080.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
            <children>
                <TableView layoutX="21.0" layoutY="49.0" prefHeight="386.0" prefWidth="413.0">
                    <columns>
                        <TableColumn prefWidth="122.0" text="Description" />
                        <TableColumn prefWidth="57.0" text="Price" />
                        <TableColumn prefWidth="81.0" text="Sub Total" />
                        <TableColumn prefWidth="96.0" text="Table Id" />
                        <TableColumn prefWidth="57.0" text="Price" />
                    </columns>
                </TableView>
                <JFXTextField layoutX="53.0" layoutY="439.0" prefHeight="37.0" prefWidth="155.0" />
                <JFXTextField layoutX="253.0" layoutY="439.0" prefHeight="37.0" prefWidth="155.0" />
                <GridPane layoutX="63.0" layoutY="503.0" prefHeight="75.0" prefWidth="345.0">
                    <columnConstraints>
                        <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                        <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                    </columnConstraints>
                    <rowConstraints>
                        <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                    </rowConstraints>
                    <children>
                        <AnchorPane prefHeight="200.0" prefWidth="200.0">
                            <children>
                                <JFXButton layoutX="25.0" layoutY="25.0" onAction="#actorder" prefHeight="75.0" prefWidth="173.0" text="Order" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                            </children>
                        </AnchorPane>
                        <AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1">
                            <children>
                                <JFXButton layoutX="39.0" layoutY="14.0" onAction="#actnew" prefHeight="75.0" prefWidth="172.0" text="New" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                            </children>
                        </AnchorPane>
                    </children>
                </GridPane>
                <MenuBar layoutX="21.0" layoutY="14.0" prefHeight="29.0" prefWidth="413.0">
                    <menus>
                        <Menu mnemonicParsing="false" text="File">
                            <items>
                                <MenuItem mnemonicParsing="false" text="Close" />
                            </items>
                        </Menu>
                        <Menu mnemonicParsing="false" text="Edit">
                            <items>
                                <MenuItem mnemonicParsing="false" text="Delete" />
                            </items>
                        </Menu>
                        <Menu mnemonicParsing="false" text="Help">
                            <items>
                                <MenuItem mnemonicParsing="false" text="About" />
                            </items>
                        </Menu>
                    </menus>
                </MenuBar>
                <StackPane fx:id="acContent" layoutX="454.0" layoutY="49.0" prefHeight="525.0" prefWidth="605.0">
                    <children>
                        <AnchorPane fx:id="anchora" prefHeight="200.0" prefWidth="200.0">
                           <children>

                               <GridPane fx:id="sasa" layoutX="17.0" layoutY="7.0" prefHeight="90.0" prefWidth="571.0">
                                   <columnConstraints>
                                       <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                       <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                       <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                       <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                       <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                   </columnConstraints>
                                   <rowConstraints>
                                       <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                                   </rowConstraints>
                                   <children>
                                       <AnchorPane prefHeight="200.0" prefWidth="200.0">
                                           <children>
                                               <JFXButton fx:id="table" layoutX="37.0" layoutY="19.0" onAction="#acttable" prefHeight="90.0" prefWidth="135.0" text="TABLE" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                                           </children>
                                       </AnchorPane>
                                       <AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1">
                                           <children>
                                               <JFXButton fx:id="stock" layoutX="43.0" layoutY="32.0" onAction="#actstock" prefHeight="90.0" prefWidth="134.0" text="STOCK" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                                           </children>
                                       </AnchorPane>
                                       <AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="2">
                                           <children>
                                               <JFXButton fx:id="reports" layoutX="26.0" layoutY="32.0" onAction="#actreports" prefHeight="90.0" prefWidth="134.0" text="REPORTS" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                                           </children>
                                       </AnchorPane>
                                       <AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="3">
                                           <children>
                                               <JFXButton fx:id="users" layoutX="26.0" layoutY="32.0" onAction="#actusers" prefHeight="90.0" prefWidth="134.0" text="USERS" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                                           </children>
                                       </AnchorPane>
                                       <AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="4">
                                           <children>
                                               <JFXButton fx:id="logout" layoutX="28.0" layoutY="32.0" onAction="#actlogout" prefHeight="90.0" prefWidth="134.0" text="LOGOUT" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                                           </children>
                                       </AnchorPane>
                                   </children>
                               </GridPane>
                        <HBox fx:id="hboxx" layoutX="17.0" layoutY="110.0" prefHeight="398.0" prefWidth="571.0" />
                           </children>
                        </AnchorPane>
                    </children>
                </StackPane>
            </children>
        </AnchorPane>
    </children>
</AnchorPane>
</code>```

i would want to align the buttons in a hbox but am getting an error here

```<code>@Override
    public void initialize(URL url, ResourceBundle rb) {
    hboxx.getChildren().add(buttons)
    }
</code>```

Any Help Thank you.

答:
// connectivity for mysql database coding
String category_name= "Stock";

Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sonoo","root","root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from category where category_name=" + "'" + category_name + "'");
rs.next();

int num_of_rows = rs.getInt(3); (Fetched from database according to category)

Panel p1=new Panel();
p1.setLayout(new GridLayout(Math.Ceil(num_of_rows/6),6,10,10));

Button b[];

b=new Button[num_of_rows];

for(int i=0;i<num_of_rows;i++)
{
 b[i]=new Button(category_name + "" + (i+1));
 p1.add(b[i]);
 b[i].addActionListener(this); // needed if to perform button click
}

//adding the panel to the container
add(p1);

public void actionPerformed(ActionEvent ae)
{
 // The event click code goes here
}```

Body:
There is this video in youtube https://www.youtube.com/watch?v=Idtm2Y6I23w
Whereby the person has dynamically populated buttons created from the items that are stored in the database.For instance in this picture

It has some categories that includes Tables,Stock,Reports and Users
When a user clicks on the Table category it displays Buttons dynamically created from items stored in the database mysql. For instance this is the result image:

How does one get to develop like that?
Is there a for loop statements that is going to be used?

EDIT

This is how i did it.This is the source code.

public class OrderController implements Initializable {

    @FXML
    private ListView<Button> listvieww;

    @FXML
    private HBox hboxx;

    List<String> listOfSomething = null;
//@FXML
//    private Pane panedynamic;
    private DBConnection database = new DBConnection();
    private Connection connection;
    private Statement statement;
    private ResultSet resultSet;

    private ObservableList<Button> buttons = FXCollections.observableArrayList();

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
    hboxx.getChildren().add(buttons)
    }

    @FXML
    void acttable(ActionEvent event) {

        // TODO
        String sqlQuery = "SELECT * FROM restauranttables;";
        try {
            connection = database.getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sqlQuery);
            while (resultSet.next()) {
                String current = resultSet.getString("tablename");
                ObservableList<String> list = FXCollections.observableArrayList(current);
                Button b = new Button(list.toString());
                buttons.add(b);

            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    @FXML
    void actlogout(ActionEvent event) {

    }

    @FXML
    void actnew(ActionEvent event) {

    }

    @FXML
    void actorder(ActionEvent event) {

    }

    @FXML
    void actreports(ActionEvent event) {

    }

    @FXML
    void actstock(ActionEvent event) {

    }

    @FXML
    void actusers(ActionEvent event) {

    }

}

this is how my scene builder looks like

<?xml version="1.0" encoding="UTF-8"?>

<?import com.jfoenix.controls.JFXButton?>
<?import com.jfoenix.controls.JFXTextField?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.layout.StackPane?>

<AnchorPane id="AnchorPane" prefHeight="600.0" prefWidth="1080.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controllers.OrderController">
    <children>
        <AnchorPane layoutX="55.0" layoutY="29.0" prefHeight="600.0" prefWidth="1080.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
            <children>
                <TableView layoutX="21.0" layoutY="49.0" prefHeight="386.0" prefWidth="413.0">
                    <columns>
                        <TableColumn prefWidth="122.0" text="Description" />
                        <TableColumn prefWidth="57.0" text="Price" />
                        <TableColumn prefWidth="81.0" text="Sub Total" />
                        <TableColumn prefWidth="96.0" text="Table Id" />
                        <TableColumn prefWidth="57.0" text="Price" />
                    </columns>
                </TableView>
                <JFXTextField layoutX="53.0" layoutY="439.0" prefHeight="37.0" prefWidth="155.0" />
                <JFXTextField layoutX="253.0" layoutY="439.0" prefHeight="37.0" prefWidth="155.0" />
                <GridPane layoutX="63.0" layoutY="503.0" prefHeight="75.0" prefWidth="345.0">
                    <columnConstraints>
                        <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                        <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                    </columnConstraints>
                    <rowConstraints>
                        <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                    </rowConstraints>
                    <children>
                        <AnchorPane prefHeight="200.0" prefWidth="200.0">
                            <children>
                                <JFXButton layoutX="25.0" layoutY="25.0" onAction="#actorder" prefHeight="75.0" prefWidth="173.0" text="Order" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                            </children>
                        </AnchorPane>
                        <AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1">
                            <children>
                                <JFXButton layoutX="39.0" layoutY="14.0" onAction="#actnew" prefHeight="75.0" prefWidth="172.0" text="New" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                            </children>
                        </AnchorPane>
                    </children>
                </GridPane>
                <MenuBar layoutX="21.0" layoutY="14.0" prefHeight="29.0" prefWidth="413.0">
                    <menus>
                        <Menu mnemonicParsing="false" text="File">
                            <items>
                                <MenuItem mnemonicParsing="false" text="Close" />
                            </items>
                        </Menu>
                        <Menu mnemonicParsing="false" text="Edit">
                            <items>
                                <MenuItem mnemonicParsing="false" text="Delete" />
                            </items>
                        </Menu>
                        <Menu mnemonicParsing="false" text="Help">
                            <items>
                                <MenuItem mnemonicParsing="false" text="About" />
                            </items>
                        </Menu>
                    </menus>
                </MenuBar>
                <StackPane fx:id="acContent" layoutX="454.0" layoutY="49.0" prefHeight="525.0" prefWidth="605.0">
                    <children>
                        <AnchorPane fx:id="anchora" prefHeight="200.0" prefWidth="200.0">
                           <children>

                               <GridPane fx:id="sasa" layoutX="17.0" layoutY="7.0" prefHeight="90.0" prefWidth="571.0">
                                   <columnConstraints>
                                       <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                       <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                       <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                       <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                       <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                   </columnConstraints>
                                   <rowConstraints>
                                       <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                                   </rowConstraints>
                                   <children>
                                       <AnchorPane prefHeight="200.0" prefWidth="200.0">
                                           <children>
                                               <JFXButton fx:id="table" layoutX="37.0" layoutY="19.0" onAction="#acttable" prefHeight="90.0" prefWidth="135.0" text="TABLE" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                                           </children>
                                       </AnchorPane>
                                       <AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1">
                                           <children>
                                               <JFXButton fx:id="stock" layoutX="43.0" layoutY="32.0" onAction="#actstock" prefHeight="90.0" prefWidth="134.0" text="STOCK" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                                           </children>
                                       </AnchorPane>
                                       <AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="2">
                                           <children>
                                               <JFXButton fx:id="reports" layoutX="26.0" layoutY="32.0" onAction="#actreports" prefHeight="90.0" prefWidth="134.0" text="REPORTS" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                                           </children>
                                       </AnchorPane>
                                       <AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="3">
                                           <children>
                                               <JFXButton fx:id="users" layoutX="26.0" layoutY="32.0" onAction="#actusers" prefHeight="90.0" prefWidth="134.0" text="USERS" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                                           </children>
                                       </AnchorPane>
                                       <AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="4">
                                           <children>
                                               <JFXButton fx:id="logout" layoutX="28.0" layoutY="32.0" onAction="#actlogout" prefHeight="90.0" prefWidth="134.0" text="LOGOUT" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                                           </children>
                                       </AnchorPane>
                                   </children>
                               </GridPane>
                        <HBox fx:id="hboxx" layoutX="17.0" layoutY="110.0" prefHeight="398.0" prefWidth="571.0" />
                           </children>
                        </AnchorPane>
                    </children>
                </StackPane>
            </children>
        </AnchorPane>
    </children>
</AnchorPane>

i would want to align the buttons in a hbox but am getting an error here

@Override
    public void initialize(URL url, ResourceBundle rb) {
    hboxx.getChildren().add(buttons)
    }

Any Help Thank you.


问:
Web scraping by Beautifulsoup
In my previous post, I wanna scrape some horse racing data on HKJC. Thanks to the help of Dmitriy Fialkovskiy, I've made it happen by slightly modifying the given code. However, when I was trying to understand the logic behind, there was a line couldn't be explained:

```<code>from bs4 import BeautifulSoup as BS
import requests
import pandas as pd

url_list = ['http://www.hkjc.com/english/racing/horse.asp?HorseNo=S217','http://www.hkjc.com/english/racing/horse.asp?HorseNo=A093','http://www.hkjc.com/english/racing/horse.asp?HorseNo=V344','http://www.hkjc.com/english/racing/horse.asp?HorseNo=V077', 'http://www.hkjc.com/english/racing/horse.asp?HorseNo=P361', 'http://www.hkjc.com/english/racing/horse.asp?HorseNo=T103']

res=[] #placing res outside of loop
for link in url_list:
    r = requests.get(link)
    r.encoding = 'utf-8'

    html_content = r.text
    soup = BS(html_content, 'lxml')

    table = soup.find('table', class_='bigborder')
    if not table:
        continue

    trs = table.find_all('tr')

    if not trs:
        continue #if trs are not found, then starting next iteration with other link

    headers = trs[0]
    headers_list=[]
    for td in headers.find_all('td'):
        headers_list.append(td.text)
    headers_list+=['Season']
    headers_list.insert(19,'pseudocol1')
    headers_list.insert(20,'pseudocol2')
    headers_list.insert(21,'pseudocol3')

    row = []
    season = ''
    for tr in trs[1:]:
        if 'Season' in tr.text:
            season = tr.text

        else:
            tds = tr.find_all('td')
            for td in tds:
                row.append(td.text.strip('\n').strip('\r').strip('\t').strip('"').strip())
            row.append(season.strip())
            res.append(row)
            row=[]

res = [i for i in res if i[0]!=''] #outside of loop

df=pd.DataFrame(res, columns=headers_list) #outside of loop
del df['pseudocol1'],df['pseudocol2'],df['pseudocol3']
del df['VideoReplay']
</code>```

I'm wondering what's the purpose of adding a repeated row =[] in the else condition and why would that works. Thank you.

答: The row=[] inside the loop clears the list, making it empty again. Since the list is declared once before the for loop, it would otherwise carry on elements that were appended in one for iteration to the other. Doing row=[] clears it to an empty list again.

Title: Web scraping by Beautifulsoup

Body:
In my previous post, I wanna scrape some horse racing data on HKJC. Thanks to the help of Dmitriy Fialkovskiy, I've made it happen by slightly modifying the given code. However, when I was trying to understand the logic behind, there was a line couldn't be explained:

from bs4 import BeautifulSoup as BS
import requests
import pandas as pd

url_list = ['http://www.hkjc.com/english/racing/horse.asp?HorseNo=S217','http://www.hkjc.com/english/racing/horse.asp?HorseNo=A093','http://www.hkjc.com/english/racing/horse.asp?HorseNo=V344','http://www.hkjc.com/english/racing/horse.asp?HorseNo=V077', 'http://www.hkjc.com/english/racing/horse.asp?HorseNo=P361', 'http://www.hkjc.com/english/racing/horse.asp?HorseNo=T103']

res=[] #placing res outside of loop
for link in url_list:
    r = requests.get(link)
    r.encoding = 'utf-8'

    html_content = r.text
    soup = BS(html_content, 'lxml')

    table = soup.find('table', class_='bigborder')
    if not table:
        continue

    trs = table.find_all('tr')

    if not trs:
        continue #if trs are not found, then starting next iteration with other link

    headers = trs[0]
    headers_list=[]
    for td in headers.find_all('td'):
        headers_list.append(td.text)
    headers_list+=['Season']
    headers_list.insert(19,'pseudocol1')
    headers_list.insert(20,'pseudocol2')
    headers_list.insert(21,'pseudocol3')

    row = []
    season = ''
    for tr in trs[1:]:
        if 'Season' in tr.text:
            season = tr.text

        else:
            tds = tr.find_all('td')
            for td in tds:
                row.append(td.text.strip('\n').strip('\r').strip('\t').strip('"').strip())
            row.append(season.strip())
            res.append(row)
            row=[]

res = [i for i in res if i[0]!=''] #outside of loop

df=pd.DataFrame(res, columns=headers_list) #outside of loop
del df['pseudocol1'],df['pseudocol2'],df['pseudocol3']
del df['VideoReplay']

I'm wondering what's the purpose of adding a repeated row =[] in the else condition and why would that works. Thank you.


问:
Need to include a variable in a function of a query in Laravel
I have something like this:

```<code>$configurations = Configs:all();

foreach($configs as $config){

$documents = document::whereHas('user', function ($q) {
$q->where("portal_id", $config->id),})->get()

...
}
</code>```

This does not work because $config is not defined in the query function.

How do I put the $config->id object there?

答:
also you can write like this, no need to write foreach loop:</p>

```<code>$configurations = Configs:all();
$documents = Document::whereHas('user', function($q) use($configurations) {
    $q->whereIn('portal_id', $configurations->pluck('id'));
});
</code>```

Body:
I have something like this:

$configurations = Configs:all();

foreach($configs as $config){

$documents = document::whereHas('user', function ($q) {
$q->where("portal_id", $config->id),})->get()

...
}

This does not work because $config is not defined in the query function.

How do I put the $config->id object there?

Body:
also you can write like this, no need to write foreach loop:

$configurations = Configs:all();
$documents = Document::whereHas('user', function($q) use($configurations) {
    $q->whereIn('portal_id', $configurations->pluck('id'));
});


问:
Scaling Bokeh according to screen
As you can see here, I have two plots in same row. I need to scale whole row according to screen size but maintain plot length ratio.

I tried with argument: sizing_mode = 'scale width', but it doesn't work because it changes heights of plots.

```<code>p1 = figure(plot_width=NewRanges_Row1[0], plot_height=height, tools=[hover1, TOOLS], title="CHROMOSOME_1",
            toolbar_location="above", responsive = True)
p1.circle('x1', 'y1', fill_color=chromosome1_colors, line_color=chromosome1_colors,
          fill_alpha=chromosome1_transparency, size=7, source=source1)
p2 = figure(plot_width=NewRanges_Row1[1], plot_height=height, tools=[hover22, TOOLS], title="CHROMOSOME_22")
p2.circle('x22', 'y22', fill_color=chromosome22_colors, line_color=chromosome22_colors,
          fill_alpha=chromosome22_transparency, size=7, source=source22)
</code>```

Where p1 is first plot in row, and p2 is second plot in row.

Is there a way to scale Bokeh figures automatically according to size of screen, while maintaining the ratio of widths in same row?

答:
Bokeh's responsive plotting functionality is still quite poor when it comes to complex layouts. The solution that I've found is to use Python's built in library to determine the screen resolution and then set the height and width values for each object.

```<code>import ctypes
screen_width = ctypes.windll.user32.GetSystemMetrics(0)
max_width = floor(96 * screen_width / 100)  # buffer to adjust
p1_width = 0.8*max_width
p2_width = 0.2*max_width
</code>```

However, this means that the web application is not truly responsive since it will not resize with the user's browser page as the screen resolution is determined only once when the application starts. If you need a more responsive app, you will need to look into doing that by tweaking the app's css and js.

Title: Scaling Bokeh according to screen

Body:
As you can see here, I have two plots in same row. I need to scale whole row according to screen size but maintain plot length ratio.

I tried with argument: sizing_mode = 'scale width', but it doesn't work because it changes heights of plots.

p1 = figure(plot_width=NewRanges_Row1[0], plot_height=height, tools=[hover1, TOOLS], title="CHROMOSOME_1",
            toolbar_location="above", responsive = True)
p1.circle('x1', 'y1', fill_color=chromosome1_colors, line_color=chromosome1_colors,
          fill_alpha=chromosome1_transparency, size=7, source=source1)
p2 = figure(plot_width=NewRanges_Row1[1], plot_height=height, tools=[hover22, TOOLS], title="CHROMOSOME_22")
p2.circle('x22', 'y22', fill_color=chromosome22_colors, line_color=chromosome22_colors,
          fill_alpha=chromosome22_transparency, size=7, source=source22)

Where p1 is first plot in row, and p2 is second plot in row.

Is there a way to scale Bokeh figures automatically according to size of screen, while maintaining the ratio of widths in same row?

Body:
Bokeh's responsive plotting functionality is still quite poor when it comes to complex layouts. The solution that I've found is to use Python's built in library to determine the screen resolution and then set the height and width values for each object.

import ctypes
screen_width = ctypes.windll.user32.GetSystemMetrics(0)
max_width = floor(96 * screen_width / 100)  # buffer to adjust
p1_width = 0.8*max_width
p2_width = 0.2*max_width

However, this means that the web application is not truly responsive since it will not resize with the user's browser page as the screen resolution is determined only once when the application starts. If you need a more responsive app, you will need to look into doing that by tweaking the app's css and js.


问:
PHP / MySQL build tree menu
I am trying to build an un-oredered list menu tree from my database in PHP and MySQL.

I have an array of page objects I am returning from the db.  Each page object has parent_id attribute, which is set to null if it doesn't have a parent.  Here's what the page objects look like:

```<code>page object
  id
  title
  parent_id
</code>```

If possible I would like to not do it recursively and only hit the database once, since I am going to be building the menu on almost every request.  I want to create a function that I can just pass my array of objects to and it will return the html list.

答:
I ended up going with this solution (pastebin reference):

```<code><?php

/**
 * Generate HTML for multi-dimensional menu from MySQL database
 * with ONE QUERY and WITHOUT RECURSION
 * @author J. Bruni
 */
class MenuBuilder
{
    /**
     * MySQL connection
     */
    var $conn;

    /**
     * Menu items
     */
    var $items = array();

    /**
     * HTML contents
     */
    var $html  = array();

    /**
     * Create MySQL connection
     */
    function MenuBuilder()
    {
        $this->conn = mysql_connect( 'localhost', 'user', 'pass' );
        mysql_select_db( 'example', $this->conn );
    }

    /**
     * Perform MySQL query and return all results
     */
    function fetch_assoc_all( $sql )
    {
        $result = mysql_query( $sql, $this->conn );

        if ( !$result )
            return false;

        $assoc_all = array();

        while( $fetch = mysql_fetch_assoc( $result ) )
            $assoc_all[] = $fetch;

        mysql_free_result( $result );

        return $assoc_all;
    }

    /**
     * Get all menu items from database
     */
    function get_menu_items()
    {
        // Change the field names and the table name in the query below to match tour needs
        $sql = 'SELECT id, parent_id, title, link, position FROM menu_item ORDER BY parent_id, position;';
        return $this->fetch_assoc_all( $sql );
    }

    /**
     * Build the HTML for the menu
     */
    function get_menu_html( $root_id = 0 )
    {
        $this->html  = array();
        $this->items = $this->get_menu_items();

        foreach ( $this->items as $item )
            $children[$item['parent_id']][] = $item;

        // loop will be false if the root has no children (i.e., an empty menu!)
        $loop = !empty( $children[$root_id] );

        // initializing $parent as the root
        $parent = $root_id;
        $parent_stack = array();

        // HTML wrapper for the menu (open)
        $this->html[] = '<ul>';

        while ( $loop && ( ( $option = each( $children[$parent] ) ) || ( $parent > $root_id ) ) )
        {
            if ( $option === false )
            {
                $parent = array_pop( $parent_stack );

                // HTML for menu item containing childrens (close)
                $this->html[] = str_repeat( "\t", ( count( $parent_stack ) + 1 ) * 2 ) . '</ul>';
                $this->html[] = str_repeat( "\t", ( count( $parent_stack ) + 1 ) * 2 - 1 ) . '</li>';
            }
            elseif ( !empty( $children[$option['value']['id']] ) )
            {
                $tab = str_repeat( "\t", ( count( $parent_stack ) + 1 ) * 2 - 1 );

                // HTML for menu item containing childrens (open)
                $this->html[] = sprintf(
                    '%1$s<li><a href="%2$s">%3$s</a>',
                    $tab,   // %1$s = tabulation
                    $option['value']['link'],   // %2$s = link (URL)
                    $option['value']['title']   // %3$s = title
                );
                $this->html[] = $tab . "\t" . '<ul class="submenu">';

                array_push( $parent_stack, $option['value']['parent_id'] );
                $parent = $option['value']['id'];
            }
            else
                // HTML for menu item with no children (aka "leaf")
                $this->html[] = sprintf(
                    '%1$s<li><a href="%2$s">%3$s</a></li>',
                    str_repeat( "\t", ( count( $parent_stack ) + 1 ) * 2 - 1 ),   // %1$s = tabulation
                    $option['value']['link'],   // %2$s = link (URL)
                    $option['value']['title']   // %3$s = title
                );
        }

        // HTML wrapper for the menu (close)
        $this->html[] = '</ul>';

        return implode( "\r\n", $this->html );
    }
}
</code>```

Example Data:

```<code>CREATE TABLE `menu_item` (
  `id` int(11) NOT NULL,
  `title` varchar(75) DEFAULT NULL,
  `link` varchar(100) DEFAULT NULL,
  `parent_id` int(11) DEFAULT NULL,
  `position` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
);

INSERT INTO `menu_item` (`id`, `title`, `link`, `parent_id`, `position`) VALUES (1,'1','1.html',0,1);
INSERT INTO `menu_item` (`id`, `title`, `link`, `parent_id`, `position`) VALUES (2,'2','2.html',0,2);
INSERT INTO `menu_item` (`id`, `title`, `link`, `parent_id`, `position`) VALUES (3,'11','11.html',1,1);
INSERT INTO `menu_item` (`id`, `title`, `link`, `parent_id`, `position`) VALUES (4,'12','12.html',1,2);
INSERT INTO `menu_item` (`id`, `title`, `link`, `parent_id`, `position`) VALUES (5,'21','21.html',2,1);
INSERT INTO `menu_item` (`id`, `title`, `link`, `parent_id`, `position`) VALUES (6,'22','22.html',2,2);
INSERT INTO `menu_item` (`id`, `title`, `link`, `parent_id`, `position`) VALUES (7,'3','3.html',0,3);
</code>```

Usage:

```<code>$menu = new MenuBuilder();
echo '```' . htmlentities( $menu->get_menu_html() ) . '</pŕe>';
```

Title: PHP / MySQL build tree menu

Body:
I am trying to build an un-oredered list menu tree from my database in PHP and MySQL.

I have an array of page objects I am returning from the db.  Each page object has parent_id attribute, which is set to null if it doesn't have a parent.  Here's what the page objects look like:

page object
  id
  title
  parent_id

If possible I would like to not do it recursively and only hit the database once, since I am going to be building the menu on almost every request.  I want to create a function that I can just pass my array of objects to and it will return the html list.

Body:
I ended up going with this solution (pastebin reference):

<?php

/**
 * Generate HTML for multi-dimensional menu from MySQL database
 * with ONE QUERY and WITHOUT RECURSION
 * @author J. Bruni
 */
class MenuBuilder
{
    /**
     * MySQL connection
     */
    var $conn;

    /**
     * Menu items
     */
    var $items = array();

    /**
     * HTML contents
     */
    var $html  = array();

    /**
     * Create MySQL connection
     */
    function MenuBuilder()
    {
        $this->conn = mysql_connect( 'localhost', 'user', 'pass' );
        mysql_select_db( 'example', $this->conn );
    }

    /**
     * Perform MySQL query and return all results
     */
    function fetch_assoc_all( $sql )
    {
        $result = mysql_query( $sql, $this->conn );

        if ( !$result )
            return false;

        $assoc_all = array();

        while( $fetch = mysql_fetch_assoc( $result ) )
            $assoc_all[] = $fetch;

        mysql_free_result( $result );

        return $assoc_all;
    }

    /**
     * Get all menu items from database
     */
    function get_menu_items()
    {
        // Change the field names and the table name in the query below to match tour needs
        $sql = 'SELECT id, parent_id, title, link, position FROM menu_item ORDER BY parent_id, position;';
        return $this->fetch_assoc_all( $sql );
    }

    /**
     * Build the HTML for the menu
     */
    function get_menu_html( $root_id = 0 )
    {
        $this->html  = array();
        $this->items = $this->get_menu_items();

        foreach ( $this->items as $item )
            $children[$item['parent_id']][] = $item;

        // loop will be false if the root has no children (i.e., an empty menu!)
        $loop = !empty( $children[$root_id] );

        // initializing $parent as the root
        $parent = $root_id;
        $parent_stack = array();

        // HTML wrapper for the menu (open)
        $this->html[] = '<ul>';

        while ( $loop && ( ( $option = each( $children[$parent] ) ) || ( $parent > $root_id ) ) )
        {
            if ( $option === false )
            {
                $parent = array_pop( $parent_stack );

                // HTML for menu item containing childrens (close)
                $this->html[] = str_repeat( "\t", ( count( $parent_stack ) + 1 ) * 2 ) . '</ul>';
                $this->html[] = str_repeat( "\t", ( count( $parent_stack ) + 1 ) * 2 - 1 ) . '</li>';
            }
            elseif ( !empty( $children[$option['value']['id']] ) )
            {
                $tab = str_repeat( "\t", ( count( $parent_stack ) + 1 ) * 2 - 1 );

                // HTML for menu item containing childrens (open)
                $this->html[] = sprintf(
                    '%1$s<li><a href="%2$s">%3$s</a>',
                    $tab,   // %1$s = tabulation
                    $option['value']['link'],   // %2$s = link (URL)
                    $option['value']['title']   // %3$s = title
                );
                $this->html[] = $tab . "\t" . '<ul class="submenu">';

                array_push( $parent_stack, $option['value']['parent_id'] );
                $parent = $option['value']['id'];
            }
            else
                // HTML for menu item with no children (aka "leaf")
                $this->html[] = sprintf(
                    '%1$s<li><a href="%2$s">%3$s</a></li>',
                    str_repeat( "\t", ( count( $parent_stack ) + 1 ) * 2 - 1 ),   // %1$s = tabulation
                    $option['value']['link'],   // %2$s = link (URL)
                    $option['value']['title']   // %3$s = title
                );
        }

        // HTML wrapper for the menu (close)
        $this->html[] = '</ul>';

        return implode( "\r\n", $this->html );
    }
}

Example Data:

CREATE TABLE `menu_item` (
  `id` int(11) NOT NULL,
  `title` varchar(75) DEFAULT NULL,
  `link` varchar(100) DEFAULT NULL,
  `parent_id` int(11) DEFAULT NULL,
  `position` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
);

INSERT INTO `menu_item` (`id`, `title`, `link`, `parent_id`, `position`) VALUES (1,'1','1.html',0,1);
INSERT INTO `menu_item` (`id`, `title`, `link`, `parent_id`, `position`) VALUES (2,'2','2.html',0,2);
INSERT INTO `menu_item` (`id`, `title`, `link`, `parent_id`, `position`) VALUES (3,'11','11.html',1,1);
INSERT INTO `menu_item` (`id`, `title`, `link`, `parent_id`, `position`) VALUES (4,'12','12.html',1,2);
INSERT INTO `menu_item` (`id`, `title`, `link`, `parent_id`, `position`) VALUES (5,'21','21.html',2,1);
INSERT INTO `menu_item` (`id`, `title`, `link`, `parent_id`, `position`) VALUES (6,'22','22.html',2,2);
INSERT INTO `menu_item` (`id`, `title`, `link`, `parent_id`, `position`) VALUES (7,'3','3.html',0,3);

Usage:

$menu = new MenuBuilder();
echo '<pre>' . htmlentities( $menu->get_menu_html() ) . '</pŕe>';


问:
Multiple Database connections at runtime using spring -jdbc or hibernate
I have one master db. After login with master db I have  some another db. Is it possible to connect at runtime to second db and also have instanace of first db also(master db) application using spring-jdbc or hibernate,
thanks in advance.

答:
Yes, sure. You can create as many data sources as you need. Just define them in the Spring Context and autowire in you classes. This question might help you with defining components with the same type but different names.

UPD1: you can create a datasource at runtime just like that:

```<code>    DataSource ds = new DataSource();
    ds.setUsername("username");
    ds.setPassword("password");
    ds.setDriverClassName("com.mysql.jdbc.Driver"); // or another driver
    ds.setUrl("jdbc:mysql://{hostname}:{port}/{dbName}?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false");
    ds.setTestWhileIdle(true);
    ds.setTestOnBorrow(true);
    ds.setTestOnReturn(false);
    ds.setValidationQuery("/* ping */ SELECT 1");
    ds.setValidationQueryTimeout(1);
    ds.setValidationInterval(30000);
    ds.setTimeBetweenEvictionRunsMillis(30000);
    ds.setMinIdle(1);
    ds.setMaxWait(10000);
    ds.setMaxIdle(10);
    ds.setInitialSize(10);
    ds.setMinEvictableIdleTimeMillis(30000);
</code>```

Body:
Yes, sure. You can create as many data sources as you need. Just define them in the Spring Context and autowire in you classes. This question might help you with defining components with the same type but different names.

UPD1: you can create a datasource at runtime just like that:

    DataSource ds = new DataSource();
    ds.setUsername("username");
    ds.setPassword("password");
    ds.setDriverClassName("com.mysql.jdbc.Driver"); // or another driver
    ds.setUrl("jdbc:mysql://{hostname}:{port}/{dbName}?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false");
    ds.setTestWhileIdle(true);
    ds.setTestOnBorrow(true);
    ds.setTestOnReturn(false);
    ds.setValidationQuery("/* ping */ SELECT 1");
    ds.setValidationQueryTimeout(1);
    ds.setValidationInterval(30000);
    ds.setTimeBetweenEvictionRunsMillis(30000);
    ds.setMinIdle(1);
    ds.setMaxWait(10000);
    ds.setMaxIdle(10);
    ds.setInitialSize(10);
    ds.setMinEvictableIdleTimeMillis(30000);


问:
How to search and select text in dropdown using selenium webdriver
I am new to Selenium and i am stuck in one implementation
My requirements are

Go to Settings page

Look for the dropdown

Fetch all values from dropdown

Look for a certain text in dropdown

If the text is not selected,Select the particular text in  dropdown

My code is as follows

```<code>void setru()
    {
        driver.switchTo().frame("contentFrame");
        Select rudropdown=new Select(driver.findElement(By.id("DefaultOrganisationDropDown")));
        List<WebElement> drop=rudropdown.getOptions();
        int e=drop.size();
        for(int i=0;i<e;i++)
        {
            String temp=drop.get(i).getText();
            String actual_RU="000139, NEXTRAN CORPORATION - JACKSONVILLE";
            boolean flag=false;
            if(temp.contains("000139"))
            {
                flag=true;
                rudropdown.selectByValue("actual_RU");

            }

        }
</code>```

But this is giving me error message.
org.openqa.selenium.NoSuchElementException: Cannot locate option with value: actual_RU

答:
It may works if you replace the below line in your code

```<code>rudropdown.selectByValue("actual_RU");
</code>```

with

```<code>rudropdown.selectByValue(temp);
</code>```

Body:
I am new to Selenium and i am stuck in one implementation
My requirements are

Go to Settings page

Look for the dropdown

Fetch all values from dropdown

Look for a certain text in dropdown

If the text is not selected,Select the particular text in  dropdown

My code is as follows

void setru()
    {
        driver.switchTo().frame("contentFrame");
        Select rudropdown=new Select(driver.findElement(By.id("DefaultOrganisationDropDown")));
        List<WebElement> drop=rudropdown.getOptions();
        int e=drop.size();
        for(int i=0;i<e;i++)
        {
            String temp=drop.get(i).getText();
            String actual_RU="000139, NEXTRAN CORPORATION - JACKSONVILLE";
            boolean flag=false;
            if(temp.contains("000139"))
            {
                flag=true;
                rudropdown.selectByValue("actual_RU");

            }

        }

But this is giving me error message.
org.openqa.selenium.NoSuchElementException: Cannot locate option with value: actual_RU

Body:
It may works if you replace the below line in your code

rudropdown.selectByValue("actual_RU");

with

rudropdown.selectByValue(temp);


问:
How to make servo reach the desired angle slowly?
I found a solution that make a servo reach a desired angle step by step , But it depends on the current angle of servo .
this is the code :

```<code>    if servo_current angle > servo_desired_angle :
        while(x=true) :
             servo_current_angle -=1
             duty_cycle = (((12.5-2.5)/(180-0) * servo_current_angle) +2.5
             p.ChangeDutyCycle (duty_cycle)
             time.sleep(0.01)
             if servo_current angle = servo_desired_angle :
                 x = false
    elif servo_current_angle < servo_desired_angle :
         while(x=true) :
             servo_current_angle +=1
             duty_cycle = (((12.5-2.5)/(180-0) * servo_current_angle) +2.5
             p.ChangeDutyCycle (duty_cycle)
             time.sleep(0.01)
             if servo_current angle = servo_desired_angle :
                 x = false
</code>```

the problem is How to know servo_current_angle ?

答:
With a typical open-loop hobby servo (one with no feedback encoder) there is no way to know the position at all.  All you can do is supply a pulse as described above and trust that the servo's load will not prevent it from moving to the commanded position.   Other options:

You can add an encoder of your own like a digital or optical encoder.

You can change to closed-loop servos (much more expensive) that have encoders built in like the Dynamixel line.

To address your problem of smoother step by step movement, you need to command it to intermediate positions between the current position and the desired position.  Think of it as taking 20 (in the example below) tiny steps instead of one big step.  To do that, use a loop to update the duty cycle. Here is an example:

```<code>current duty_cycle = 7.5
desired_duty_cycle = 5.0
steps = 20.0
duty_cycle_delta = (desired_duty_cycle - current_duty_cycle) / steps
while (current_duty_cycle != desired_duty_cycle):
    if (current_duty_cycle > desired_duty_cycle):
        duty_cycle_delta = -duty_cycle_delta
    current_duty_cycle = current_duty_cycle + duty_cycle_delta
    p.ChangeDutyCycle (current_duty_cycle)
</code>```

This will approach the desired position by commanding intermediate positions until the desired position is reached.  Alter the steps variable to alter the speed that it approaches the desired position.

Body:
I found a solution that make a servo reach a desired angle step by step , But it depends on the current angle of servo .
this is the code :

    if servo_current angle > servo_desired_angle :
        while(x=true) :
             servo_current_angle -=1
             duty_cycle = (((12.5-2.5)/(180-0) * servo_current_angle) +2.5
             p.ChangeDutyCycle (duty_cycle)
             time.sleep(0.01)
             if servo_current angle = servo_desired_angle :
                 x = false
    elif servo_current_angle < servo_desired_angle :
         while(x=true) :
             servo_current_angle +=1
             duty_cycle = (((12.5-2.5)/(180-0) * servo_current_angle) +2.5
             p.ChangeDutyCycle (duty_cycle)
             time.sleep(0.01)
             if servo_current angle = servo_desired_angle :
                 x = false

the problem is How to know servo_current_angle ?

Body:
With a typical open-loop hobby servo (one with no feedback encoder) there is no way to know the position at all.  All you can do is supply a pulse as described above and trust that the servo's load will not prevent it from moving to the commanded position.   Other options:

You can add an encoder of your own like a digital or optical encoder.

You can change to closed-loop servos (much more expensive) that have encoders built in like the Dynamixel line.

To address your problem of smoother step by step movement, you need to command it to intermediate positions between the current position and the desired position.  Think of it as taking 20 (in the example below) tiny steps instead of one big step.  To do that, use a loop to update the duty cycle. Here is an example:

current duty_cycle = 7.5
desired_duty_cycle = 5.0
steps = 20.0
duty_cycle_delta = (desired_duty_cycle - current_duty_cycle) / steps
while (current_duty_cycle != desired_duty_cycle):
    if (current_duty_cycle > desired_duty_cycle):
        duty_cycle_delta = -duty_cycle_delta
    current_duty_cycle = current_duty_cycle + duty_cycle_delta
    p.ChangeDutyCycle (current_duty_cycle)

This will approach the desired position by commanding intermediate positions until the desired position is reached.  Alter the steps variable to alter the speed that it approaches the desired position.


问:
How to stop Clion tab key behaviour
When on a C++ line of code like the following

```<code>aType.aMethod(
     std::make_shared< T_1>();
^^^^^-- Press tab here
)
</code>```

Clion tries to move to the next parameter(i guess), but being the only parameter it goes nowhere. I want to have the tab to just insert characters(tab or space that is) and not to try to cycle the cursor among the method parameter. Is there a way to stop this alternative functionality?

I searched to no avail in

Settings|Editor|CodeStyle|C/C++

Thank you

答:
"Try changing the "Next parameter" and "Previous parameter" keybindings to something else than Tab."

– Eldar Abusalimov Jul 5 '17 at 9:02

Title: How to stop Clion tab key behaviour

Body:
When on a C++ line of code like the following

aType.aMethod(
     std::make_shared< T_1>();
^^^^^-- Press tab here
)

Clion tries to move to the next parameter(i guess), but being the only parameter it goes nowhere. I want to have the tab to just insert characters(tab or space that is) and not to try to cycle the cursor among the method parameter. Is there a way to stop this alternative functionality?

I searched to no avail in

Settings|Editor|CodeStyle|C/C++

Thank you


问:
Can we able to use mulitple sparksessions to access two different Hive servers
I have a scenario to compare two different tables source and destination from two separate remote hive servers, can we able to use two SparkSessions something like I tried below:-

```<code> val spark = SparkSession.builder().master("local")
  .appName("spark remote")
  .config("javax.jdo.option.ConnectionURL", "jdbc:mysql://192.168.175.160:3306/metastore?useSSL=false")
  .config("javax.jdo.option.ConnectionUserName", "hiveroot")
  .config("javax.jdo.option.ConnectionPassword", "hivepassword")
  .config("hive.exec.scratchdir", "/tmp/hive/${user.name}")
  .config("hive.metastore.uris", "thrift://192.168.175.160:9083")
  .enableHiveSupport()
  .getOrCreate()

SparkSession.clearActiveSession()
SparkSession.clearDefaultSession()

val sparkdestination = SparkSession.builder()
  .config("javax.jdo.option.ConnectionURL", "jdbc:mysql://192.168.175.42:3306/metastore?useSSL=false")
  .config("javax.jdo.option.ConnectionUserName", "hiveroot")
  .config("javax.jdo.option.ConnectionPassword", "hivepassword")
  .config("hive.exec.scratchdir", "/tmp/hive/${user.name}")
  .config("hive.metastore.uris", "thrift://192.168.175.42:9083")
  .enableHiveSupport()
  .getOrCreate()
</code>```

I tried with  SparkSession.clearActiveSession() and SparkSession.clearDefaultSession() but it isn't working, throwing the error below:

```<code>Hive: Failed to access metastore. This class should not accessed in runtime.
org.apache.hadoop.hive.ql.metadata.HiveException: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient
</code>```

is there any other way we can achieve accessing two hive tables using multiple SparkSessions or SparkContext.

Thanks

答:
Look at SparkSession getOrCreate method

which state that

gets an existing [[SparkSession]] or, if there is no existing one,
  creates a new one based on the options set in this builder.

This method first checks whether there is a valid thread-local
  SparkSession,   and if yes, return that one. It then checks whether
  there is a valid global   default SparkSession, and if yes, return
  that one. If no valid global default   SparkSession exists, the method
  creates a new SparkSession and assigns the   newly created
  SparkSession as the global default.
      In case an existing SparkSession is returned, the config options specified in   this builder will be applied to the existing
  SparkSession.

That's the reason its returning first session and its configurations.

Please go through the docs to find out alternative ways to create session..

I'm working on <2 spark version. So I am not sure how to create new session with out collision of configuration exactly..

But, here is useful test case i.e SparkSessionBuilderSuite.scala to do that-
 DIY..

Example method in that test  case

```<code>test("use session from active thread session and propagate config options") {
    val defaultSession = SparkSession.builder().getOrCreate()
    val activeSession = defaultSession.newSession()
    SparkSession.setActiveSession(activeSession)
    val session = SparkSession.builder().config("spark-config2", "a").getOrCreate()

    assert(activeSession != defaultSession)
    assert(session == activeSession)
    assert(session.conf.get("spark-config2") == "a")
    assert(session.sessionState.conf == SQLConf.get)
    assert(SQLConf.get.getConfString("spark-config2") == "a")
    SparkSession.clearActiveSession()

    assert(SparkSession.builder().getOrCreate() == defaultSession)
    SparkSession.clearDefaultSession()
  }
</code>```

Body:
I have a scenario to compare two different tables source and destination from two separate remote hive servers, can we able to use two SparkSessions something like I tried below:-

 val spark = SparkSession.builder().master("local")
  .appName("spark remote")
  .config("javax.jdo.option.ConnectionURL", "jdbc:mysql://192.168.175.160:3306/metastore?useSSL=false")
  .config("javax.jdo.option.ConnectionUserName", "hiveroot")
  .config("javax.jdo.option.ConnectionPassword", "hivepassword")
  .config("hive.exec.scratchdir", "/tmp/hive/${user.name}")
  .config("hive.metastore.uris", "thrift://192.168.175.160:9083")
  .enableHiveSupport()
  .getOrCreate()

SparkSession.clearActiveSession()
SparkSession.clearDefaultSession()

val sparkdestination = SparkSession.builder()
  .config("javax.jdo.option.ConnectionURL", "jdbc:mysql://192.168.175.42:3306/metastore?useSSL=false")
  .config("javax.jdo.option.ConnectionUserName", "hiveroot")
  .config("javax.jdo.option.ConnectionPassword", "hivepassword")
  .config("hive.exec.scratchdir", "/tmp/hive/${user.name}")
  .config("hive.metastore.uris", "thrift://192.168.175.42:9083")
  .enableHiveSupport()
  .getOrCreate()

I tried with  SparkSession.clearActiveSession() and SparkSession.clearDefaultSession() but it isn't working, throwing the error below:

Hive: Failed to access metastore. This class should not accessed in runtime.
org.apache.hadoop.hive.ql.metadata.HiveException: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

is there any other way we can achieve accessing two hive tables using multiple SparkSessions or SparkContext.

Thanks

Body:
Look at SparkSession getOrCreate method

which state that

gets an existing [[SparkSession]] or, if there is no existing one,
  creates a new one based on the options set in this builder.

This method first checks whether there is a valid thread-local
  SparkSession,   and if yes, return that one. It then checks whether
  there is a valid global   default SparkSession, and if yes, return
  that one. If no valid global default   SparkSession exists, the method
  creates a new SparkSession and assigns the   newly created
  SparkSession as the global default.
      In case an existing SparkSession is returned, the config options specified in   this builder will be applied to the existing
  SparkSession.

That's the reason its returning first session and its configurations.

Please go through the docs to find out alternative ways to create session..

I'm working on <2 spark version. So I am not sure how to create new session with out collision of configuration exactly..

But, here is useful test case i.e SparkSessionBuilderSuite.scala to do that-
 DIY..

Example method in that test  case

test("use session from active thread session and propagate config options") {
    val defaultSession = SparkSession.builder().getOrCreate()
    val activeSession = defaultSession.newSession()
    SparkSession.setActiveSession(activeSession)
    val session = SparkSession.builder().config("spark-config2", "a").getOrCreate()

    assert(activeSession != defaultSession)
    assert(session == activeSession)
    assert(session.conf.get("spark-config2") == "a")
    assert(session.sessionState.conf == SQLConf.get)
    assert(SQLConf.get.getConfString("spark-config2") == "a")
    SparkSession.clearActiveSession()

    assert(SparkSession.builder().getOrCreate() == defaultSession)
    SparkSession.clearDefaultSession()
  }


Title: Pair IP addresses in a list pulled from xlrd

Body:
I have used xlrd to pull data from a column (Data Below). I need to group together the ip addressess. So ip address that appear next together in the output belong to the same pool and single ones are in a pool of their own. For example (10.100.33.183,10.100.33.184) belong to (pool1). (Pool6 =10.100.33.89)

How do I go about achieving this all help welcome.

['', '', '', '', '', '', '', 'Pool Member IP', '', '10.100.33.184 (S56723FR6VL01)', '10.100.33.183 (S56723FR6VL02)', '', '', '', '', '', '', '', '10.101.33.182 (S56723FR6VL03)', '10.100.33.181 (S56723FR6VL04)', '', '', '', '', '', '', '', '10.100.33.180 (S56723FR6VL05)', '10.100.33.179 (S56723FR6VL06)', '', '', '', '', '', '', '', '10.100.33.178 (S56723FR6VL07)', '10.100.33.177 (S56723FR6VL08)', '', '', '', '', '', '', '', '10.100.33.90 (S56723FR6VL09)', '', '', '', '', '', '', '', '', '10.100.33.89 (S56723FR6VL0A)', '', '', '', '', '', '', '', '', '10.100.33.91 (S56723FR6VW01)', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']

Body:
@franciscosollima's solution is good. Here's another way with regex.

iplist = ['', '', '', '', '', '', '', 'Pool Member IP', '', '10.100.33.184 (S56723FR6VL01)', '10.100.33.183 (S56723FR6VL02)', '', '', '', '', '', '', '', '10.101.33.182 (S56723FR6VL03)', '10.100.33.181 (S56723FR6VL04)', '', '', '', '', '', '', '', '10.100.33.180 (S56723FR6VL05)', '10.100.33.179 (S56723FR6VL06)', '', '', '', '', '', '', '', '10.100.33.178 (S56723FR6VL07)', '10.100.33.177 (S56723FR6VL08)', '', '', '', '', '', '', '', '10.100.33.90 (S56723FR6VL09)', '', '', '', '', '', '', '', '', '10.100.33.89 (S56723FR6VL0A)', '', '', '', '', '', '', '', '', '10.100.33.91 (S56723FR6VW01)', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']

import re

p = re.compile('[\d]+(?:\.[\d]+){3}')

pools = [[]]

for ip in iplist:
    m = p.match(ip)
    if m:
        pools[-1].append(m.group(0))
    elif not pools[-1]:
        continue
    else:
        pools.append([])

if [] in pools:
    pools.remove([])

for i, p in enumerate(pools, 1):
    print("Group " + str(i) +": " + str(p))

It's as simple as adding consecutive matches to the same pool. Otherwise, initialise a new one. The regex pattern will match from the start, and you may configure it detect IPv6 addresses too.

Prints out:

Group 1: ['10.100.33.184', '10.100.33.183']
Group 2: ['10.101.33.182', '10.100.33.181']
Group 3: ['10.100.33.180', '10.100.33.179']
Group 4: ['10.100.33.178', '10.100.33.177']
Group 5: ['10.100.33.90']
Group 6: ['10.100.33.89']
Group 7: ['10.100.33.91']


问:
What is the meaning of 'mean_test_score' in cv_result?
Hello I'm doing a GridSearchCV and I'm printing the result with the .cv_results_ function from scikit learn.

My problem is that when I'm evaluating by hand the mean on all the test score splits I obtain a different number compared to what it is written in 'mean_test_score'. Which is different from the standard np.mean()?

I attach here the code with the result:

```<code>n_estimators = [100]
max_depth = [3]
learning_rate = [0.1]

param_grid = dict(max_depth=max_depth, n_estimators=n_estimators, learning_rate=learning_rate)

gkf = GroupKFold(n_splits=7)

grid_search = GridSearchCV(model, param_grid, scoring=score_auc, cv=gkf)
grid_result = grid_search.fit(X, Y, groups=patients)

grid_result.cv_results_
</code>```

The result of this operation is:

```<code>{'mean_fit_time': array([ 8.92773601]),
 'mean_score_time': array([ 0.04288721]),
 'mean_test_score': array([ 0.83490629]),
 'mean_train_score': array([ 0.95167036]),
 'param_learning_rate': masked_array(data = [0.1],
              mask = [False],
        fill_value = ?),
 'param_max_depth': masked_array(data = [3],
              mask = [False],
        fill_value = ?),
 'param_n_estimators': masked_array(data = [100],
              mask = [False],
        fill_value = ?),
 'params': ({'learning_rate': 0.1, 'max_depth': 3, 'n_estimators': 100},),
 'rank_test_score': array([1]),
 'split0_test_score': array([ 0.74821666]),
 'split0_train_score': array([ 0.97564995]),
 'split1_test_score': array([ 0.80089016]),
 'split1_train_score': array([ 0.95361201]),
 'split2_test_score': array([ 0.92876979]),
 'split2_train_score': array([ 0.93935856]),
 'split3_test_score': array([ 0.95540287]),
 'split3_train_score': array([ 0.94718634]),
 'split4_test_score': array([ 0.89083901]),
 'split4_train_score': array([ 0.94787374]),
 'split5_test_score': array([ 0.90926355]),
 'split5_train_score': array([ 0.94829775]),
 'split6_test_score': array([ 0.82520379]),
 'split6_train_score': array([ 0.94971417]),
 'std_fit_time': array([ 1.79167576]),
 'std_score_time': array([ 0.02970254]),
 'std_test_score': array([ 0.0809713]),
 'std_train_score': array([ 0.0105566])}
</code>```

As you can see, doing the np.mean of all the test_score it gives you a value approximately of 0.8655122606479532 while the 'mean_test_score' is 0.83490629

Thanks for you help,
Leonardo.

答:
I will post this as a new answer since its so much code:

The test and train scores of the folds are: (taken from the results you posted in your question)

```<code>test_scores = [0.74821666,0.80089016,0.92876979,0.95540287,0.89083901,0.90926355,0.82520379]
train_scores = [0.97564995,0.95361201,0.93935856,0.94718634,0.94787374,0.94829775,0.94971417]
</code>```

The amount of training samples in those folds are: (taken from the output of print([(len(train), len(test)) for train, test in gkf.split(X, groups=patients)]))

```<code>train_len = [41835, 56229, 56581, 58759, 60893, 60919, 62056]
test_len = [24377, 9983, 9631, 7453, 5319, 5293, 4156]
</code>```

Then the test- and train-means with the amount of training samples per fold as weight is:

```<code>train_avg = np.average(train_scores, weights=train_len)
-> 0.95064898361714389
test_avg = np.average(test_scores, weights=test_len)
-> 0.83490628649308296
</code>```

So this is exactly the value sklearn gives you. It is also the correct mean accuracy of your classification. The mean of the folds is incorrect in that it depends on the somewhat arbitrary splits/folds you chose.

So in concusion, both explanations were indeed identical and correct.

Body:
Hello I'm doing a GridSearchCV and I'm printing the result with the .cv_results_ function from scikit learn.

My problem is that when I'm evaluating by hand the mean on all the test score splits I obtain a different number compared to what it is written in 'mean_test_score'. Which is different from the standard np.mean()?

I attach here the code with the result:

n_estimators = [100]
max_depth = [3]
learning_rate = [0.1]

param_grid = dict(max_depth=max_depth, n_estimators=n_estimators, learning_rate=learning_rate)

gkf = GroupKFold(n_splits=7)

grid_search = GridSearchCV(model, param_grid, scoring=score_auc, cv=gkf)
grid_result = grid_search.fit(X, Y, groups=patients)

grid_result.cv_results_

The result of this operation is:

{'mean_fit_time': array([ 8.92773601]),
 'mean_score_time': array([ 0.04288721]),
 'mean_test_score': array([ 0.83490629]),
 'mean_train_score': array([ 0.95167036]),
 'param_learning_rate': masked_array(data = [0.1],
              mask = [False],
        fill_value = ?),
 'param_max_depth': masked_array(data = [3],
              mask = [False],
        fill_value = ?),
 'param_n_estimators': masked_array(data = [100],
              mask = [False],
        fill_value = ?),
 'params': ({'learning_rate': 0.1, 'max_depth': 3, 'n_estimators': 100},),
 'rank_test_score': array([1]),
 'split0_test_score': array([ 0.74821666]),
 'split0_train_score': array([ 0.97564995]),
 'split1_test_score': array([ 0.80089016]),
 'split1_train_score': array([ 0.95361201]),
 'split2_test_score': array([ 0.92876979]),
 'split2_train_score': array([ 0.93935856]),
 'split3_test_score': array([ 0.95540287]),
 'split3_train_score': array([ 0.94718634]),
 'split4_test_score': array([ 0.89083901]),
 'split4_train_score': array([ 0.94787374]),
 'split5_test_score': array([ 0.90926355]),
 'split5_train_score': array([ 0.94829775]),
 'split6_test_score': array([ 0.82520379]),
 'split6_train_score': array([ 0.94971417]),
 'std_fit_time': array([ 1.79167576]),
 'std_score_time': array([ 0.02970254]),
 'std_test_score': array([ 0.0809713]),
 'std_train_score': array([ 0.0105566])}

As you can see, doing the np.mean of all the test_score it gives you a value approximately of 0.8655122606479532 while the 'mean_test_score' is 0.83490629

Thanks for you help,
Leonardo.

Body:
I will post this as a new answer since its so much code:

The test and train scores of the folds are: (taken from the results you posted in your question)

test_scores = [0.74821666,0.80089016,0.92876979,0.95540287,0.89083901,0.90926355,0.82520379]
train_scores = [0.97564995,0.95361201,0.93935856,0.94718634,0.94787374,0.94829775,0.94971417]

The amount of training samples in those folds are: (taken from the output of print([(len(train), len(test)) for train, test in gkf.split(X, groups=patients)]))

train_len = [41835, 56229, 56581, 58759, 60893, 60919, 62056]
test_len = [24377, 9983, 9631, 7453, 5319, 5293, 4156]

Then the test- and train-means with the amount of training samples per fold as weight is:

train_avg = np.average(train_scores, weights=train_len)
-> 0.95064898361714389
test_avg = np.average(test_scores, weights=test_len)
-> 0.83490628649308296

So this is exactly the value sklearn gives you. It is also the correct mean accuracy of your classification. The mean of the folds is incorrect in that it depends on the somewhat arbitrary splits/folds you chose.

So in concusion, both explanations were indeed identical and correct.


问:
Is it possible to add comments to eclipse.ini file
I wanted to comment some custom parameters I am using now, to remember why they are there the next time I edit it.

But I cannot find any reference to comments in this file. Only this, but it is pretty old and hopefully there is a way to add comments now.

Somebody knows?

答:
Eclipse 4.5.2 on Windows 7, # is working for me.
but be careful, key - value are in separate line in eclipse.ini and you need to comment out key-value in same time. I added a example.

Working

```<code>#-clean
-startup
plugins/org.eclipse.equinox.launcher_1.3.100.v20150511-1540.jar
-showlocation
#-vm
#C:/dev/software/jdk1.8.0_121/bin/javaw.exe
-vm
C:/dev/software/jdk1.8.0_131/bin/javaw.exe
</code>```

Not working

```<code>-vm
#C:/dev/software/jdk1.8.0_121/bin/javaw.exe
C:/dev/software/jdk1.8.0_131/bin/javaw.exe
</code>```

Body:
Eclipse 4.5.2 on Windows 7, # is working for me.
but be careful, key - value are in separate line in eclipse.ini and you need to comment out key-value in same time. I added a example.

Working

#-clean
-startup
plugins/org.eclipse.equinox.launcher_1.3.100.v20150511-1540.jar
-showlocation
#-vm
#C:/dev/software/jdk1.8.0_121/bin/javaw.exe
-vm
C:/dev/software/jdk1.8.0_131/bin/javaw.exe

Not working

-vm
#C:/dev/software/jdk1.8.0_121/bin/javaw.exe
C:/dev/software/jdk1.8.0_131/bin/javaw.exe


问:
Touch events interception and routing
I have a MapControl and I am showing a MapIcon in the center of the map, which I update every second and center again. This works nice.

But now, I am trying to disable all gestures and touch events for the MapControl without success. The closest I have been to accomplish this is disabling all the four InteractionModes like PanInteractionMode. But if you try to drag the map with two fingers, it is still dragged and this is not acceptable.

On top on that, the MapControl is inside a Pivot control and I would like to route the MapControl events towards the Pivot so it can detect swipe gestures over the map too.

Am I dreaming too much?

答:
When I set the following four interaction modes to Disabled, I can no longer interact with the map. I am on Windows 10 Creators Update.

But even with them plus setting IsHitTestVisible to False, the MapControl would still swallow any input. The workaround is to overlay a transparent Rectangle. This way the swipe on Pivot will work again.

```<code><PivotItem Header="PivotItem 0">
    <Grid>
        <Maps:MapControl PanInteractionMode="Disabled"
                         RotateInteractionMode="Disabled"
                         TiltInteractionMode="Disabled"
                         ZoomInteractionMode="Disabled"
                         IsHitTestVisible="False" />
        <Rectangle Fill="Transparent" />
    </Grid>
</PivotItem>
</code>```

Title: Touch events interception and routing

Body:
When I set the following four interaction modes to Disabled, I can no longer interact with the map. I am on Windows 10 Creators Update.

But even with them plus setting IsHitTestVisible to False, the MapControl would still swallow any input. The workaround is to overlay a transparent Rectangle. This way the swipe on Pivot will work again.

<PivotItem Header="PivotItem 0">
    <Grid>
        <Maps:MapControl PanInteractionMode="Disabled"
                         RotateInteractionMode="Disabled"
                         TiltInteractionMode="Disabled"
                         ZoomInteractionMode="Disabled"
                         IsHitTestVisible="False" />
        <Rectangle Fill="Transparent" />
    </Grid>
</PivotItem>


问:
VB6 Manifest not working on Windows 7
I have created a manifest file for a VB6 application that is running on Windows 7 (not for any visual style changes, just to make sure it accesses the common registry and not a virtualised one)

The exe name is Capadm40.exe, the manifest is named Capadm40.exe.manifest and contains the following:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <assemblyIdentity version="1.0.0.0"
     processorArchitecture="X86"
     name="CompanyName.Capadm40"
     type="win32"/>
  <description>Administers the System</description>
  <!-- Identify the application security requirements. -->
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel
          level="asInvoker"
          uiAccess="false"/>
        </requestedPrivileges>
       </security>
  </trustInfo>
</assembly>
</code>```

However, this doesn't seem to make any difference. ie the application is still using the virtualised registry hive. What is also strange is the after I unticked the 'Run this program as an administrator' option in the properties of the application exe, windows still shows a shield on the application icon, leading my to think this is some issue with my windows installation rather than a fault with the manifest. Any ideas?

答:
You're probably running afoul of the fusion cache (and the Explorer Shell's icon cache).  External manifests are strongly discouraged anyway, but trying to add one after the program has previously been run often leads to such symptoms.

See Manifest and the fusion cache for a brief description.

You could also touch the EXE to reload the cache.

Title: VB6 Manifest not working on Windows 7

Body:
I have created a manifest file for a VB6 application that is running on Windows 7 (not for any visual style changes, just to make sure it accesses the common registry and not a virtualised one)

The exe name is Capadm40.exe, the manifest is named Capadm40.exe.manifest and contains the following:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <assemblyIdentity version="1.0.0.0"
     processorArchitecture="X86"
     name="CompanyName.Capadm40"
     type="win32"/>
  <description>Administers the System</description>

  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel
          level="asInvoker"
          uiAccess="false"/>
        </requestedPrivileges>
       </security>
  </trustInfo>
</assembly>

However, this doesn't seem to make any difference. ie the application is still using the virtualised registry hive. What is also strange is the after I unticked the 'Run this program as an administrator' option in the properties of the application exe, windows still shows a shield on the application icon, leading my to think this is some issue with my windows installation rather than a fault with the manifest. Any ideas?


问:
How can I fill / populate DropDown with my IEnumerable<Model> value ASP.NET MVC
I tried to set my dropdown list values from my model as it is the value I need to see in the dropdown
But I'm facing an error:

The type arguments for method
  'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper,
  System.Linq.Expressions.Expression>,
  System.Collections.Generic.IEnumerable,
  string)' cannot be inferred from the usage. Try specifying the type
  arguments explicitly.

And here is my code:

```<code>@model IEnumerable<Language>
@using Web.Helpers
@{
    ViewBag.Title = "";
}
<div class="">
    <div class="row">
        <div class="col-md-12 col-sm-12 col-xs-12">
            <div class="x_panel">
                <div class="x_title">
                    <h2><i class="fa fa-filter"></i> </h2>
                    <div class="clearfix"></div>
                </div>
                <div class="x_content">
                    <br />
                    @using (Html.BeginForm("Settings","Language", FormMethod.Post, new { @class = "form-horizontal form-label-left" }))
                    {
                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)

                        <div class="col-md-12 col-sm-12">
                            <div class="col-md-12 col-sm-12">
                                @Html.DropDownListFor(WHATTOWRITEHERE, new SelectList(ViewBag.Languagess, "Id", "Name"), new { @class = "form-control" })
                            </div>
                        </div>

                    }

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

Controller action:

```<code>public ActionResult Settings()
{
   List<Language> activeL = LanguageController.GetAll();
   ViewBag.Languagess = activeLanguages;

   return View(activeL);
}
</code>```

Maybe I could delete ViewBag.Languagess at all, so I can use  (Model, "Id", "Name") there instad of (ViewBag.Languagess, "Id", "Name")

答:
It would work like in this example:</p>

```<code>@{
   List<SelectListItem> listItems= new List<SelectListItem>();
   listItems.Add(new SelectListItem
        {
          Text = "Exemplo1",
          Value = "Exemplo1"
        });
   listItems.Add(new SelectListItem
        {
            Text = "Exemplo2",
            Value = "Exemplo2",
            Selected = true
        });
   listItems.Add(new SelectListItem
        {
            Text = "Exemplo3",
            Value = "Exemplo3"
        });
}

@Html.DropDownListFor(model => model.tipo, listItems, "-- Select Status --")
</code>```

Body:
I tried to set my dropdown list values from my model as it is the value I need to see in the dropdown
But I'm facing an error:

The type arguments for method
  'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper,
  System.Linq.Expressions.Expression>,
  System.Collections.Generic.IEnumerable,
  string)' cannot be inferred from the usage. Try specifying the type
  arguments explicitly.

And here is my code:

@model IEnumerable<Language>
@using Web.Helpers
@{
    ViewBag.Title = "";
}

                    @using (Html.BeginForm("Settings","Language", FormMethod.Post, new { @class = "form-horizontal form-label-left" }))
                    {
                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)

                                @Html.DropDownListFor(WHATTOWRITEHERE, new SelectList(ViewBag.Languagess, "Id", "Name"), new { @class = "form-control" })

                    }

                }
            }
        }
    }
}

Controller action:

public ActionResult Settings()
{
   List<Language> activeL = LanguageController.GetAll();
   ViewBag.Languagess = activeLanguages;

   return View(activeL);
}

Maybe I could delete ViewBag.Languagess at all, so I can use  (Model, "Id", "Name") there instad of (ViewBag.Languagess, "Id", "Name")

Body:
It would work like in this example:

@{
   List<SelectListItem> listItems= new List<SelectListItem>();
   listItems.Add(new SelectListItem
        {
          Text = "Exemplo1",
          Value = "Exemplo1"
        });
   listItems.Add(new SelectListItem
        {
            Text = "Exemplo2",
            Value = "Exemplo2",
            Selected = true
        });
   listItems.Add(new SelectListItem
        {
            Text = "Exemplo3",
            Value = "Exemplo3"
        });
}

@Html.DropDownListFor(model => model.tipo, listItems, "-- Select Status --")


问:
PHP - Echoing multiple nested quotes of HTML
I'm attempting to echo the following line of HTML through PHP

```<code>echo "<a class='fa fa-ban fa-2x cancelClass' onClick='cancelClass('$id', '$formattedDate', '$time')'></a><p class='text-center'>".$formattedDate." @ $time</p>";
</code>```

I don't get an error. But the quotes for onClick='cancelClass... don't get parsed properly, which leads to the javascript function not executing.

How it gets color coded in Google Chrome Source View

How it should get color coded (example of another function)

答:
Using double quotes in HTML.
Using htmlspecialchars with ENT_QUOTES to escape values which have double quote.</p>

```<code>echo '<a class="fa fa-ban fa-2x cancelClass" onClick="'.htmlspecialchars("cancelClass('$id', '$formattedDate', '$time')", ENT_QUOTES).
 '"></a><p class="text-center">'.$formattedDate." @ $time</p>";
</code>```

Body:
I'm attempting to echo the following line of HTML through PHP

echo "
".$formattedDate." @ $time
";

I don't get an error. But the quotes for onClick='cancelClass... don't get parsed properly, which leads to the javascript function not executing.

How it gets color coded in Google Chrome Source View

How it should get color coded (example of another function)

Body:
Using double quotes in HTML.
Using htmlspecialchars with ENT_QUOTES to escape values which have double quote.

echo '<a class="fa fa-ban fa-2x cancelClass" onClick="'.htmlspecialchars("cancelClass('$id', '$formattedDate', '$time')", ENT_QUOTES).
 '"></a><p class="text-center">'.$formattedDate." @ $time</p>";


问:
android: fit height of DrawableLeft in a textView
I am trying to display a blue line next to a block of text, pretty much like this:

Here's my code:

```<code><TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:drawableLeft="@drawable/blue_line" />
</code>```

blue_line is a jpg file. a blue rectangle. it displays in its original size regardless of the text in the textview. how can i adjust its height dynamically according to the height of the text? like make it shorter when theres little amount of text and longer when there's more text....

答:
I Created a class that extends TextView, and resize the drawables in onPreDrawListener.

```<code>public class MyTextView extends AppCompatTextView {

    public MyTextView(Context context, AttributeSet attrs, int style) {
        super(context, attrs, style);
        fitCompoundDrawableToLineHeight();
    }

    private void fitCompoundDrawableToLineHeight() {
        OnPreDraw.run(this, () -> {
            final Drawable[] cd = getCompoundDrawables();
            Arrays.stream(cd)
                .filter(drawable -> drawable != null)
                .forEach(d -> d.setBounds(0, 0, getLineHeight(), getLineHeight()));
            setCompoundDrawables(cd[0], cd[1], cd[2], cd[3]);
        });
    }
}

// Convenience class that abstracts onPreDraw logic
public class OnPreDraw {
    public static void run(View view, Runnable task) {
        view.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (!view.getViewTreeObserver().isAlive()) {
                    return true;
                }
                view.getViewTreeObserver().removeOnPreDrawListener(this);
                task.run();
                return true;
            }
        });
    }
}
</code>```

Body:
I am trying to display a blue line next to a block of text, pretty much like this:

Here's my code:

<TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:drawableLeft="@drawable/blue_line" />

blue_line is a jpg file. a blue rectangle. it displays in its original size regardless of the text in the textview. how can i adjust its height dynamically according to the height of the text? like make it shorter when theres little amount of text and longer when there's more text....

Body:
I Created a class that extends TextView, and resize the drawables in onPreDrawListener.

public class MyTextView extends AppCompatTextView {

    public MyTextView(Context context, AttributeSet attrs, int style) {
        super(context, attrs, style);
        fitCompoundDrawableToLineHeight();
    }

    private void fitCompoundDrawableToLineHeight() {
        OnPreDraw.run(this, () -> {
            final Drawable[] cd = getCompoundDrawables();
            Arrays.stream(cd)
                .filter(drawable -> drawable != null)
                .forEach(d -> d.setBounds(0, 0, getLineHeight(), getLineHeight()));
            setCompoundDrawables(cd[0], cd[1], cd[2], cd[3]);
        });
    }
}

// Convenience class that abstracts onPreDraw logic
public class OnPreDraw {
    public static void run(View view, Runnable task) {
        view.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (!view.getViewTreeObserver().isAlive()) {
                    return true;
                }
                view.getViewTreeObserver().removeOnPreDrawListener(this);
                task.run();
                return true;
            }
        });
    }
}