问:
Custom dialog works wrong on android 7.1.1
Hi im working with custom dialog in android,
my code:

```<code>public void generarDialogoParametros(String titulo, boolean llamaNumero) {
    Dialog dialogo = new Dialog(context,R.style.AlertDialogTheme);
    dialogo.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialogo.setContentView(R.layout.dialogo_parametros);
    dialogo.setTitle(titulo);
    TextView spo2 = (TextView) dialogo.findViewById(R.id.editTextSPO2);
    TextView pulsobajo = (TextView) dialogo.findViewById(R.id.editTextPulsoAlto);
    TextView pulsoalto = (TextView) dialogo.findViewById(R.id.editTextPulsoBajo);
    Button guardar = (Button) dialogo.findViewById(R.id.btnAceptarParametros);
    Button cancelar = (Button) dialogo.findViewById(R.id.btnCancelarParametros);
    spo2.setText(preferencias.getSPO2() + "");
    pulsoalto.setText(preferencias.getPulsoAlto() + "");
    pulsobajo.setText(preferencias.getPulsoBajo() + "");
    guardarParametrosNuevos(guardar,cancelar, dialogo, spo2, pulsoalto, pulsobajo, llamaNumero);
    dialogo.show();
    dialogo.setCancelable(false);
}
</code>```

in android 4,5,6 works like:

But in 7+

I dont know, how i'm fix it can help me?

答:
Try this  set hight and width of your dialog programatically using below code</p>

```<code>    public void generarDialogoParametros(String titulo, boolean llamaNumero) {
            Dialog dialogo = new Dialog(context,R.style.AlertDialogTheme);
            dialogo.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialogo.setContentView(R.layout.dialogo_parametros);
            Window window = dialogo.getWindow();
            window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
            window.setGravity(Gravity.CENTER);
            dialogo.setTitle(titulo);
            TextView spo2 = (TextView) dialogo.findViewById(R.id.editTextSPO2);
            TextView pulsobajo = (TextView) dialogo.findViewById(R.id.editTextPulsoAlto);
            TextView pulsoalto = (TextView) dialogo.findViewById(R.id.editTextPulsoBajo);
            Button guardar = (Button) dialogo.findViewById(R.id.btnAceptarParametros);
            Button cancelar = (Button) dialogo.findViewById(R.id.btnCancelarParametros);
            spo2.setText(preferencias.getSPO2() + "");
            pulsoalto.setText(preferencias.getPulsoAlto() + "");
            pulsobajo.setText(preferencias.getPulsoBajo() + "");
            guardarParametrosNuevos(guardar,cancelar, dialogo, spo2, pulsoalto, pulsobajo, llamaNumero);
            dialogo.show();
            dialogo.setCancelable(false);
        }
</code>```

Body:
Hi im working with custom dialog in android,
my code:

public void generarDialogoParametros(String titulo, boolean llamaNumero) {
    Dialog dialogo = new Dialog(context,R.style.AlertDialogTheme);
    dialogo.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialogo.setContentView(R.layout.dialogo_parametros);
    dialogo.setTitle(titulo);
    TextView spo2 = (TextView) dialogo.findViewById(R.id.editTextSPO2);
    TextView pulsobajo = (TextView) dialogo.findViewById(R.id.editTextPulsoAlto);
    TextView pulsoalto = (TextView) dialogo.findViewById(R.id.editTextPulsoBajo);
    Button guardar = (Button) dialogo.findViewById(R.id.btnAceptarParametros);
    Button cancelar = (Button) dialogo.findViewById(R.id.btnCancelarParametros);
    spo2.setText(preferencias.getSPO2() + "");
    pulsoalto.setText(preferencias.getPulsoAlto() + "");
    pulsobajo.setText(preferencias.getPulsoBajo() + "");
    guardarParametrosNuevos(guardar,cancelar, dialogo, spo2, pulsoalto, pulsobajo, llamaNumero);
    dialogo.show();
    dialogo.setCancelable(false);
}

in android 4,5,6 works like:

But in 7+

I dont know, how i'm fix it can help me?

Body:
Try this  set hight and width of your dialog programatically using below code

    public void generarDialogoParametros(String titulo, boolean llamaNumero) {
            Dialog dialogo = new Dialog(context,R.style.AlertDialogTheme);
            dialogo.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialogo.setContentView(R.layout.dialogo_parametros);
            Window window = dialogo.getWindow();
            window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
            window.setGravity(Gravity.CENTER);
            dialogo.setTitle(titulo);
            TextView spo2 = (TextView) dialogo.findViewById(R.id.editTextSPO2);
            TextView pulsobajo = (TextView) dialogo.findViewById(R.id.editTextPulsoAlto);
            TextView pulsoalto = (TextView) dialogo.findViewById(R.id.editTextPulsoBajo);
            Button guardar = (Button) dialogo.findViewById(R.id.btnAceptarParametros);
            Button cancelar = (Button) dialogo.findViewById(R.id.btnCancelarParametros);
            spo2.setText(preferencias.getSPO2() + "");
            pulsoalto.setText(preferencias.getPulsoAlto() + "");
            pulsobajo.setText(preferencias.getPulsoBajo() + "");
            guardarParametrosNuevos(guardar,cancelar, dialogo, spo2, pulsoalto, pulsobajo, llamaNumero);
            dialogo.show();
            dialogo.setCancelable(false);
        }


来源: stackexchange

问:
Undefined Name "Y", as well as weird outputting issue
my code compiles, but when I try to run it, it gives me an error of "undefined name" when I'm running a Y/N loop control variable.  I've input the coding of the whole program below.

Also, it displays the closing dialog while it's asking the loop question.. what did I do wrong here?

```<code>//declarations
String itemName;  //name of item
String itemPriceInput;  //user input of price
double itemPrice;  //parsed name of price
String itemQuantityInput;  //user input of quantity
double itemQuantity; //parsed input of quantity
String inputMore; //loop control

//Create file instance
java.io.File itemAttributes = new java.io.File("Items_In_Stock.txt");

//Create a scanner for the file
Scanner input = new Scanner(itemAttributes);

System.out.println("Welcome to the inventory list program");  //welcome dialog for user
System.out.println("This program will show items on hand, as well as their info"); //more dialog

System.out.println("Enter 'Y' to proceed, or 'Q' to quit"); //asking to start program

inputMore=input.next(); //taking input for loop control

while (inputMore.equalsIgnoreCase("y")) //beginning outer loop

{
  while (input.hasNext()) //beginning inner loop
  {
    itemName=input.next(); // input item name
    System.out.print (" ");

    itemPriceInput=input.next(); //input item price
    itemPrice=Double.parseDouble(itemPriceInput); //parse to double
    System.out.print (" ");

    itemQuantityInput=input.next(); //input quantity
    itemQuantity=Double.parseDouble(itemQuantityInput); //parse to double

    System.out.println("Name: " + itemName + " " + "Price: " + itemPrice + " " + "Quantity: " + itemQuantity); //display input items
  } //close inner loop

  System.out.print("Enter 'Y' to input more, or 'Q' to quit"); //asking user to input more, or quit

} //close outer loop
  input.close(); //close program

  System.out.println("Thank you for using the program.  Goodbye");//goodbye statement
</code>```

答:
I will assume your txt file contains data like

```<code>ddda 8998 787
gdfgd 8998 787
</code>```

I can see two flaws so far:
As you are asking user "Enter 'Y' to proceed, or 'Q' to quit" you should take different scanner for this using System.in.

Also why are you using while loop inside?? You shoul use if condition there to be able to ask user for choice..

Here's the updated code. It will solve your issue:

```<code>// declarations
        String itemName; // name of item
        String itemPriceInput; // user input of price
        double itemPrice; // parsed name of price
        String itemQuantityInput; // user input of quantity
        double itemQuantity; // parsed input of quantity
        String inputMore; // loop control

        // Create file instance
        java.io.File itemAttributes = new java.io.File("Items_In_Stock.txt");

        // Create a scanner for the file
        Scanner input = new Scanner(itemAttributes);

        System.out.println("Welcome to the inventory list program");
        System.out
                .println("This program will show items on hand, as well as their info");

        System.out.println("Enter 'Y' to proceed, or 'Q' to quit");
//      inputMore = input.next(); // taking input for loop control

        Scanner sc = new Scanner(System.in);
//      System.out.println(inputMore);
        while (sc.next().equalsIgnoreCase("y")) // beginning outer loop

        {
            if(input.hasNext()) // beginning inner loop
            {
                itemName = input.next(); // input item name

                itemPriceInput = input.next(); // input item price
                itemPrice = Double.parseDouble(itemPriceInput); // parse to
                                                                // double

                itemQuantityInput = input.next(); // input quantity
                itemQuantity = Double.parseDouble(itemQuantityInput); // parse
                                                                        // to
                                                                        // double

                System.out.println("Name: " + itemName + " " + "Price: "
                        + itemPrice + " " + "Quantity: " + itemQuantity); // display
                                                                            // input
                                                                            // items
            } // close inner loop
            else
            {
                System.out.println("No more records");
                break;
            }

            System.out.print("Enter 'Y' to input more, or 'Q' to quit"); // asking
                                                                            // user
                                                                            // to
                                                                            // input
                                                                            // more,
                                                                            // or
//          inputMore = input.next();                                                               // quit

        } // close outer loop
        input.close(); // close program

        System.out.println("Thank you for using the program.  Goodbye");// goodbye
                                                                        // statement}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
my code compiles, but when I try to run it, it gives me an error of "undefined name" when I'm running a Y/N loop control variable.  I've input the coding of the whole program below.

Also, it displays the closing dialog while it's asking the loop question.. what did I do wrong here?

//declarations
String itemName;  //name of item
String itemPriceInput;  //user input of price
double itemPrice;  //parsed name of price
String itemQuantityInput;  //user input of quantity
double itemQuantity; //parsed input of quantity
String inputMore; //loop control

//Create file instance
java.io.File itemAttributes = new java.io.File("Items_In_Stock.txt");

//Create a scanner for the file
Scanner input = new Scanner(itemAttributes);

System.out.println("Welcome to the inventory list program");  //welcome dialog for user
System.out.println("This program will show items on hand, as well as their info"); //more dialog

System.out.println("Enter 'Y' to proceed, or 'Q' to quit"); //asking to start program

inputMore=input.next(); //taking input for loop control

while (inputMore.equalsIgnoreCase("y")) //beginning outer loop

{
  while (input.hasNext()) //beginning inner loop
  {
    itemName=input.next(); // input item name
    System.out.print (" ");

    itemPriceInput=input.next(); //input item price
    itemPrice=Double.parseDouble(itemPriceInput); //parse to double
    System.out.print (" ");

    itemQuantityInput=input.next(); //input quantity
    itemQuantity=Double.parseDouble(itemQuantityInput); //parse to double

    System.out.println("Name: " + itemName + " " + "Price: " + itemPrice + " " + "Quantity: " + itemQuantity); //display input items
  } //close inner loop

  System.out.print("Enter 'Y' to input more, or 'Q' to quit"); //asking user to input more, or quit

} //close outer loop
  input.close(); //close program

  System.out.println("Thank you for using the program.  Goodbye");//goodbye statement

Body:
I will assume your txt file contains data like

ddda 8998 787
gdfgd 8998 787

I can see two flaws so far:
As you are asking user "Enter 'Y' to proceed, or 'Q' to quit" you should take different scanner for this using System.in.

Also why are you using while loop inside?? You shoul use if condition there to be able to ask user for choice..

Here's the updated code. It will solve your issue:

// declarations
        String itemName; // name of item
        String itemPriceInput; // user input of price
        double itemPrice; // parsed name of price
        String itemQuantityInput; // user input of quantity
        double itemQuantity; // parsed input of quantity
        String inputMore; // loop control

        // Create file instance
        java.io.File itemAttributes = new java.io.File("Items_In_Stock.txt");

        // Create a scanner for the file
        Scanner input = new Scanner(itemAttributes);

        System.out.println("Welcome to the inventory list program");
        System.out
                .println("This program will show items on hand, as well as their info");

        System.out.println("Enter 'Y' to proceed, or 'Q' to quit");
//      inputMore = input.next(); // taking input for loop control

        Scanner sc = new Scanner(System.in);
//      System.out.println(inputMore);
        while (sc.next().equalsIgnoreCase("y")) // beginning outer loop

        {
            if(input.hasNext()) // beginning inner loop
            {
                itemName = input.next(); // input item name

                itemPriceInput = input.next(); // input item price
                itemPrice = Double.parseDouble(itemPriceInput); // parse to
                                                                // double

                itemQuantityInput = input.next(); // input quantity
                itemQuantity = Double.parseDouble(itemQuantityInput); // parse
                                                                        // to
                                                                        // double

                System.out.println("Name: " + itemName + " " + "Price: "
                        + itemPrice + " " + "Quantity: " + itemQuantity); // display
                                                                            // input
                                                                            // items
            } // close inner loop
            else
            {
                System.out.println("No more records");
                break;
            }

            System.out.print("Enter 'Y' to input more, or 'Q' to quit"); // asking
                                                                            // user
                                                                            // to
                                                                            // input
                                                                            // more,
                                                                            // or
//          inputMore = input.next();                                                               // quit

        } // close outer loop
        input.close(); // close program

        System.out.println("Thank you for using the program.  Goodbye");// goodbye
                                                                        // statement}


问:
node.js Project Works on Local Machine, Issues when Deployed on Heroku
I have a node.js + Express project that I've been working on, and it's been working when I run it on my machine. I've set port 4200 for my Express API, with

```<code>var port = 4200;
</code>```

in app.js

I access the API using axios in React:

```<code>axios.get('https://localhost:4200/posts ... etc
</code>```

This all works when I run it on my machine, but when I deploy this with Heroku, I get this error:

GET https://localhost:4200/posts net::ERR_CONNECTION_REFUSED

Error: Network Error
      at createError (createError.js:16)
      at XMLHttpRequest.handleError (xhr.js:87)

How do I fix this?

答:
There are two thing I would like to highlight:

1)
Quoting from https://devcenter.heroku.com/articles/deploying-nodejs#specifying-a-start-script

The command in a web process type must bind to the port number specified in the PORT environment variable. If it does not, the dyno will not start.

So what you should do is

```<code>var port = process.env.PORT || 4200;
</code>```

Now when working on local system port 4200 will be used and when deployed on heroku port assigned by environment variable will be used.

2)
From your question you say you are using axios.get('https://localhost:4200/posts ... etc. When app is deployed how is it supposed to use localhost?

Change localhost to whatever the domain you get when creating app on Heroku.

Body:
I have a node.js + Express project that I've been working on, and it's been working when I run it on my machine. I've set port 4200 for my Express API, with

var port = 4200;

in app.js

I access the API using axios in React:

axios.get('https://localhost:4200/posts ... etc

This all works when I run it on my machine, but when I deploy this with Heroku, I get this error:

GET https://localhost:4200/posts net::ERR_CONNECTION_REFUSED

Error: Network Error
      at createError (createError.js:16)
      at XMLHttpRequest.handleError (xhr.js:87)

How do I fix this?

Body:
There are two thing I would like to highlight:

1)
Quoting from https://devcenter.heroku.com/articles/deploying-nodejs#specifying-a-start-script

The command in a web process type must bind to the port number specified in the PORT environment variable. If it does not, the dyno will not start.

So what you should do is

var port = process.env.PORT || 4200;

Now when working on local system port 4200 will be used and when deployed on heroku port assigned by environment variable will be used.

2)
From your question you say you are using axios.get('https://localhost:4200/posts ... etc. When app is deployed how is it supposed to use localhost?

Change localhost to whatever the domain you get when creating app on Heroku.


问:
Home page down due to Woocommerce Wechat Pay plugin
This is a shoppingmall manager. Our website is www.picknfit.com

Last Friday, we tried to add wechat pay for payment, and dowloaded Woocommerce Wechat Pay.

However, we received fatal error, and our homepage went down. Is there a solution to restore our website?

答:
There is another plugin declaring class ILogHandler.

Step 1:
Deactivate the plugin 'WordPress WooCommerce 微信支付插件' (wechat-weixin-payments-for-woocommerce) your website should be up and running.

Step 2:
Write to the plugin author explain him error. Ask him to namespace the class name.


问:
Missing closing paranthes MySQL workbench, Query syntax
this is my code:

```<code>SELECT Lname
    ,Fname
FROM EMPLOYEE
WHERE NOT EXISTS (
        SELECT *
        FROM WORKS_ON B
        WHERE (
                B.Pno IN (
                    SELECT Pnumber
                    FROM PROJECT
                    WHERE Dnum = 5
                        AND NOT EXISTS (
                            SELECT *
                            FROM WORKS_ON C
                            WHERE C.Essn = Ssn
                                AND C.Pno = B.Pno
                            )
                    )
                );
</code>```

It is almost true but it doesn't work error message : Missing closing parenthesis

答: Closing parenthesis is that ) thing on the end. The error is telling you that you have four ('s, but only three )'s.

Body:
this is my code:

SELECT Lname
    ,Fname
FROM EMPLOYEE
WHERE NOT EXISTS (
        SELECT *
        FROM WORKS_ON B
        WHERE (
                B.Pno IN (
                    SELECT Pnumber
                    FROM PROJECT
                    WHERE Dnum = 5
                        AND NOT EXISTS (
                            SELECT *
                            FROM WORKS_ON C
                            WHERE C.Essn = Ssn
                                AND C.Pno = B.Pno
                            )
                    )
                );

It is almost true but it doesn't work error message : Missing closing parenthesis


问:
How do I query for an object with an object array property in MySQL?
I have seen this asked before in different ways, but I'm hoping for a straight answer.

If I have two classes, Parent and Child, stored in two different MySQL tables, what is the best way of querying for a complete Parent object, with a list of all Children?

e.g.

```<code>class Parent {
   id: number;
   name: string;
   Children: Child[]
}

class Child {
   id: number;
   name: string;
   age: number;
}
</code>```

How do I get a list of matching Parents by name, with a list of children for each?

Do I have to write a query to grab all matching Parents, and then an additional query for each Parent to get all the Child elements?

This is obviously pseudo-SQL, but I'm hoping for something like this:

```<code>SELECT p.id, p.name,
(SELECT * from c) as children from parent p LEFT JOIN child c on p.id = c.parent_id
</code>```

答:
If your parent table container child_id then

```<code>SELECT p.id, p.name,c.name,c.age from parent p LEFT JOIN child c on p.child_id = c.id
</code>```

if your child table contain parent_id then

```<code>SELECT p.id, p.name,c.name,c.age from parent p LEFT JOIN child c on p.id = c.parent_id
</code>```

in case a parent has multiple children then

```<code>select parent.name,(select group_concat(name,'|',age) from child where child.parent_id = parent.id) as child  from parent
</code>```

Body:
I have seen this asked before in different ways, but I'm hoping for a straight answer.

If I have two classes, Parent and Child, stored in two different MySQL tables, what is the best way of querying for a complete Parent object, with a list of all Children?

e.g.

class Parent {
   id: number;
   name: string;
   Children: Child[]
}

class Child {
   id: number;
   name: string;
   age: number;
}

How do I get a list of matching Parents by name, with a list of children for each?

Do I have to write a query to grab all matching Parents, and then an additional query for each Parent to get all the Child elements?

This is obviously pseudo-SQL, but I'm hoping for something like this:

SELECT p.id, p.name,
(SELECT * from c) as children from parent p LEFT JOIN child c on p.id = c.parent_id

Body:
If your parent table container child_id then

SELECT p.id, p.name,c.name,c.age from parent p LEFT JOIN child c on p.child_id = c.id

if your child table contain parent_id then

SELECT p.id, p.name,c.name,c.age from parent p LEFT JOIN child c on p.id = c.parent_id

in case a parent has multiple children then

select parent.name,(select group_concat(name,'|',age) from child where child.parent_id = parent.id) as child  from parent


问:
Programmatically uncheck checkboxcolumn in datagridview
How can I programmatically uncheck all rows in a DataGridViewCheckboxColumn in a datagridview?

I can get the correct value of the checkbox using

```<code>(bool)row.Cells[CheckBoxColumn.Index].FormattedValue
</code>```

but that's only a getter.

I have tried setting the value of the cell using

```<code>(bool)row.Cells[CheckBoxColumn.Index].value = false
</code>```

but that doesn't affect the FormattedValue.

How can I solve this?

答:
Haven't checked but you can try;

```<code>CheckBox cb = (row.Cells[CheckBoxColumn.Index].Controls[0] as CheckBox);
if(cb != null)
{
    cb.Checked = false;
}
</code>```

It's type may be different. Just debug and cast it to what it is.

ContentLicense: CC BY-SA 2.5

Body:
How can I programmatically uncheck all rows in a DataGridViewCheckboxColumn in a datagridview?

I can get the correct value of the checkbox using

(bool)row.Cells[CheckBoxColumn.Index].FormattedValue

but that's only a getter.

I have tried setting the value of the cell using

(bool)row.Cells[CheckBoxColumn.Index].value = false

but that doesn't affect the FormattedValue.

How can I solve this?

Body:
Haven't checked but you can try;

CheckBox cb = (row.Cells[CheckBoxColumn.Index].Controls[0] as CheckBox);
if(cb != null)
{
    cb.Checked = false;
}

It's type may be different. Just debug and cast it to what it is.


问:
How to sum two lists together?
I'm trying to do a sum of two list, for example:

1> example:sum([4,5], [6,7])
[10,12]
```

答:
The Built-In Function zipwith/3 in lists module can solve your problem

```<code>> lists:zipwith(fun(X, Y) -> X+Y end, [4, 5], [6, 7]).
 [10, 12]
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to sum two lists together?

Body:
The Built-In Function zipwith/3 in lists module can solve your problem

> lists:zipwith(fun(X, Y) -> X+Y end, [4, 5], [6, 7]).
 [10, 12]


问:
Using streams to find Max
Is the following the recommended way to attempt finding Max with streams?

```<code>List<Employee> emps = new ArrayList<>();
emps.add(new Employee("Roy1",32));
emps.add(new Employee("Roy2",12));
emps.add(new Employee("Roy3",22));
emps.add(new Employee("Roy4",42));
emps.add(new Employee("Roy5",52));

Integer maxSal= emps.stream().mapToInt(e -> e.getSalary()).reduce((a,b)->Math.max(a, b));
System.out.println("Max " + maxSal);
</code>```

It results in a compilation error - what does this mean?

```<code>error: incompatible types: OptionalInt cannot be
nverted to Integer
                  Integer maxSal= emps.stream().mapToInt(e -> e.getSalary()).
uce((a,b)->Math.max(a, b));
</code>```

答:
There is already a max method in IntStream. You don't have to reinvent the wheel:

```<code>OptionalInt maxSal = emps.stream().mapToInt(Employee::getSalary).max();
System.out.println("Max " + maxSal);
</code>```

max returns OptionalInt instead of Integer because there can be no elements in the list. You can use OptionalInt methods to extract the value from it:

```<code>maxSal.ifPresent(System.out::println);
</code>```

Or:

```<code>System.out.println(maxSal.orElse(0));
</code>```

Or:

```<code>System.out.println(maxSal.getAsInt());
</code>```

The latter one may throw an exception, so be careful.

Title: Using streams to find Max

Body:
Is the following the recommended way to attempt finding Max with streams?

List<Employee> emps = new ArrayList<>();
emps.add(new Employee("Roy1",32));
emps.add(new Employee("Roy2",12));
emps.add(new Employee("Roy3",22));
emps.add(new Employee("Roy4",42));
emps.add(new Employee("Roy5",52));

Integer maxSal= emps.stream().mapToInt(e -> e.getSalary()).reduce((a,b)->Math.max(a, b));
System.out.println("Max " + maxSal);

It results in a compilation error - what does this mean?

error: incompatible types: OptionalInt cannot be
nverted to Integer
                  Integer maxSal= emps.stream().mapToInt(e -> e.getSalary()).
uce((a,b)->Math.max(a, b));

Body:
There is already a max method in IntStream. You don't have to reinvent the wheel:

OptionalInt maxSal = emps.stream().mapToInt(Employee::getSalary).max();
System.out.println("Max " + maxSal);

max returns OptionalInt instead of Integer because there can be no elements in the list. You can use OptionalInt methods to extract the value from it:

maxSal.ifPresent(System.out::println);

Or:

System.out.println(maxSal.orElse(0));

Or:

System.out.println(maxSal.getAsInt());

The latter one may throw an exception, so be careful.


问:
Having trouble reformatting date
I have a dict that has a bunch of dates in European format (%d/%m/%Y).
I am trying to reformat the dates so that they are in US format (%m/%d/%Y).
Whenever I run it, the following error is identified:

```<code>ValueError: time data '2' does not match format '%m/%d/%Y'
</code>```

Anyone know what I need to correct?
Thanks for your help!

```<code>from datetime import datetime
import time
from time import mktime

Transaction_Date=[
"23/08/2017",
"23/08/2017",
"21/08/2017",
"01/10/2017",
"19/08/2017",
"19/08/2017",
"18/08/2017",
"03/09/2017",
"27/09/2017",
"26/08/2017",
"03/10/2017",
"27/09/2017",
"27/03/2017",
"02/08/2017",
"20/08/2017",
"20/08/2017",
"20/08/2017",
"20/08/2017",
"20/08/2017",
"20/08/2017"]

for row in Transaction_Date:
    Transaction_Date = row[0]
    Transaction_Date = datetime.strptime(Transaction_Date,'%d/%m/%Y').strftime('%m/%d/%Y')
    print(Transaction_Date)
</code>```

Gives the following error:

```<code>ValueError: time data '2' does not match format '%m/%d/%Y'
</code>```

From what I can tell, the dates format is correct, why is the system saying different?

答:
Your code has 2 mistakes:-

Using same name (Transition_Date) for both collection and your result,
you are using row[0] instead of row

```<code>from datetime import datetime
import time
from time import mktime

Transaction_Date_Collection = [ "23/08/2017", "23/08/2017", "21/08/2017", "01/10/2017", "19/08/2017", "19/08/2017", "18/08/2017", "03/09/2017", "27/09/2017", "26/08/2017", "03/10/2017", "27/09/2017", "27/03/2017", "02/08/2017", "20/08/2017", "20/08/2017", "20/08/2017", "20/08/2017", "20/08/2017", "20/08/2017"]

for Transaction_Date in Transaction_Date_Collection:
    Transaction_Date = datetime.strptime(Transaction_Date,'%d/%m/%Y').strftime('%m/%d/%Y')
    print(Transaction_Date)
</code>```

Title: Having trouble reformatting date

Body:
I have a dict that has a bunch of dates in European format (%d/%m/%Y).
I am trying to reformat the dates so that they are in US format (%m/%d/%Y).
Whenever I run it, the following error is identified:

ValueError: time data '2' does not match format '%m/%d/%Y'

Anyone know what I need to correct?
Thanks for your help!

from datetime import datetime
import time
from time import mktime

Transaction_Date=[
"23/08/2017",
"23/08/2017",
"21/08/2017",
"01/10/2017",
"19/08/2017",
"19/08/2017",
"18/08/2017",
"03/09/2017",
"27/09/2017",
"26/08/2017",
"03/10/2017",
"27/09/2017",
"27/03/2017",
"02/08/2017",
"20/08/2017",
"20/08/2017",
"20/08/2017",
"20/08/2017",
"20/08/2017",
"20/08/2017"]

for row in Transaction_Date:
    Transaction_Date = row[0]
    Transaction_Date = datetime.strptime(Transaction_Date,'%d/%m/%Y').strftime('%m/%d/%Y')
    print(Transaction_Date)

Gives the following error:

ValueError: time data '2' does not match format '%m/%d/%Y'

From what I can tell, the dates format is correct, why is the system saying different?

Body:
Your code has 2 mistakes:-

Using same name (Transition_Date) for both collection and your result,
you are using row[0] instead of row

from datetime import datetime
import time
from time import mktime

Transaction_Date_Collection = [ "23/08/2017", "23/08/2017", "21/08/2017", "01/10/2017", "19/08/2017", "19/08/2017", "18/08/2017", "03/09/2017", "27/09/2017", "26/08/2017", "03/10/2017", "27/09/2017", "27/03/2017", "02/08/2017", "20/08/2017", "20/08/2017", "20/08/2017", "20/08/2017", "20/08/2017", "20/08/2017"]

for Transaction_Date in Transaction_Date_Collection:
    Transaction_Date = datetime.strptime(Transaction_Date,'%d/%m/%Y').strftime('%m/%d/%Y')
    print(Transaction_Date)


问:
Dagger 2: Unable to find generated class in Intellij Idea (Kotlin)
I was trying to write a application to understand spark and dagger 2. But was unable to use generated dagger files.

There are multiple questions similar to this one, but I am not able to solve the problem using any of those.

My project can be found at github here

The build.gradle file looks like this

```<code>...
apply plugin: 'kotlin-kapt'
dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
    compile "com.sparkjava:spark-kotlin:$spark_kotlin_version"
    compile "org.slf4j:slf4j-log4j12:$slf4j_version"
    compile "com.google.dagger:dagger:$dagger_version"
    kapt "com.google.dagger:dagger-compiler:$dagger_version"

    testCompile group: 'junit', name: 'junit', version: '4.12'
}
....
</code>```

It's the SparkSetup.kt Class that I am trying to inject. Module and Component for this are present in co.pissarra.util.dagger package

The contents of SetupModule.kt looks like this

```<code>@Module
class SetUpModule {
    @Provides
    @Singleton
    fun provideSparkSetup() : SparkSetup {
        return SparkSetup()
    }
}
</code>```

And this is AppComponent.kt Class

```<code>@Singleton
@Component(modules = arrayOf(SetUpModule::class))
interface AppComponent {
    fun sparkSetup() : SparkSetup
}
</code>```

Ideally there should be a class by the name DaggerAppComponent, which infact is present in the build directory (both generated and classes). But this only works if I am not using DaggerAppComponent anywhere in the project. If I try using this, intellij idea gives the error that Unresolved reference: DaggerAppComponent and the project also fails to build.

I would like to change the file ContainerRunner.kt and instead of calling SparkSetup().init() directly, I would like to have that done through DI.

答:
This looks like KT-17923.
Please update your Kotlin IDE plugin version to 1.1.60 or 1.2-Beta.

Also, as a work-around, you can specify the generated directories manually:

```<code>apply plugin: 'idea'
idea {
    module {
        sourceDirs += file('build/generated/source/kapt/main')
        generatedSourceDirs += file('build/generated/source/kapt/main')
    }
}
</code>```

Note that you need to re-import project after adding this to your build.gradle.

The only thing that seems strange for me is that the error also reproduces during the build. Please check if DaggerAppComponent lays in the same package with the class that references it (or there is an import directive).

Body:
I was trying to write a application to understand spark and dagger 2. But was unable to use generated dagger files.

There are multiple questions similar to this one, but I am not able to solve the problem using any of those.

My project can be found at github here

The build.gradle file looks like this

...
apply plugin: 'kotlin-kapt'
dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
    compile "com.sparkjava:spark-kotlin:$spark_kotlin_version"
    compile "org.slf4j:slf4j-log4j12:$slf4j_version"
    compile "com.google.dagger:dagger:$dagger_version"
    kapt "com.google.dagger:dagger-compiler:$dagger_version"

    testCompile group: 'junit', name: 'junit', version: '4.12'
}
....

It's the SparkSetup.kt Class that I am trying to inject. Module and Component for this are present in co.pissarra.util.dagger package

The contents of SetupModule.kt looks like this

@Module
class SetUpModule {
    @Provides
    @Singleton
    fun provideSparkSetup() : SparkSetup {
        return SparkSetup()
    }
}

And this is AppComponent.kt Class

@Singleton
@Component(modules = arrayOf(SetUpModule::class))
interface AppComponent {
    fun sparkSetup() : SparkSetup
}

Ideally there should be a class by the name DaggerAppComponent, which infact is present in the build directory (both generated and classes). But this only works if I am not using DaggerAppComponent anywhere in the project. If I try using this, intellij idea gives the error that Unresolved reference: DaggerAppComponent and the project also fails to build.

I would like to change the file ContainerRunner.kt and instead of calling SparkSetup().init() directly, I would like to have that done through DI.

Body:
This looks like KT-17923.
Please update your Kotlin IDE plugin version to 1.1.60 or 1.2-Beta.

Also, as a work-around, you can specify the generated directories manually:

apply plugin: 'idea'
idea {
    module {
        sourceDirs += file('build/generated/source/kapt/main')
        generatedSourceDirs += file('build/generated/source/kapt/main')
    }
}

Note that you need to re-import project after adding this to your build.gradle.

The only thing that seems strange for me is that the error also reproduces during the build. Please check if DaggerAppComponent lays in the same package with the class that references it (or there is an import directive).


问:
Mysql Group_Concat function
Not understanding how to use the GROUP_CONCAT function as my queries seem to repeat values that I don't actually want.

I have three tables:

```<code>------------------
Content
------------------
cid | title
2334 | Lorem Ipsum

------------------
Organizers
------------------
cid | name | sort
2334 | John Doe | 0

------------------
Participants
------------------
cid | name | sort
2334 | Jane Doe | 0
2334 | Bob Hope | 1
2334 | Bart Simpson | 2
</code>```

I'm trying to write a query that will produce:

```<code>cid | title | organizers | participants
2334 | Lorem Ipsum | John Doe | Jane Doe, Bob Hope, Bart Simpson
</code>```

So, I'm trying to use GROUP_CONCAT.  But, values are being repeated, so I'm not sure how to output the results I'm looking for?

```<code>SELECT GROUP_CONCAT(co.name) as organizers,
GROUP_CONCAT(cp.name) FROM content n
LEFT JOIN organizers co ON n.cid = co.cid
LEFT JOIN participants cp ON n.cid = cp.cid
WHERE n.cid = 2334
</code>```

The above yields:

```<code>cid | title | organizers | participants
2334 | Lorem Ipsum | John Doe, John Doe, John Doe | Jane Doe, Bob Hope, Bart Simpson
</code>```

答:
```<code>SELECT n.cid, n.Title,
  GROUP_CONCAT(DISTINCT co.name ORDER BY co.sort) as organizers,
  GROUP_CONCAT(cp.name ORDER BY cp.sort)
FROM Content n
LEFT JOIN Organizers co ON n.cid = co.cid
LEFT JOIN Participants cp ON n.cid = cp.cid
GROUP BY n.cid
</code>```

Title: Mysql Group_Concat function

Body:
Not understanding how to use the GROUP_CONCAT function as my queries seem to repeat values that I don't actually want.

I have three tables:

------------------
Content
------------------
cid | title
2334 | Lorem Ipsum

------------------
Organizers
------------------
cid | name | sort
2334 | John Doe | 0

------------------
Participants
------------------
cid | name | sort
2334 | Jane Doe | 0
2334 | Bob Hope | 1
2334 | Bart Simpson | 2

I'm trying to write a query that will produce:

cid | title | organizers | participants
2334 | Lorem Ipsum | John Doe | Jane Doe, Bob Hope, Bart Simpson

So, I'm trying to use GROUP_CONCAT.  But, values are being repeated, so I'm not sure how to output the results I'm looking for?

SELECT GROUP_CONCAT(co.name) as organizers,
GROUP_CONCAT(cp.name) FROM content n
LEFT JOIN organizers co ON n.cid = co.cid
LEFT JOIN participants cp ON n.cid = cp.cid
WHERE n.cid = 2334

The above yields:

cid | title | organizers | participants
2334 | Lorem Ipsum | John Doe, John Doe, John Doe | Jane Doe, Bob Hope, Bart Simpson


问:
How to do two nested aggregations in elasticsearch?
City and home type are two nested objects in the following document mapping:

```<code>"mappings" : {
  "home_index_doc" : {
    "properties" : {
      "city" : {
        "type" : "nested",
        "properties" : {
          "country" : {
            "type" : "nested",
            "properties" : {
              "name" : {
                "type" : "text"
              }
            }
          },
          "name" : {
            "type" : "keyword"
          }
        }
      },
      "home_type" : {
        "type" : "nested",
        "properties" : {
          "name" : {
            "type" : "keyword"
          }
        }
      },
      ...
    }
  }
}
</code>```

I am trying to do the following aggregation:
Take all present documents and show all home_types per city.

I imagine it should look similar to:

```<code>"aggregations": {
  "all_cities": {
    "buckets": [
      {
        "key": "Tokyo",
         "doc_count": 12,
         "home_types": {
            "buckets": [
               {
                  "key": "apartment",
                  "doc_count": 5
               },
               {
                  "key": "house",
                  "doc_count": 12
               }
            ]
         }
      },
      {
        "key": "New York",
         "doc_count": 1,
         "home_types": {
            "buckets": [
               {
                  "key": "house",
                  "doc_count": 1
               }
            ]
         }
      }
    ]
  }
}
</code>```

After trying gazzilion aproaches and combinations, I've made it that far with Kibana:

```<code>GET home-index/home_index_doc/_search
{
  "size": 0,
  "aggs": {
    "all_cities": {
     "nested": {
         "path": "city"
      },
      "aggs": {
        "city_name": {
          "terms": {
            "field": "city.name"
          }
        }
      }
    },
    "aggs": {
      "all_home_types": {
        "nested": {
          "path": "home_type"
        },
        "aggs": {
          "home_type_name": {
            "terms": {
              "field": "home_type.name"
            }
          }
        }
      }
    }
  }
}
</code>```

and I get the following exception:

```<code>    "type": "unknown_named_object_exception",
    "reason": "Unknown BaseAggregationBuilder [all_home_types]",
</code>```

答:
You need to use reverse_nested in order to jump out of the city nested type back at the root level and do another nested aggregation for the home_type nested type. Basically, like this:

```<code>{
  "size": 0,
  "aggs": {
    "all_cities": {
      "nested": {
        "path": "city"
      },
      "aggs": {
        "city_name": {
          "terms": {
            "field": "city.name"
          },
          "aggs": {
            "by_home_types": {
              "reverse_nested": {},
              "aggs": {
                "all_home_types": {
                  "nested": {
                    "path": "home_type"
                  },
                  "aggs": {
                    "home_type_name": {
                      "terms": {
                        "field": "home_type.name"
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</code>```

Body:
City and home type are two nested objects in the following document mapping:

"mappings" : {
  "home_index_doc" : {
    "properties" : {
      "city" : {
        "type" : "nested",
        "properties" : {
          "country" : {
            "type" : "nested",
            "properties" : {
              "name" : {
                "type" : "text"
              }
            }
          },
          "name" : {
            "type" : "keyword"
          }
        }
      },
      "home_type" : {
        "type" : "nested",
        "properties" : {
          "name" : {
            "type" : "keyword"
          }
        }
      },
      ...
    }
  }
}

I am trying to do the following aggregation:
Take all present documents and show all home_types per city.

I imagine it should look similar to:

"aggregations": {
  "all_cities": {
    "buckets": [
      {
        "key": "Tokyo",
         "doc_count": 12,
         "home_types": {
            "buckets": [
               {
                  "key": "apartment",
                  "doc_count": 5
               },
               {
                  "key": "house",
                  "doc_count": 12
               }
            ]
         }
      },
      {
        "key": "New York",
         "doc_count": 1,
         "home_types": {
            "buckets": [
               {
                  "key": "house",
                  "doc_count": 1
               }
            ]
         }
      }
    ]
  }
}

After trying gazzilion aproaches and combinations, I've made it that far with Kibana:

GET home-index/home_index_doc/_search
{
  "size": 0,
  "aggs": {
    "all_cities": {
     "nested": {
         "path": "city"
      },
      "aggs": {
        "city_name": {
          "terms": {
            "field": "city.name"
          }
        }
      }
    },
    "aggs": {
      "all_home_types": {
        "nested": {
          "path": "home_type"
        },
        "aggs": {
          "home_type_name": {
            "terms": {
              "field": "home_type.name"
            }
          }
        }
      }
    }
  }
}

and I get the following exception:

    "type": "unknown_named_object_exception",
    "reason": "Unknown BaseAggregationBuilder [all_home_types]",

Body:
You need to use reverse_nested in order to jump out of the city nested type back at the root level and do another nested aggregation for the home_type nested type. Basically, like this:

{
  "size": 0,
  "aggs": {
    "all_cities": {
      "nested": {
        "path": "city"
      },
      "aggs": {
        "city_name": {
          "terms": {
            "field": "city.name"
          },
          "aggs": {
            "by_home_types": {
              "reverse_nested": {},
              "aggs": {
                "all_home_types": {
                  "nested": {
                    "path": "home_type"
                  },
                  "aggs": {
                    "home_type_name": {
                      "terms": {
                        "field": "home_type.name"
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}


问:
Plot Sum of column by values in other columns
I have a dataframe like the sample data below.  I would like to create a plot showing the sum of the "Correct" column by each of the other 4 columns, when those columns have value 1.  The columns are dummy variables, so a 1 in the "Chinese" column indicates that record was flagged as Chinese.  So I'd like to create a bar plot showing sum of "Correct" for each dummy variable.

Sample Data:

```<code>           Food  Chinese  Italian  Food Stands    \
176          1     0        0        0
148          0     0        0        0
143          0     1        0        0
45           0     1        0        0

     Correct
176        0
148        1
143        0
45         1
</code>```

答:
Here is a working example, it uses mask to only create column sums from rows where Correct=1

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

df = pd.DataFrame()
df['Chinese'] = [0,1,1,1,0,0,1]
df['Italian'] = [1,0,0,0,1,1,0]
df['Correct'] = [1,1,0,1,1,0,0]

df.mask(df['Correct'].apply(lambda x: bool(x)), inplace=True)
df[['Italian','Chinese']].sum().plot.bar()

plt.show()
</code>```

Body:
I have a dataframe like the sample data below.  I would like to create a plot showing the sum of the "Correct" column by each of the other 4 columns, when those columns have value 1.  The columns are dummy variables, so a 1 in the "Chinese" column indicates that record was flagged as Chinese.  So I'd like to create a bar plot showing sum of "Correct" for each dummy variable.

Sample Data:

           Food  Chinese  Italian  Food Stands    \
176          1     0        0        0
148          0     0        0        0
143          0     1        0        0
45           0     1        0        0

     Correct
176        0
148        1
143        0
45         1

Body:
Here is a working example, it uses mask to only create column sums from rows where Correct=1

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame()
df['Chinese'] = [0,1,1,1,0,0,1]
df['Italian'] = [1,0,0,0,1,1,0]
df['Correct'] = [1,1,0,1,1,0,0]

df.mask(df['Correct'].apply(lambda x: bool(x)), inplace=True)
df[['Italian','Chinese']].sum().plot.bar()

plt.show()


答:
Answering to your question the problem is that reduce method is going to return an OptionalInt so you need to call the .getAsInt() method if you want to have the Integer value.

```<code>    Integer maxSal = emps.stream().mapToInt(e -> e.getSalary())
         .reduce((a,b)->Math.max(a, b)).getAsInt();
</code>```

In case there is no maximum on the list you will get a NoSuchElementException that you need to deal with.

Title: Using streams to find Max

Body:
Answering to your question the problem is that reduce method is going to return an OptionalInt so you need to call the .getAsInt() method if you want to have the Integer value.

    Integer maxSal = emps.stream().mapToInt(e -> e.getSalary())
         .reduce((a,b)->Math.max(a, b)).getAsInt();

In case there is no maximum on the list you will get a NoSuchElementException that you need to deal with.


问:
Visual studio 2017 "Unable to connect to web server 'IIS Express'"
If I attempt to launch my .net core app I get this message. I realize there are many posts out there claiming to fix this but I have tried every method they suggest and none are working.

If I go into the project properties under debug and change the port, then it will connect 1 time. Then if I attempt to connect again, it will give me the same error again. I can then switch the port back to the original and it will load one time, then it will fail any time beyond that, until I switch it again. Anyone have any ideas or fixes they used?

Thanks!

答:
I installed core 2.0 and updated VS 2017 to 15.4.3 today, had the same error.

I ended up changing the application to run on a different port, it worked for me.

I have tried to delete the vs folder but did not work.

Hope it helps.


问:
Clojure: create a list of values extracted from record
I have a data structure of type "clojure.data.xml.Element" that looks like this (pretty printed):

```<code>{:tag :eSearchResult,
 :attrs {},
 :content
 ({:tag :Count, :attrs {}, :content ("16")}
  {:tag :RetMax, :attrs {}, :content ("16")}
  {:tag :RetStart, :attrs {}, :content ("0")}
  {:tag :IdList,
   :attrs {},
   :content
   ({:tag :Id, :attrs {}, :content ("28911150")}
    {:tag :Id, :attrs {}, :content ("28899394")}
    {:tag :Id, :attrs {}, :content ("28597238")}
    {:tag :Id, :attrs {}, :content ("28263281")}
    {:tag :Id, :attrs {}, :content ("28125459")}
    {:tag :Id, :attrs {}, :content ("26911135")}
    {:tag :Id, :attrs {}, :content ("26699345")}
    {:tag :Id, :attrs {}, :content ("26297102")}
    {:tag :Id, :attrs {}, :content ("26004019")}
    {:tag :Id, :attrs {}, :content ("25995331")}
    {:tag :Id, :attrs {}, :content ("25429093")}
    {:tag :Id, :attrs {}, :content ("25355095")}
    {:tag :Id, :attrs {}, :content ("25224593")}
    {:tag :Id, :attrs {}, :content ("24816246")}
    {:tag :Id, :attrs {}, :content ("24779721")}
    {:tag :Id, :attrs {}, :content ("24740865")})}
</code>```

How do I extract the Ids from these records? In other words create a function that takes this data structure and returns a list of Id strings ("28911150" "28899394" ...)?

Thanks.

答:
In addition to specter, you could also use the tupelo.forest library:

```<code>(dotest
  (with-forest (new-forest)
    (let [root-hid   (add-tree-enlive
                       {:tag     :eSearchResult,
                        :attrs   {},
                        :content [
                            {:tag :Count, :attrs {}, :content ["16"]}
                            {:tag :RetMax, :attrs {}, :content ["16"]}
                            {:tag :RetStart, :attrs {}, :content ["0"]}
                            {:tag     :IdList,
                             :attrs   {},
                             :content [
                                 {:tag :Id, :attrs {}, :content ["28911150"]}
                                 {:tag :Id, :attrs {}, :content ["28899394"]}
                                 {:tag :Id, :attrs {}, :content ["28597238"]}
                                 {:tag :Id, :attrs {}, :content ["28263281"]}
                                 {:tag :Id, :attrs {}, :content ["28125459"]}
                                 {:tag :Id, :attrs {}, :content ["26911135"]}
                                 {:tag :Id, :attrs {}, :content ["26699345"]}
                                 {:tag :Id, :attrs {}, :content ["26297102"]}
                                 {:tag :Id, :attrs {}, :content ["26004019"]}
                                 {:tag :Id, :attrs {}, :content ["25995331"]}
                                 {:tag :Id, :attrs {}, :content ["25429093"]}
                                 {:tag :Id, :attrs {}, :content ["25355095"]}
                                 {:tag :Id, :attrs {}, :content ["25224593"]}
                                 {:tag :Id, :attrs {}, :content ["24816246"]}
                                 {:tag :Id, :attrs {}, :content ["24779721"]}
                                 {:tag :Id, :attrs {}, :content ["24740865"]} ]}]})
</code>```

We can find the path from root to each Id element, and then extrace the ID string with just 2 lines:

```<code>          id-content-paths (find-paths root-hid [:eSearchResult :IdList :Id])
          id-strings       (forv [path id-content-paths]
                             (grab :value (hid->leaf (last path))))]
</code>```

The hid->bush function prints a Hiccup-like representation of the data tree:

```<code>  (is= (hid->bush root-hid)
        [{:tag :eSearchResult}
         [{:tag :Count, :value "16"}]
         [{:tag :RetMax, :value "16"}]
         [{:tag :RetStart, :value "0"}]
         [{:tag :IdList}
          [{:tag :Id, :value "28911150"}]
          [{:tag :Id, :value "28899394"}]
          [{:tag :Id, :value "28597238"}]
          [{:tag :Id, :value "28263281"}]
          [{:tag :Id, :value "28125459"}]
          [{:tag :Id, :value "26911135"}]
          [{:tag :Id, :value "26699345"}]
          [{:tag :Id, :value "26297102"}]
          [{:tag :Id, :value "26004019"}]
          [{:tag :Id, :value "25995331"}]
          [{:tag :Id, :value "25429093"}]
          [{:tag :Id, :value "25355095"}]
          [{:tag :Id, :value "25224593"}]
          [{:tag :Id, :value "24816246"}]
          [{:tag :Id, :value "24779721"}]
          [{:tag :Id, :value "24740865"}]]])
</code>```

This unit test shows the desired results:

```<code>  (is= id-strings
        ["28911150"
         "28899394"
         "28597238"
         "28263281"
         "28125459"
         "26911135"
         "26699345"
         "26297102"
         "26004019"
         "25995331"
         "25429093"
         "25355095"
         "25224593"
         "24816246"
         "24779721"
         "24740865"])
      )))
</code>```

Body:
I have a data structure of type "clojure.data.xml.Element" that looks like this (pretty printed):

{:tag :eSearchResult,
 :attrs {},
 :content
 ({:tag :Count, :attrs {}, :content ("16")}
  {:tag :RetMax, :attrs {}, :content ("16")}
  {:tag :RetStart, :attrs {}, :content ("0")}
  {:tag :IdList,
   :attrs {},
   :content
   ({:tag :Id, :attrs {}, :content ("28911150")}
    {:tag :Id, :attrs {}, :content ("28899394")}
    {:tag :Id, :attrs {}, :content ("28597238")}
    {:tag :Id, :attrs {}, :content ("28263281")}
    {:tag :Id, :attrs {}, :content ("28125459")}
    {:tag :Id, :attrs {}, :content ("26911135")}
    {:tag :Id, :attrs {}, :content ("26699345")}
    {:tag :Id, :attrs {}, :content ("26297102")}
    {:tag :Id, :attrs {}, :content ("26004019")}
    {:tag :Id, :attrs {}, :content ("25995331")}
    {:tag :Id, :attrs {}, :content ("25429093")}
    {:tag :Id, :attrs {}, :content ("25355095")}
    {:tag :Id, :attrs {}, :content ("25224593")}
    {:tag :Id, :attrs {}, :content ("24816246")}
    {:tag :Id, :attrs {}, :content ("24779721")}
    {:tag :Id, :attrs {}, :content ("24740865")})}

How do I extract the Ids from these records? In other words create a function that takes this data structure and returns a list of Id strings ("28911150" "28899394" ...)?

Thanks.

Body:
In addition to specter, you could also use the tupelo.forest library:

(dotest
  (with-forest (new-forest)
    (let [root-hid   (add-tree-enlive
                       {:tag     :eSearchResult,
                        :attrs   {},
                        :content [
                            {:tag :Count, :attrs {}, :content ["16"]}
                            {:tag :RetMax, :attrs {}, :content ["16"]}
                            {:tag :RetStart, :attrs {}, :content ["0"]}
                            {:tag     :IdList,
                             :attrs   {},
                             :content [
                                 {:tag :Id, :attrs {}, :content ["28911150"]}
                                 {:tag :Id, :attrs {}, :content ["28899394"]}
                                 {:tag :Id, :attrs {}, :content ["28597238"]}
                                 {:tag :Id, :attrs {}, :content ["28263281"]}
                                 {:tag :Id, :attrs {}, :content ["28125459"]}
                                 {:tag :Id, :attrs {}, :content ["26911135"]}
                                 {:tag :Id, :attrs {}, :content ["26699345"]}
                                 {:tag :Id, :attrs {}, :content ["26297102"]}
                                 {:tag :Id, :attrs {}, :content ["26004019"]}
                                 {:tag :Id, :attrs {}, :content ["25995331"]}
                                 {:tag :Id, :attrs {}, :content ["25429093"]}
                                 {:tag :Id, :attrs {}, :content ["25355095"]}
                                 {:tag :Id, :attrs {}, :content ["25224593"]}
                                 {:tag :Id, :attrs {}, :content ["24816246"]}
                                 {:tag :Id, :attrs {}, :content ["24779721"]}
                                 {:tag :Id, :attrs {}, :content ["24740865"]} ]}]})

We can find the path from root to each Id element, and then extrace the ID string with just 2 lines:

          id-content-paths (find-paths root-hid [:eSearchResult :IdList :Id])
          id-strings       (forv [path id-content-paths]
                             (grab :value (hid->leaf (last path))))]

The hid->bush function prints a Hiccup-like representation of the data tree:

  (is= (hid->bush root-hid)
        [{:tag :eSearchResult}
         [{:tag :Count, :value "16"}]
         [{:tag :RetMax, :value "16"}]
         [{:tag :RetStart, :value "0"}]
         [{:tag :IdList}
          [{:tag :Id, :value "28911150"}]
          [{:tag :Id, :value "28899394"}]
          [{:tag :Id, :value "28597238"}]
          [{:tag :Id, :value "28263281"}]
          [{:tag :Id, :value "28125459"}]
          [{:tag :Id, :value "26911135"}]
          [{:tag :Id, :value "26699345"}]
          [{:tag :Id, :value "26297102"}]
          [{:tag :Id, :value "26004019"}]
          [{:tag :Id, :value "25995331"}]
          [{:tag :Id, :value "25429093"}]
          [{:tag :Id, :value "25355095"}]
          [{:tag :Id, :value "25224593"}]
          [{:tag :Id, :value "24816246"}]
          [{:tag :Id, :value "24779721"}]
          [{:tag :Id, :value "24740865"}]]])

This unit test shows the desired results:

  (is= id-strings
        ["28911150"
         "28899394"
         "28597238"
         "28263281"
         "28125459"
         "26911135"
         "26699345"
         "26297102"
         "26004019"
         "25995331"
         "25429093"
         "25355095"
         "25224593"
         "24816246"
         "24779721"
         "24740865"])
      )))


问:
Order by custom field value not working for acf date field
I have custom post type event which has custom field event_date. The date format for this field is set to Ymd.

I'm trying to get posts in order of event_date

Here is the code to pull the posts in that order

```<code>$today = date('Ymd');

$args = array (
    'post_type'             => array( 'event' ),
    'posts_per_page'        => '-1',
    'order'                 => 'ASC',
    'orderby'              =>'meta_value', // also tried having meta_value_num but that didn't worked as well
    'meta_key'              =>'event_date',
    'meta_query' => array(
        array(
            'key'       => 'event_date',
            'compare'   => '>=',
            'value'     => $today,
        )
    ),
    'suppress_filters' => true
);
/*
global $wp_filter;
var_dump( $wp_filter['posts_orderby'] );die;
This returns NULL as well
*/

    $query = new WP_Query( $args );
    echo '```';
    var_dump($query->request);die;
```

<p>But the $query->request shows the ORDER BY as post_date rahter than my supplied query.
Here is the dump of request</p>

```string(681) "SELECT   wp_posts.* FROM wp_posts  INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )  INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) WHERE 1=1  AND (
  wp_posts.ID NOT IN (
                SELECT object_id
                FROM wp_term_relationships
                WHERE term_taxonomy_id IN (11)
            )
) AND (
  wp_postmeta.meta_key = 'event_date'
  AND
  (
    ( mt1.meta_key = 'event_date' AND mt1.meta_value >= '20171113' )
  )
) AND wp_posts.post_type = 'event' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date ASC "
```

<p>can't order by the event_date.
What am i doing wrong??
Even tried by having</p>

```remove_all_filters('posts_orderby');
```

before the wp_query still same result.

FINALLY: Thanks everyone for your kind responses, finnally solved by just changing the order_by to orderby in my query.
Thanks @Prasanna Venkatesh  for letting me check in phpmyadmin. Ran the code in phpmyadmin and fixed it. PS: the sql query was correct except the order_by.

答:
You're missing 'type' => 'DATE' to meta query.

```<code>$args = array (
    'post_type'             => array( 'event' ),
    'posts_per_page'        => '-1',
    'order'                 => 'ASC',
    'orderby'              =>'meta_value', // also tried having meta_value_num but that didn't worked as well
    'meta_key'              =>'event_date',
    'meta_query' => array(
        array(
            'key'       => 'event_date',
            'compare'   => '>=',
            'value'     => $today,
            'type'      => 'DATE'
        )
    ),
    'suppress_filters' => true
);
</code>```

Body:
I have custom post type event which has custom field event_date. The date format for this field is set to Ymd.

I'm trying to get posts in order of event_date

Here is the code to pull the posts in that order

$today = date('Ymd');

$args = array (
    'post_type'             => array( 'event' ),
    'posts_per_page'        => '-1',
    'order'                 => 'ASC',
    'orderby'              =>'meta_value', // also tried having meta_value_num but that didn't worked as well
    'meta_key'              =>'event_date',
    'meta_query' => array(
        array(
            'key'       => 'event_date',
            'compare'   => '>=',
            'value'     => $today,
        )
    ),
    'suppress_filters' => true
);
/*
global $wp_filter;
var_dump( $wp_filter['posts_orderby'] );die;
This returns NULL as well
*/

    $query = new WP_Query( $args );
    echo '
';
    var_dump($query->request);die;

But the $query->request shows the ORDER BY as post_date rahter than my supplied query.
Here is the dump of request

string(681) "SELECT   wp_posts.* FROM wp_posts  INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )  INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) WHERE 1=1  AND (
  wp_posts.ID NOT IN (
                SELECT object_id
                FROM wp_term_relationships
                WHERE term_taxonomy_id IN (11)
            )
) AND (
  wp_postmeta.meta_key = 'event_date'
  AND
  (
    ( mt1.meta_key = 'event_date' AND mt1.meta_value >= '20171113' )
  )
) AND wp_posts.post_type = 'event' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date ASC "

can't order by the event_date.
What am i doing wrong??
Even tried by having

remove_all_filters('posts_orderby');

before the wp_query still same result.

FINALLY: Thanks everyone for your kind responses, finnally solved by just changing the order_by to orderby in my query.
Thanks @Prasanna Venkatesh  for letting me check in phpmyadmin. Ran the code in phpmyadmin and fixed it. PS: the sql query was correct except the order_by.

Body:
You're missing 'type' => 'DATE' to meta query.

$args = array (
    'post_type'             => array( 'event' ),
    'posts_per_page'        => '-1',
    'order'                 => 'ASC',
    'orderby'              =>'meta_value', // also tried having meta_value_num but that didn't worked as well
    'meta_key'              =>'event_date',
    'meta_query' => array(
        array(
            'key'       => 'event_date',
            'compare'   => '>=',
            'value'     => $today,
            'type'      => 'DATE'
        )
    ),
    'suppress_filters' => true
);


问:
Why HTML/CSS Dropdown Menu links not clicking thru on 1st click, only 2nd+ click works?
Strangely, all of the links in a HTML/CSS/JS dropdown menu (top right with parent menu items "Home" "Shop" "Create" as shown in example image), do not click-thru to their href= destinations on the 1st click.  Clicking 1 time does nothing.  Wait a few seconds to verify nothing happens, then click again - works browser follows the link to the destination on the 2nd click fine.

I am testing in Google Chrome.

This is the only menu or set of links having this issue in the entire site...

I've already right-clicked on them to inspect-element with the developer panel in Chrome, expecting to find some other element blocking it or something but it's not the case, the target seems clickable and the hover states work fine and everything.

View example here:  http://www.PuckStyle.com

Thank you!

Update:

Here is a screenshot as requested-

(source: puckstyle.com)

答:
I managed to find something using the Chrome dev tools checking for events.

If I remove that click event (1) then I can single click the link in the menu.

When I click the link to the script (2), the code block (3) is highlighted.

Looks like a script to double-tap. You could remove it from your site. Double-taping in your website is probably not needed.


问:
SQL Query Error SQL Syntax
here I have some problem during make database on mysql :

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'use android_api

create table users(    id int(11) primary key auto_increme' at line 3

here my code :

```<code>create database android_api /** Creating Database **/

use android_api /** Selecting Database **/

create table users(
   id int(11) primary key auto_increment,
   unique_id varchar(23) not null unique,
   name varchar(50) not null,
   email varchar(100) not null unique,
   encrypted_password varchar(80) not null,
   salt varchar(10) not null,
   created_at datetime,
   updated_at datetime null
); /** Creating Users Table **/
</code>```

looking forward for your help. thanks

答:
Already some people answer you question, with add on this:

Semicolon ';'indicates end of a statement, so if there are multiple
  statements then you should use semicolon else it will work fine.

So it is good practice to use whether it is single statement or multiple statements

```<code>create database android_api; /** Creating Database **/

use android_api; /** Selecting Database **/

create table users(

); /** Creating Users Table **/
</code>```

Title: SQL Query Error SQL Syntax

Body:
here I have some problem during make database on mysql :

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'use android_api

create table users(    id int(11) primary key auto_increme' at line 3

here my code :

create database android_api /** Creating Database **/

use android_api /** Selecting Database **/

create table users(
   id int(11) primary key auto_increment,
   unique_id varchar(23) not null unique,
   name varchar(50) not null,
   email varchar(100) not null unique,
   encrypted_password varchar(80) not null,
   salt varchar(10) not null,
   created_at datetime,
   updated_at datetime null
); /** Creating Users Table **/

looking forward for your help. thanks

Body:
Already some people answer you question, with add on this:

Semicolon ';'indicates end of a statement, so if there are multiple
  statements then you should use semicolon else it will work fine.

So it is good practice to use whether it is single statement or multiple statements

create database android_api; /** Creating Database **/

use android_api; /** Selecting Database **/

create table users(

); /** Creating Users Table **/


问:
Destroy PHP Session on closing
I have created a simple login page which is based on the sessions.

```<code>session_start();
</code>```

and added a logout page that contains this

```<code>session_destroy();
</code>```

Now when I close the browser/page and reopen it, the values of the session are still there.

I want to know how to completely destroy the session on page/browser close.

答:
Server can't detect browser or tab closed, you could use Javascript or Ajax but sorry I don't have knowledge about that.

My suggestion is use Session Timeout, so session will be destroyed if there's no action from user. This is an example :

```<code>// destroy every 2 minutes

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 120)) {
    // last request was more than 2 minutes ago
    session_destroy();   // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp

// end of code
</code>```

Hope this help you

Title: Destroy PHP Session on closing

Body:
I have created a simple login page which is based on the sessions.

session_start();

and added a logout page that contains this

session_destroy();

Now when I close the browser/page and reopen it, the values of the session are still there.

I want to know how to completely destroy the session on page/browser close.

Body:
Server can't detect browser or tab closed, you could use Javascript or Ajax but sorry I don't have knowledge about that.

My suggestion is use Session Timeout, so session will be destroyed if there's no action from user. This is an example :

// destroy every 2 minutes

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 120)) {
    // last request was more than 2 minutes ago
    session_destroy();   // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp

// end of code

Hope this help you


问:
How to redirect through 'POST' method using Javascript?
I've queried and doesn't work out what I've found. Is there any way to redirect to give url with POST method using Javascript or jquery?

答:
Redirect with POST vars (on jQuery)</p>

```<code>var redirect = 'http://www.website.com/page?id=23231';
$.redirectPost(redirect, {x: 'example', y: 'abc'});

$.extend(
{
    redirectPost: function(location, args)
    {
        var form = '';
        $.each( args, function( key, value ) {
            form += '<input type="hidden" name="'+key+'" value="'+value+'">';
        });
        $('<form action="'+location+'" method="POST">'+form+'</form>').submit();
    }
});
</code>```

Body:
Redirect with POST vars (on jQuery)

var redirect = 'http://www.website.com/page?id=23231';
$.redirectPost(redirect, {x: 'example', y: 'abc'});

$.extend(
{
    redirectPost: function(location, args)
    {
        var form = '';
        $.each( args, function( key, value ) {
            form += '<input type="hidden" name="'+key+'" value="'+value+'">';
        });
        $('<form action="'+location+'" method="POST">'+form+'</form>').submit();
    }
});


问:
How to use SSH and SUDO together with TRAMP in Emacs

Possible Duplicate:

  Open file via SSH and Sudo with Emacs

I want to open a file using sudo (say, /etc/hosts) on a remote machine connected by ssh using TRAMP on Emacs.

I tried couple of options, but none of them worked. Can anybody tell me how to go about it?

Thank you

答:
Use following in your .emacs

```<code>(set-default 'tramp-default-proxies-alist (quote ((".*" "\\`root\\'" "/ssh:%h:"))))
</code>```

Then you can simply type:

```<code>C-x C-f /sudo:root@host[#port]:/path/to/file
</code>```

It will ask you for your password  to access remote shell and then your password again for sudo access.

Body:
Use following in your .emacs

(set-default 'tramp-default-proxies-alist (quote ((".*" "\\`root\\'" "/ssh:%h:"))))

Then you can simply type:

C-x C-f /sudo:root@host[#port]:/path/to/file

It will ask you for your password  to access remote shell and then your password again for sudo access.


问:
Combined templete not showing full results laravel
I am having some trouble combining 2 templates together where I want the popup button to be shown together with user information. When I try doing it, it only show a few information inside instead of all. Why is that?

Background information: I am trying to make a page where it shows user information and also a button where when the user click it, they can submit some details inside. But for some reason when I combine them together it is either the form only show a bit of info with no button or show even lesser info but with button.

Here is the code for the popup button:

evaltest.blade.php (I want the information from test.blade.php to be shown here but right now only a few information is being shown)

```<code>    <html>
    <head>
        <title>Popup form </title>
        <meta name="robots" content="noindex, nofollow">
        <link href="{{ asset('css/elements.css') }}" rel="stylesheet">
        <script type="text/javascript">
        var _gaq = _gaq || [];
        _gaq.push(['_setAccount', 'UA-43981329-1']);
        _gaq.push(['_trackPageview']);
        (function () {
        var ga = document.createElement('script');
        ga.type = 'text/javascript';
        ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(ga, s);
        })();
    </script>
    </head>
     <!-- body starts here -->
     <body id ="bdy" style="overflow:hidden;">

     <div id="abc">

         <!-- Popup div starts here -->
     <div id="popupContact">

        <!-- contact us form -->
             <form class="form-horizontal" method="post" action="{{ url('/evaltest/'.$data0->id) }}">
            {{ csrf_field() }}
            <img id ="close" src="{{ URL::to('/image') }}/3.png" onclick ="div_hide()">
             <input type="hidden" name="user_id" value="{{$data0->id}}">

         <div class="form-group">
            <label class="col-md-2"><b>Recommendation:</b></label>
          <div class="col-md-6">
            <input type="radio" id ="recommendation" name="recommendation" value="Yes"> Yes<br>
            <input type="radio" id ="recommendation" name="recommendation" value="No"> No<br>
          </div>
      </div>
            <div class="form-group">
                <div class="col-md-6-offset-2">
                  <input id= "submit" type="submit" href="javascript: check_empty()" class="btn btn-primary" value="Save">
                </div>
              </div>
            </form>
     </div>
    <!-- Popup Div Ends Here -->
    </div>
    <!-- Display Popup Button -->
//this will show a few info but no button
@include('test')
    <h1>Click Button to Evaluate</h1>
    <button id="popup" onclick="div_show()">Popup</button>
        <script src="{{ asset('/js/my_js.js') }}"></script>
//this will show even lesser info but button is shown
//@include('test')
    </body>
    </html>
</code>```

test.blade.php (there are more information inside but I only put some as an example of how I got the information)

```<code>@foreach ($data as $object)
    <b>Name: </b>{{ $object->Name }}<br><br>
    <b>Alias: </b>{{ $object->Alias }}<br><br>
    <b>Email: </b>{{$object->Email}}<br><br>
@endforeach
</code>```

答:
You should pass $data variable where you call @include. For example @include('test',[$data]).

Hope this helps :)

Body:
I am having some trouble combining 2 templates together where I want the popup button to be shown together with user information. When I try doing it, it only show a few information inside instead of all. Why is that?

Background information: I am trying to make a page where it shows user information and also a button where when the user click it, they can submit some details inside. But for some reason when I combine them together it is either the form only show a bit of info with no button or show even lesser info but with button.

Here is the code for the popup button:

evaltest.blade.php (I want the information from test.blade.php to be shown here but right now only a few information is being shown)

        <title>Popup form </title>
        <meta name="robots" content="noindex, nofollow">
        <link href="{{ asset('css/elements.css') }}" rel="stylesheet">

             <form class="form-horizontal" method="post" action="{{ url('/evaltest/'.$data0->id) }}">
            {{ csrf_field() }}

             <input type="hidden" name="user_id" value="{{$data0->id}}">

            Recommendation:

            <input type="radio" id ="recommendation" name="recommendation" value="Yes"> Yes

            <input type="radio" id ="recommendation" name="recommendation" value="No"> No

                  <input id= "submit" type="submit" href="javascript: check_empty()" class="btn btn-primary" value="Save">

            </form>

//this will show a few info but no button
@include('test')

Click Button to Evaluate

    <button id="popup" onclick="div_show()">Popup</button>

//this will show even lesser info but button is shown
//@include('test')

test.blade.php (there are more information inside but I only put some as an example of how I got the information)

@foreach ($data as $object)
    Name: {{ $object->Name }}

    Alias: {{ $object->Alias }}

    Email: {{$object->Email}}

@endforeach


问:
ActivatedRoute.routeConfig is null - Angular 2 project with Angular-cli
I have created 2 different projects using angular-cli. Both work perfectly but in one of them routeConfig is null and have no idea what's wrong.

The package.json of both file are the same so there's no any doubt about packages versions, app.modules files are the same as well.

Here is how I get routeConfig in both projects :

```<code>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  constructor(
    private router: ActivatedRoute
  ) { }

  ngOnInit(): void {
    console.log(this.router.routeConfig);
  }
}
</code>```

what's wrong with my implementation?

答:
After some struggles and looking around my code, I found the major difference between the two apps, which it was in the template part.

When works :home.component.html

```<code><div class="container bg">
  <div class="row">
    <div class="col-lg-3">
      <div class="sidebar">
        <app-sidebar></app-sidebar>
      </div>
    </div>
    <div class="col-lg-9">
      <div class="content-bar">
        <!-- Body -->
        <p>
          home works!
        </p>
        <!-- /body -->
      </div>
    </div>
  </div>
</div>
</code>```

When doesn't work : app.component.html

```<code><div class="container bg">
  <div class="row">
    <div class="col-lg-3">
      <div class="sidebar">
        <!-- <app-sidebar></app-sidebar> -->
      </div>
    </div>
    <div class="col-lg-9">
      <div class="content-bar">
        <!-- Body -->
        <router-outlet></router-outlet>
        <!-- /body -->
      </div>
    </div>
  </div>
</div>
</code>```

It should be noted that ActivatedRoute was NULL inside sidebar.component.ts.

If the answer is not clear enough, feel free to mention in comments, I will update it.

Update: As @alterfox's request the following explanation has been provided :

When I call <app-sidebar> in the same xxx.component.html as  <router-outlet> is called, routeConfig doesn't get any value, so I changed my code as mentioned and moved <app-sidebar> to a level deeper inside home.component.html which means I had to call it in every xxx.component.html

Body:
I have created 2 different projects using angular-cli. Both work perfectly but in one of them routeConfig is null and have no idea what's wrong.

The package.json of both file are the same so there's no any doubt about packages versions, app.modules files are the same as well.

Here is how I get routeConfig in both projects :

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  constructor(
    private router: ActivatedRoute
  ) { }

  ngOnInit(): void {
    console.log(this.router.routeConfig);
  }
}

what's wrong with my implementation?

Body:
After some struggles and looking around my code, I found the major difference between the two apps, which it was in the template part.

When works :home.component.html

<div class="container bg">
  <div class="row">
    <div class="col-lg-3">
      <div class="sidebar">
        <app-sidebar></app-sidebar>
      </div>
    </div>
    <div class="col-lg-9">
      <div class="content-bar">
        <!-- Body -->
        <p>
          home works!
        </p>
        <!-- /body -->
      </div>
    </div>
  </div>
</div>

When doesn't work : app.component.html

<div class="container bg">
  <div class="row">
    <div class="col-lg-3">
      <div class="sidebar">
        <!-- <app-sidebar></app-sidebar> -->
      </div>
    </div>
    <div class="col-lg-9">
      <div class="content-bar">
        <!-- Body -->
        <router-outlet></router-outlet>
        <!-- /body -->
      </div>
    </div>
  </div>
</div>

It should be noted that ActivatedRoute was NULL inside sidebar.component.ts.

If the answer is not clear enough, feel free to mention in comments, I will update it.

Update: As @alterfox's request the following explanation has been provided :

When I call <app-sidebar> in the same xxx.component.html as  <router-outlet> is called, routeConfig doesn't get any value, so I changed my code as mentioned and moved <app-sidebar> to a level deeper inside home.component.html which means I had to call it in every xxx.component.html


问:
How to deploy SNAPSHOT with sources and JavaDoc?
I want to deploy sources and javadocs with my snapshots. This means that I want to automize the following command:

```<code>mvn clean source:jar javadoc:jar deploy
</code>```

Just to execute:

```<code>mvn clean deploy
</code>```

I don't want to have javadoc/sources generation executed during the install phase (i.e. local builds).

I know that source/javadoc plugins can be synchronized with the execution of the release plugin but I can't figure out how to wire it to the snapshots releases.

答:
<build>
  <plugins>
    <plugin>
      <artifactId>maven-source-plugin</artifactId>
      <executions>
        <execution>
          <id>attach-sources</id>
          <phase>deploy</phase>
          <goals><goal>jar-no-fork</goal></goals>
        </execution>
      </executions>
    </plugin>
    <plugin>
      <artifactId>maven-javadoc-plugin</artifactId>
      <executions>
        <execution>
          <id>attach-javadocs</id>
          <phase>deploy</phase>
          <goals><goal>jar</goal></goals>
        </execution>
      </executions>
    </plugin>
    <plugin>

      <artifactId>maven-deploy-plugin</artifactId>
      <executions>
        <execution>
          <id>deploy</id>
          <phase>deploy</phase>
          <goals><goal>deploy</goal></goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>
```

See Sonatype's OSS parent POM for a complete example.

Body:
I want to deploy sources and javadocs with my snapshots. This means that I want to automize the following command:

mvn clean source:jar javadoc:jar deploy

Just to execute:

mvn clean deploy

I don't want to have javadoc/sources generation executed during the install phase (i.e. local builds).

I know that source/javadoc plugins can be synchronized with the execution of the release plugin but I can't figure out how to wire it to the snapshots releases.

Body:
<build>
  <plugins>
    <plugin>
      <artifactId>maven-source-plugin</artifactId>
      <executions>
        <execution>
          <id>attach-sources</id>
          <phase>deploy</phase>
          <goals><goal>jar-no-fork</goal></goals>
        </execution>
      </executions>
    </plugin>
    <plugin>
      <artifactId>maven-javadoc-plugin</artifactId>
      <executions>
        <execution>
          <id>attach-javadocs</id>
          <phase>deploy</phase>
          <goals><goal>jar</goal></goals>
        </execution>
      </executions>
    </plugin>
    <plugin>
      <!-- explicitly define maven-deploy-plugin after other to force exec order -->
      <artifactId>maven-deploy-plugin</artifactId>
      <executions>
        <execution>
          <id>deploy</id>
          <phase>deploy</phase>
          <goals><goal>deploy</goal></goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

See Sonatype's OSS parent POM for a complete example.


问:
Missing closing paranthes MySQL workbench, Query syntax
this is my code:

```<code>SELECT Lname
    ,Fname
FROM EMPLOYEE
WHERE NOT EXISTS (
        SELECT *
        FROM WORKS_ON B
        WHERE (
                B.Pno IN (
                    SELECT Pnumber
                    FROM PROJECT
                    WHERE Dnum = 5
                        AND NOT EXISTS (
                            SELECT *
                            FROM WORKS_ON C
                            WHERE C.Essn = Ssn
                                AND C.Pno = B.Pno
                            )
                    )
                );
</code>```

It is almost true but it doesn't work error message : Missing closing parenthesis

答:
Because you missing a ) at the end of your query.

```<code>SELECT Lname, Fname FROM EMPLOYEE WHERE NOT EXISTS
(
    SELECT * FROM WORKS_ON B WHERE
    (

        B.Pno IN
        (   SELECT Pnumber FROM PROJECT WHERE Dnum=5 AND NOT EXISTS
            (   SELECT * FROM WORKS_ON C WHERE C.Essn=Ssn AND C.Pno=B.Pno)
        )
    )
);
</code>```

Body:
this is my code:

SELECT Lname
    ,Fname
FROM EMPLOYEE
WHERE NOT EXISTS (
        SELECT *
        FROM WORKS_ON B
        WHERE (
                B.Pno IN (
                    SELECT Pnumber
                    FROM PROJECT
                    WHERE Dnum = 5
                        AND NOT EXISTS (
                            SELECT *
                            FROM WORKS_ON C
                            WHERE C.Essn = Ssn
                                AND C.Pno = B.Pno
                            )
                    )
                );

It is almost true but it doesn't work error message : Missing closing parenthesis

Body:
Because you missing a ) at the end of your query.

SELECT Lname, Fname FROM EMPLOYEE WHERE NOT EXISTS
(
    SELECT * FROM WORKS_ON B WHERE
    (

        B.Pno IN
        (   SELECT Pnumber FROM PROJECT WHERE Dnum=5 AND NOT EXISTS
            (   SELECT * FROM WORKS_ON C WHERE C.Essn=Ssn AND C.Pno=B.Pno)
        )
    )
);


问:
how to read a specific line and print a specific position in this line using python
how to read specific lines from the text file, which contains several lines with the same character of "!". My goal is to find  the last line and print the position number four "[4]".

my file.txt:

```<code>     1.0000   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000
     1.0000   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000
     1.0000   1.0000   1.0002   0.9879   0.8682   0.6437  -0.0000  -0.0000
.
.
.
.
!    T   E              =    -122.1058
.
.
.
!    T   E              =    -123.1050
.
.
.
!    T   E              =    -125.10584323
</code>```

my script (not working):

```<code>import sys, os
import datetime
import time as t

oTE_list = []
oTE = []

with open("file.txt","r") as f:
    text = f.readlines()
for line in text:
  if line[0] == '!':
    oTE_list.append(line[4])

# Change Lists To Number Format
for item in oTE_list:
  oTE.append(float(item))

for idx, item in enumerate(oTE_list):
    if idx == len(oTE_list) - 1:
        print(item)
number5 = (item)
</code>```

on the other hand, I managed with bash:

```<code>grep ! file.txt | awk 'END{print $5}'
</code>```

the result should be like this: -125.10584323

Thanks.

答:
I think what you're looking for here is how to cut and slice your string. I've tweaked the code you supplied above to include this string slice. Check out the first for loop :-)

```<code>def main():
    oTE_list = []
    oTE = []

    with open("file.txt","r") as f:
        text = f.readlines()
    for line in text:
        if line[0] == '!':
            equals_index = line.index('=')
            # Get everything after the equal and remove extra whitespace
            after_equal = line[equals_index+1:].strip()
            oTE_list.append(after_equal)

    # Change Lists To Number Format
    for item in oTE_list:
        oTE.append(float(item))

    for idx, item in enumerate(oTE_list):
        if idx == len(oTE_list) - 1:
            print(item)

if __name__ == '__main__':
    main()
</code>```

Running this I get the result:

```<code>C:\Python35\python.exe C:/Users/Frito/GitSource/help/sample.py
-125.10584323
</code>```

Now you may be wondering how this is working. Your input is a bit difficult as there isn't really a good way that I know of to remove all the spaces in between the !, T, E, = and <number> fields. In this case by looking at your data I opted to find the equal sign and just look at the data after it. The line equals_index = line.index('=') finds the position in the string where the equal sign is at. This "position" includes spaces. This is can be seen by looking at the string's position 24. For example print(line[24]).

Now that we can compute where the equal sign is at we can then get everything after the equal sign. In your example this is the number you wish to print to the screen with some extra spaces. If you were to print the string "   abc   " directly using the print command it would print with three spaces before and after the abc. The .strip() function in python removes those extra spaces.

When we combine these two approaches above we can find your number and print just that number. I hope this helps!

Body:
how to read specific lines from the text file, which contains several lines with the same character of "!". My goal is to find  the last line and print the position number four "[4]".

my file.txt:

     1.0000   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000
     1.0000   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000
     1.0000   1.0000   1.0002   0.9879   0.8682   0.6437  -0.0000  -0.0000
.
.
.
.
!    T   E              =    -122.1058
.
.
.
!    T   E              =    -123.1050
.
.
.
!    T   E              =    -125.10584323

my script (not working):

import sys, os
import datetime
import time as t

oTE_list = []
oTE = []

with open("file.txt","r") as f:
    text = f.readlines()
for line in text:
  if line[0] == '!':
    oTE_list.append(line[4])

# Change Lists To Number Format
for item in oTE_list:
  oTE.append(float(item))

for idx, item in enumerate(oTE_list):
    if idx == len(oTE_list) - 1:
        print(item)
number5 = (item)

on the other hand, I managed with bash:

grep ! file.txt | awk 'END{print $5}'

the result should be like this: -125.10584323

Thanks.

Body:
I think what you're looking for here is how to cut and slice your string. I've tweaked the code you supplied above to include this string slice. Check out the first for loop :-)

def main():
    oTE_list = []
    oTE = []

    with open("file.txt","r") as f:
        text = f.readlines()
    for line in text:
        if line[0] == '!':
            equals_index = line.index('=')
            # Get everything after the equal and remove extra whitespace
            after_equal = line[equals_index+1:].strip()
            oTE_list.append(after_equal)

    # Change Lists To Number Format
    for item in oTE_list:
        oTE.append(float(item))

    for idx, item in enumerate(oTE_list):
        if idx == len(oTE_list) - 1:
            print(item)

if __name__ == '__main__':
    main()

Running this I get the result:

C:\Python35\python.exe C:/Users/Frito/GitSource/help/sample.py
-125.10584323

Now you may be wondering how this is working. Your input is a bit difficult as there isn't really a good way that I know of to remove all the spaces in between the !, T, E, = and <number> fields. In this case by looking at your data I opted to find the equal sign and just look at the data after it. The line equals_index = line.index('=') finds the position in the string where the equal sign is at. This "position" includes spaces. This is can be seen by looking at the string's position 24. For example print(line[24]).

Now that we can compute where the equal sign is at we can then get everything after the equal sign. In your example this is the number you wish to print to the screen with some extra spaces. If you were to print the string "   abc   " directly using the print command it would print with three spaces before and after the abc. The .strip() function in python removes those extra spaces.

When we combine these two approaches above we can find your number and print just that number. I hope this helps!


问:
Highcharts width flow out of parent div
I am trying to create a dashboard where I want a chart made using highcharts and an action box in a row and in turn two buttons in action box in column. I want the action box to wrap the content and chart to take leftover space. But I am not getting expected result. The chart is taking more width than its parent div i.e. its container. Here is my HTML code.

```<code><md-content flex layout-padding>
    <md-card layout="row" layout-wrap>
        <div flex layout-padding>
            <highchart id="summary-chart" config="dashboard.chartConfig"></highchart>
        </div>
        <div layout-align="start center" layout="column" layout-padding>
            <div layout-align="start center" layout-fill>
                <img src="../../../assets/images/computer.png">
                <label layout-fill>Computer</label>
            </div>
        </div>
    </md-card>
</md-content>
</code>```

Here is something that I expect:

This is what I am getting as result:

Note: The icon is hidden by the chart

答:
Add this code in your css file</p>

```<code> .highcharts-container {
    width:100% !important;
    height:100% !important;
 }
</code>```

Title: Highcharts width flow out of parent div

Body:
I am trying to create a dashboard where I want a chart made using highcharts and an action box in a row and in turn two buttons in action box in column. I want the action box to wrap the content and chart to take leftover space. But I am not getting expected result. The chart is taking more width than its parent div i.e. its container. Here is my HTML code.

<md-content flex layout-padding>
    <md-card layout="row" layout-wrap>

            <highchart id="summary-chart" config="dashboard.chartConfig"></highchart>

                Computer

    </md-card>
</md-content>

Here is something that I expect:

This is what I am getting as result:

Note: The icon is hidden by the chart

Body:
Add this code in your css file

 .highcharts-container {
    width:100% !important;
    height:100% !important;
 }


答:
It's simple enough, I don't know why you complicated it.

```<code>f = open("file.txt", "r")
lines = [line for line in f.readlines() if line[0]=="!"]
number = float(lines[-1].split()[4])
</code>```

Explanation:

f.readlines() reads all lines and make a list of lines.

lines is a list of lines starting with !.

lines[-1] selects the last lines from the list.

lines[-1].split() will make a list of words in the last line. (split at " " (spaces))

lines[-1].split()[4] will select the 5th word from the list of words.

float(lines[-1].split()[4]) will convert the word to float.

Title: how to read a specific line and print a specific position in this line using python

Body:
It's simple enough, I don't know why you complicated it.

f = open("file.txt", "r")
lines = [line for line in f.readlines() if line[0]=="!"]
number = float(lines[-1].split()[4])

Explanation:

f.readlines() reads all lines and make a list of lines.

lines is a list of lines starting with !.

lines[-1] selects the last lines from the list.

lines[-1].split() will make a list of words in the last line. (split at " " (spaces))

lines[-1].split()[4] will select the 5th word from the list of words.

float(lines[-1].split()[4]) will convert the word to float.