问:
Use column values of dataframe as index and columns name
I'm working with a dataframe that looks like this:

```<code>    Client_ID   Product_ID   Cost
0      4            1         40
1      4            2         32
2      5            1         38
3      6            7         89
4      7            3         21
5      4            5         45
6      2            5         23
7      2            4         71
8      5            8         11
9      7            8         14
</code>```

For each couple 'Client_ID, Product_ID' there is only one occurence/row in the dataframe.

I want to build a dataframe where the Product_ID is the index and where the the column names are the client names while the cost become the value in each cell, it would look like this:

```<code>                     Client_ID
Product_ID    1   2   3   4   5   6   7
   1          x   x   x  40  38   x   x
   2          x   x   x  32   x   x   x
   3          x   x   x   x   x   x  21
   4          x  71   x   x   x   x   x
   5          x  23   x  45   x   x   x
   6          x   x   x   x   x   x   x
   7          x   x   x   x   x  89   x
   8          x   x   x   x  11   x  14
   9          x   x   x   x   x   x   x
  10          x   x   x   x   x   x   x
</code>```

I tried to achieve this by doing this:

```<code>df.pivot(index='Product_ID', columns='Client_ID')
</code>```

But it didn't work, I tried then making Product_ID the index first and then do the pivot:

```<code>df = df.set_index('Product_ID')
df.index.name = None
df.pivot(columns='Client_ID')
</code>```

No success neither.

Does somebody know how to achieve such a thing?

Thank you for your help.

Edit

The Product_ID values are strings.

答:
It seems need pivot + reindex for add missing rows/ columns:

```<code>#reindex by union of columns
a = np.union1d(df['Client_ID'],df['Product_ID'])
df = df.pivot(index='Product_ID', columns='Client_ID', values='Cost')
       .reindex(index=a, columns=a)
print (df)
Client_ID    1     2   3     4     5     6     7   8
Product_ID
1          NaN   NaN NaN  40.0  38.0   NaN   NaN NaN
2          NaN   NaN NaN  32.0   NaN   NaN   NaN NaN
3          NaN   NaN NaN   NaN   NaN   NaN  21.0 NaN
4          NaN  71.0 NaN   NaN   NaN   NaN   NaN NaN
5          NaN  23.0 NaN  45.0   NaN   NaN   NaN NaN
6          NaN   NaN NaN   NaN   NaN   NaN   NaN NaN
7          NaN   NaN NaN   NaN   NaN  89.0   NaN NaN
8          NaN   NaN NaN   NaN  11.0   NaN  14.0 NaN
</code>```

Or:

```<code>#1 to max value of columns
b = range(1,df['Client_ID'].max()+1)
a = range(1,df['Product_ID'].max()+1)
df = df.pivot(index='Product_ID', columns='Client_ID', values='Cost')
       .reindex(index=a, columns=b)
print (df)
Client_ID    1     2   3     4     5     6     7
Product_ID
1          NaN   NaN NaN  40.0  38.0   NaN   NaN
2          NaN   NaN NaN  32.0   NaN   NaN   NaN
3          NaN   NaN NaN   NaN   NaN   NaN  21.0
4          NaN  71.0 NaN   NaN   NaN   NaN   NaN
5          NaN  23.0 NaN  45.0   NaN   NaN   NaN
6          NaN   NaN NaN   NaN   NaN   NaN   NaN
7          NaN   NaN NaN   NaN   NaN  89.0   NaN
8          NaN   NaN NaN   NaN  11.0   NaN  14.0
</code>```

Detail:

```<code>print (df.pivot(index='Product_ID', columns='Client_ID', values='Cost'))
Client_ID      2     4     5     6     7
Product_ID
1            NaN  40.0  38.0   NaN   NaN
2            NaN  32.0   NaN   NaN   NaN
3            NaN   NaN   NaN   NaN  21.0
4           71.0   NaN   NaN   NaN   NaN
5           23.0  45.0   NaN   NaN   NaN
7            NaN   NaN   NaN  89.0   NaN
8            NaN   NaN  11.0   NaN  14.0
</code>```

Last if necessary replace NaNs, but get mixed values - numeric with strings:

```<code>df = df.fillna('x')
</code>```

Body:
I'm working with a dataframe that looks like this:

    Client_ID   Product_ID   Cost
0      4            1         40
1      4            2         32
2      5            1         38
3      6            7         89
4      7            3         21
5      4            5         45
6      2            5         23
7      2            4         71
8      5            8         11
9      7            8         14

For each couple 'Client_ID, Product_ID' there is only one occurence/row in the dataframe.

I want to build a dataframe where the Product_ID is the index and where the the column names are the client names while the cost become the value in each cell, it would look like this:

                     Client_ID
Product_ID    1   2   3   4   5   6   7
   1          x   x   x  40  38   x   x
   2          x   x   x  32   x   x   x
   3          x   x   x   x   x   x  21
   4          x  71   x   x   x   x   x
   5          x  23   x  45   x   x   x
   6          x   x   x   x   x   x   x
   7          x   x   x   x   x  89   x
   8          x   x   x   x  11   x  14
   9          x   x   x   x   x   x   x
  10          x   x   x   x   x   x   x

I tried to achieve this by doing this:

df.pivot(index='Product_ID', columns='Client_ID')

But it didn't work, I tried then making Product_ID the index first and then do the pivot:

df = df.set_index('Product_ID')
df.index.name = None
df.pivot(columns='Client_ID')

No success neither.

Does somebody know how to achieve such a thing?

Thank you for your help.

Edit

The Product_ID values are strings.

Body:
It seems need pivot + reindex for add missing rows/ columns:

#reindex by union of columns
a = np.union1d(df['Client_ID'],df['Product_ID'])
df = df.pivot(index='Product_ID', columns='Client_ID', values='Cost')
       .reindex(index=a, columns=a)
print (df)
Client_ID    1     2   3     4     5     6     7   8
Product_ID
1          NaN   NaN NaN  40.0  38.0   NaN   NaN NaN
2          NaN   NaN NaN  32.0   NaN   NaN   NaN NaN
3          NaN   NaN NaN   NaN   NaN   NaN  21.0 NaN
4          NaN  71.0 NaN   NaN   NaN   NaN   NaN NaN
5          NaN  23.0 NaN  45.0   NaN   NaN   NaN NaN
6          NaN   NaN NaN   NaN   NaN   NaN   NaN NaN
7          NaN   NaN NaN   NaN   NaN  89.0   NaN NaN
8          NaN   NaN NaN   NaN  11.0   NaN  14.0 NaN

Or:

#1 to max value of columns
b = range(1,df['Client_ID'].max()+1)
a = range(1,df['Product_ID'].max()+1)
df = df.pivot(index='Product_ID', columns='Client_ID', values='Cost')
       .reindex(index=a, columns=b)
print (df)
Client_ID    1     2   3     4     5     6     7
Product_ID
1          NaN   NaN NaN  40.0  38.0   NaN   NaN
2          NaN   NaN NaN  32.0   NaN   NaN   NaN
3          NaN   NaN NaN   NaN   NaN   NaN  21.0
4          NaN  71.0 NaN   NaN   NaN   NaN   NaN
5          NaN  23.0 NaN  45.0   NaN   NaN   NaN
6          NaN   NaN NaN   NaN   NaN   NaN   NaN
7          NaN   NaN NaN   NaN   NaN  89.0   NaN
8          NaN   NaN NaN   NaN  11.0   NaN  14.0

Detail:

print (df.pivot(index='Product_ID', columns='Client_ID', values='Cost'))
Client_ID      2     4     5     6     7
Product_ID
1            NaN  40.0  38.0   NaN   NaN
2            NaN  32.0   NaN   NaN   NaN
3            NaN   NaN   NaN   NaN  21.0
4           71.0   NaN   NaN   NaN   NaN
5           23.0  45.0   NaN   NaN   NaN
7            NaN   NaN   NaN  89.0   NaN
8            NaN   NaN  11.0   NaN  14.0

Last if necessary replace NaNs, but get mixed values - numeric with strings:

df = df.fillna('x')


来源: stackexchange

问:
Retrieving friends info using Facebook API

Possible Duplicate:

  How to get all friends name, id, birthday, location, etc.. from facebook API in android?

I am trying to set up a Facebook application where I have to compare the information of the user with his friends. I do not know how to retrieve the friends information such as birthday, hometown, etc. I tried using

```<code>$facebook->api('/Friend_ID')
</code>```

but this is not working. However I have already set up the extended permissions. Only to retrieve the information, I am unable to do this.. Can you please guide me?

答: What does Facebook respond for your request '/FriendID' ?</p>

ContentLicense: CC BY-SA 2.5

Body:
Possible Duplicate:

  How to get all friends name, id, birthday, location, etc.. from facebook API in android?

I am trying to set up a Facebook application where I have to compare the information of the user with his friends. I do not know how to retrieve the friends information such as birthday, hometown, etc. I tried using

$facebook->api('/Friend_ID')

but this is not working. However I have already set up the extended permissions. Only to retrieve the information, I am unable to do this.. Can you please guide me?


问:
dev and prod views give different results
I try to map and reduce datas with a couchbase view.

While in dev, everything is ok. The value returned by the reduce function is the json formated doc i'm waiting.

But when I publish the view in prod, I only got null values (keys seems to be ok : they are the same, but no value anymore).

I've tried with a simpler view (a custom _count) and the prod view gives me 3 for each key (which is obviously false) while it seems ok in dev

I can't see any error reported.

Does anyone has a clue ?

Why do dev and prod view give so different results without any error ?

How can I debug my view in this context ?

May it be a problem with the RAM size ?

The map function looks like :

```<code>function (doc, meta) {
  if (doc.EXENUM_A != "")
  {
    if (doc.PRS != "") {
      emit(doc.EXENUM_A, { ... });
    }
  }
}
</code>```

And the reduce one :

```<code>function (keys, values) {
  for (k in keys) {
    result = {"PRS":{}};
    for (v in values) { // result is modified
    ... }
    return result;
  }
}
</code>```

In dev, i get dictionary return values, in prod, i get null return values.

答: View in development mode works on a subset of documents</p>

ContentLicense: CC BY-SA 3.0

Body:
I try to map and reduce datas with a couchbase view.

While in dev, everything is ok. The value returned by the reduce function is the json formated doc i'm waiting.

But when I publish the view in prod, I only got null values (keys seems to be ok : they are the same, but no value anymore).

I've tried with a simpler view (a custom _count) and the prod view gives me 3 for each key (which is obviously false) while it seems ok in dev

I can't see any error reported.

Does anyone has a clue ?

Why do dev and prod view give so different results without any error ?

How can I debug my view in this context ?

May it be a problem with the RAM size ?

The map function looks like :

function (doc, meta) {
  if (doc.EXENUM_A != "")
  {
    if (doc.PRS != "") {
      emit(doc.EXENUM_A, { ... });
    }
  }
}

And the reduce one :

function (keys, values) {
  for (k in keys) {
    result = {"PRS":{}};
    for (v in values) { // result is modified
    ... }
    return result;
  }
}

In dev, i get dictionary return values, in prod, i get null return values.


问:
Need help in Merging Two query for HP ALM
I have two different query in HP ALM, but i want to merge and get it into one. I am not that good in SQL query so I am facing hard time in merging the query.

Query 1: Getting the execution Count for the tester

```<code>Select
 TESTCYCL.TC_ACTUAL_TESTER as 'Tester',
 sum(case when TC_Status In('Blocked','Passed','Failed','Not Completed') then 1 else 0 end) as 'Total',
 sum(case when TC_Status = 'Passed' then 1 else 0 end) as 'Pass',
 sum(case when TC_Status = 'Failed' then 1 else 0 end) as 'Fail',
 sum(case when TC_Status = 'Blocked' then 1 else 0 end) as 'Blocked',
 sum(case when TC_Status In('Not Completed','Defferred','N/A') then 1 else 0 end) as 'Others'

From  TESTCYCL
Where
 TESTCYCL.TC_EXEC_DATE = CAST(CURRENT_TIMESTAMP AS DATE)
 And
 TESTCYCL.TC_ACTUAL_TESTER in ('Username1')
 Group by TC_ACTUAL_TESTER
</code>```

Query 2: Getting the Defect raise by the tester

```<code>SELECT
 BG_DETECTED_BY,
 Sum(case when BG_Status Not in ('Closed','Defect Resolved','Rejected')then 1 else 0 end) as 'Defect Raised'
 FROM BUG
 Where BUG.BG_DETECTED_BY in ('username1')
 AND BUG.BG_DETECTION_DATE = CAST(CURRENT_TIMESTAMP AS DATE)
 Group by BG_DETECTED_BY
</code>```

I have tried inner join/ Left Join but the count of the defect raised by the user is not matching

Query3 : That i have tried:

```<code> Select
  TESTCYCL.TC_ACTUAL_TESTER as 'Tester',
  sum(case when TC_Status In('Blocked','Passed','Failed','Not Completed') then 1 else 0 end) as 'Total',
  sum(case when TC_Status = 'Passed' then 1 else 0 end) as 'Pass',
  sum(case when TC_Status = 'Failed' then 1 else 0 end) as 'Fail',
  sum(case when TC_Status = 'Blocked' then 1 else 0 end) as 'Blocked',
  sum(case when TC_Status In('Not Completed','Defferred','N/A') then 1 else 0 end) as 'Others',
  Sum(case when BG_Status Not in ('Closed','Defect Resolved','Rejected')then 1 else 0 end) as 'Defect Raised'

From  TESTCYCL
Left Join BUG
  on TESTCYCL.TC_ACTUAL_TESTER =  BUG.BG_DETECTED_BY
 AND  BUG.BG_DETECTION_DATE = CAST(CURRENT_TIMESTAMP AS DATE)
Where TESTCYCL.TC_EXEC_DATE = CAST(CURRENT_TIMESTAMP AS DATE)
  And TESTCYCL.TC_ACTUAL_TESTER in ('username1')
Group by TC_ACTUAL_TESTER
</code>```

Out is mentioned as below:

```<code>Expected Output:
Tester   Total Execution  Passed  Failed  ... Defect Raised
  A          5              3       2             10

Actual Output:
Tester   Total Execution  Passed  Failed  ... Defect Raised
  A          56              3       2             45
</code>```

答:
The problem is you are doing the COUNT() over the product cartesian. instead of concatenating the result.

Right now you are doing

```<code>   COUNT(A*B) instead of COUNT(A) || COUNT(B)
</code>```

general example, if you have two queries

```<code>SELECT * FROM A (ex: 10 rows)
SELECT * FROM B (ex: 10 rows)
</code>```

What you need is:

```<code> SELECT temp1.*, temp2.*
 FROM (SELECT * FROM A) as temp1
 JOIN (SELECT * FROM B) as temp2
   ON temp1.ID = temp2.ID
</code>```

Body:
I have two different query in HP ALM, but i want to merge and get it into one. I am not that good in SQL query so I am facing hard time in merging the query.

Query 1: Getting the execution Count for the tester

Select
 TESTCYCL.TC_ACTUAL_TESTER as 'Tester',
 sum(case when TC_Status In('Blocked','Passed','Failed','Not Completed') then 1 else 0 end) as 'Total',
 sum(case when TC_Status = 'Passed' then 1 else 0 end) as 'Pass',
 sum(case when TC_Status = 'Failed' then 1 else 0 end) as 'Fail',
 sum(case when TC_Status = 'Blocked' then 1 else 0 end) as 'Blocked',
 sum(case when TC_Status In('Not Completed','Defferred','N/A') then 1 else 0 end) as 'Others'

From  TESTCYCL
Where
 TESTCYCL.TC_EXEC_DATE = CAST(CURRENT_TIMESTAMP AS DATE)
 And
 TESTCYCL.TC_ACTUAL_TESTER in ('Username1')
 Group by TC_ACTUAL_TESTER

Query 2: Getting the Defect raise by the tester

SELECT
 BG_DETECTED_BY,
 Sum(case when BG_Status Not in ('Closed','Defect Resolved','Rejected')then 1 else 0 end) as 'Defect Raised'
 FROM BUG
 Where BUG.BG_DETECTED_BY in ('username1')
 AND BUG.BG_DETECTION_DATE = CAST(CURRENT_TIMESTAMP AS DATE)
 Group by BG_DETECTED_BY

I have tried inner join/ Left Join but the count of the defect raised by the user is not matching

Query3 : That i have tried:

 Select
  TESTCYCL.TC_ACTUAL_TESTER as 'Tester',
  sum(case when TC_Status In('Blocked','Passed','Failed','Not Completed') then 1 else 0 end) as 'Total',
  sum(case when TC_Status = 'Passed' then 1 else 0 end) as 'Pass',
  sum(case when TC_Status = 'Failed' then 1 else 0 end) as 'Fail',
  sum(case when TC_Status = 'Blocked' then 1 else 0 end) as 'Blocked',
  sum(case when TC_Status In('Not Completed','Defferred','N/A') then 1 else 0 end) as 'Others',
  Sum(case when BG_Status Not in ('Closed','Defect Resolved','Rejected')then 1 else 0 end) as 'Defect Raised'

From  TESTCYCL
Left Join BUG
  on TESTCYCL.TC_ACTUAL_TESTER =  BUG.BG_DETECTED_BY
 AND  BUG.BG_DETECTION_DATE = CAST(CURRENT_TIMESTAMP AS DATE)
Where TESTCYCL.TC_EXEC_DATE = CAST(CURRENT_TIMESTAMP AS DATE)
  And TESTCYCL.TC_ACTUAL_TESTER in ('username1')
Group by TC_ACTUAL_TESTER

Out is mentioned as below:

Expected Output:
Tester   Total Execution  Passed  Failed  ... Defect Raised
  A          5              3       2             10

Actual Output:
Tester   Total Execution  Passed  Failed  ... Defect Raised
  A          56              3       2             45

Body:
The problem is you are doing the COUNT() over the product cartesian. instead of concatenating the result.

Right now you are doing

   COUNT(A*B) instead of COUNT(A) || COUNT(B)

general example, if you have two queries

SELECT * FROM A (ex: 10 rows)
SELECT * FROM B (ex: 10 rows)

What you need is:

 SELECT temp1.*, temp2.*
 FROM (SELECT * FROM A) as temp1
 JOIN (SELECT * FROM B) as temp2
   ON temp1.ID = temp2.ID


问:
Bash Script using Grep to search for a pattern in a file
I am writing a bash script to search for a pattern in a file using GREP. I am clueless for why it isnt working. This is the program

```<code>echo "Enter file name...";
read fname;
echo "Enter the search pattern";
read pattern
if [ -f $fname ]; then
    result=`grep -i '$pattern' $fname`
    echo $result;
fi
</code>```

Or is there different approach to do this ?

Thanks

(contents of file)

```<code>Welcome to UNIX
The shell is a command programming language that provides an interface to the UNIX operating system.
The shell can modify the environment in which commands run.
Simple UNIX commands consist of one or more words separated by blanks.
Most commands produce output on the standard output that is initially connected to the terminal. This output may be sent to a file by writing.
The standard output of one UNIX command may be connected to the standard input of another UNIX Command by writing the `pipe' operator, indicated by |
</code>```

(pattern)

```<code>`UNIX` or `unix`
</code>```

答:
```<code>read -p "Enter file name..." fname
read -p "Enter the search pattern" pattern
if [ -f "$fname" ]
then
    result=$(grep -i -v -e $pattern -e "$fname")
    echo "$result"
fi
</code>```

Body:
I am writing a bash script to search for a pattern in a file using GREP. I am clueless for why it isnt working. This is the program

echo "Enter file name...";
read fname;
echo "Enter the search pattern";
read pattern
if [ -f $fname ]; then
    result=`grep -i '$pattern' $fname`
    echo $result;
fi

Or is there different approach to do this ?

Thanks

(contents of file)

Welcome to UNIX
The shell is a command programming language that provides an interface to the UNIX operating system.
The shell can modify the environment in which commands run.
Simple UNIX commands consist of one or more words separated by blanks.
Most commands produce output on the standard output that is initially connected to the terminal. This output may be sent to a file by writing.
The standard output of one UNIX command may be connected to the standard input of another UNIX Command by writing the `pipe' operator, indicated by |

(pattern)

`UNIX` or `unix`

ContentLicense: CC BY-SA 4.0


问:
execute in remote machine from a shell script in local machine

shell script should be on local machine.

shell script contain two steps
a. ssh command along with password
b. sudo command along with password.

i cannot install any packages not allowed.

Please help me how to write command inside shell script.

答:
Try this:</p>

```<code>ssh user@server_ip "bash -s" < script.sh
</code>```

Body:
Try this:

ssh user@server_ip "bash -s" < script.sh


问:
Turnoff mysql unsafe statement warning
I am using log-error to write warning/errors into a file.  When I perform INSERT IGNORE..SELECT statement, it just keep write this warning messages.

```<code>120905  3:01:23 [Warning] Unsafe statement written to the binary log using statement format since BINLOG_FORMAT = STATEMENT. INSERT IGNORE... SELECT is unsafe because the order in which rows are retrieved by the SELECT determines which (if any) rows are ignored. This order cannot be predicted and may differ on master and the slave.
</code>```

I want to stop mysql logwriter keep writing the error above over and over. (I can't see other log because they fillout the whole logfile...)

First of all, I insert (a, b, c) into a table.  c should be unique in the table, and a, b are used to select. Query will be like this

```<code>SELECT c FROM table WHERE a=value1 AND value2<b AND b<value3
</code>```

And my insert query is

```<code>INSERT IGNORE INTO table VALUES (,,),(,,)...(,,)
</code>```

I thought I could change the query not to produce warning, but my data contain unique field and I need to guarantee that the filed is unique in the table.  And 500~2000 rows should be inserted in every few seconds, so I need to do bulk insert.

If there are already dozen of millions row inserted, and I need to insert another 2000 rows in few seconds. How can I insert them safely into the table without filling the logfile with the warnings?

(I can't turn off the binary log because I need to use mysql replication.)

答:
I think this question is still open.
Use
    set max_error_count=0;
    your unsafe queries;
    set  max_error_count=64;

before the queries you want to run it is a session  variable, so you don't need to be super user to use. Not only, no warnings will be issued when you call show warnings limit 5; but such warnings are not reporting in mysql log files.
you can also use it in stored procedures. After your queries you know that are unsafe, you  can put back this variable to its original value.

Title: Turnoff mysql unsafe statement warning

Body:
I am using log-error to write warning/errors into a file.  When I perform INSERT IGNORE..SELECT statement, it just keep write this warning messages.

120905  3:01:23 [Warning] Unsafe statement written to the binary log using statement format since BINLOG_FORMAT = STATEMENT. INSERT IGNORE... SELECT is unsafe because the order in which rows are retrieved by the SELECT determines which (if any) rows are ignored. This order cannot be predicted and may differ on master and the slave.

I want to stop mysql logwriter keep writing the error above over and over. (I can't see other log because they fillout the whole logfile...)

First of all, I insert (a, b, c) into a table.  c should be unique in the table, and a, b are used to select. Query will be like this

SELECT c FROM table WHERE a=value1 AND value2<b AND b<value3

And my insert query is

INSERT IGNORE INTO table VALUES (,,),(,,)...(,,)

I thought I could change the query not to produce warning, but my data contain unique field and I need to guarantee that the filed is unique in the table.  And 500~2000 rows should be inserted in every few seconds, so I need to do bulk insert.

If there are already dozen of millions row inserted, and I need to insert another 2000 rows in few seconds. How can I insert them safely into the table without filling the logfile with the warnings?

(I can't turn off the binary log because I need to use mysql replication.)


问:
How do could I insert a certain value into a specific column
```<code>import sqlite3 as db

def criar_grupos():
    global cursor3,nome_grupo
    nome_grupo = raw_input('name of group')
    nome_criador = raw_input('new user')
    conn3 = db.connect("tabela_grupos.db")
    cursor3 = conn3.cursor()
    cursor3.execute('CREATE TABLE IF NOT EXISTS groups (name string NOT NULL
UNIQUE)')
    conn3.commit()

    cursor3.execute("alter table grupos add column '%s' 'string'" %
nome_grupo)
    cursor3.execute('UPDATE grupos SET ("nome"=?) WHERE name=?',
(nome_grupo, nome_criador))

criar_grupos()
</code>```

I'm having a bad time trying to execute this function.

I keep getting the error message:
sqlite3.OperationalError: near "(": syntax error

What could I be doing wrong.?

答:
```<code>INSERT INTO <table> (col1, col2, col5) VALUES ('val1','val2','val5');
</code>```

Body:
import sqlite3 as db

def criar_grupos():
    global cursor3,nome_grupo
    nome_grupo = raw_input('name of group')
    nome_criador = raw_input('new user')
    conn3 = db.connect("tabela_grupos.db")
    cursor3 = conn3.cursor()
    cursor3.execute('CREATE TABLE IF NOT EXISTS groups (name string NOT NULL
UNIQUE)')
    conn3.commit()

    cursor3.execute("alter table grupos add column '%s' 'string'" %
nome_grupo)
    cursor3.execute('UPDATE grupos SET ("nome"=?) WHERE name=?',
(nome_grupo, nome_criador))

criar_grupos()

I'm having a bad time trying to execute this function.

I keep getting the error message:
sqlite3.OperationalError: near "(": syntax error

What could I be doing wrong.?


问:
String compare strange bug
I have strange bug in my code. I have variable type and when I load that from class Settings ( implements persistable ) it has value "CPU 21" (type="CPU 21"), but when I try
 if(type=="CPU 21") the condition is false. How is that possible ? </p>

答:
What is difference between equals() and == ?

Explanation : 1

They both differ very much in their significance. equals() method is present in the java.lang.Object class and it is expected to check for the equivalence of the state of objects! That means, the contents of the objects. Whereas the '==' operator is expected to check the actual object instances are same or not.

For example, lets say, you have two String objects and they are being pointed by two different reference variables s1 and s2.

```<code> s1 = new String("abc");

 s2 = new String("abc");
</code>```

Now, if you use the "equals()" method to check for their equivalence as

```<code>if(s1.equals(s2))
      System.out.println("s1.equals(s2) is TRUE");
 else
      System.out.println("s1.equals(s2) is FALSE");
</code>```

You will get the output as TRUE as the 'equals()' method check for the content equivality.

Lets check the '==' operator..

```<code>if(s1==s2)
     System.out.printlln("s1==s2 is TRUE");
   else
     System.out.println("s1==s2 is FALSE");
</code>```

Now you will get the FALSE as output because both s1 and s2 are pointing to two different objects even though both of them share the same string content. It is because of 'new String()' everytime a new object is created.

Try running the program without 'new String' and just with

```<code>String s1 = "abc";

   String s2 = "abc";
</code>```

You will get TRUE for both the tests.

Explanation : 2

By definintion, the objects are all created on the heap. When you create an object, say,

```<code>Object ob1 = new SomeObject();

Object ob2 = new SomeObject();
</code>```

We have 2 objects with exactly the same contents, lets assume. We also have 2 references, lets say ob1 is at address 0x1234 and ob2 is at address 0x2345. Though the contents of the objects are the same, the references differ.

Using == compares the references. Though the objects, ob1 and ob2 are same internally, they differ on using this operation as we comare references. ob1 at address 0x1234 is compared with ob2 at address 0x2345. Hence, this comparison would fail.

object.equals() on the other hand compares the values. Hence, the comparison between ob1 and ob2 would pass. Note that the equals method should be explicitly overridden for this comparison to succeed.

Title: String compare strange bug

Body:
What is difference between equals() and == ?

Explanation : 1

They both differ very much in their significance. equals() method is present in the java.lang.Object class and it is expected to check for the equivalence of the state of objects! That means, the contents of the objects. Whereas the '==' operator is expected to check the actual object instances are same or not.

For example, lets say, you have two String objects and they are being pointed by two different reference variables s1 and s2.

 s1 = new String("abc");

 s2 = new String("abc");

Now, if you use the "equals()" method to check for their equivalence as

if(s1.equals(s2))
      System.out.println("s1.equals(s2) is TRUE");
 else
      System.out.println("s1.equals(s2) is FALSE");

You will get the output as TRUE as the 'equals()' method check for the content equivality.

Lets check the '==' operator..

if(s1==s2)
     System.out.printlln("s1==s2 is TRUE");
   else
     System.out.println("s1==s2 is FALSE");

Now you will get the FALSE as output because both s1 and s2 are pointing to two different objects even though both of them share the same string content. It is because of 'new String()' everytime a new object is created.

Try running the program without 'new String' and just with

String s1 = "abc";

   String s2 = "abc";

You will get TRUE for both the tests.

Explanation : 2

By definintion, the objects are all created on the heap. When you create an object, say,

Object ob1 = new SomeObject();

Object ob2 = new SomeObject();

We have 2 objects with exactly the same contents, lets assume. We also have 2 references, lets say ob1 is at address 0x1234 and ob2 is at address 0x2345. Though the contents of the objects are the same, the references differ.

Using == compares the references. Though the objects, ob1 and ob2 are same internally, they differ on using this operation as we comare references. ob1 at address 0x1234 is compared with ob2 at address 0x2345. Hence, this comparison would fail.

object.equals() on the other hand compares the values. Hence, the comparison between ob1 and ob2 would pass. Note that the equals method should be explicitly overridden for this comparison to succeed.


问:
can not find element to click on it for below angular code in protracror
Can anyone suggest me how to get an element and how to click on it by using below code

    <button #btn type="button" class="refereFrnd"  (click)="refereFrndMenu.toggle($event)"></button>

```

<p>I have tried with below code but getting error</p>

<pre class="lang-js prettyprint-override"><code>let footer = element(by.css('div[class="ui-g"]'));
footer.element(by.tagName('i')).click();
</code>```

Error: Failed: unknown error: Element  is not clickable at point (1079, 52). Other element would receive the click:
...

      (Session info: chrome=62.0.3202.94)

      (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)

答:
You should use expected conditions (http://www.protractortest.org/#/api?view=ProtractorExpectedConditions):</p>

```<code>var EC = protractor.ExpectedConditions;
var footer = element(by.css('div[class="ui-g"]'));
var isDisplayed = EC.visibilityOf(footer);

...

browser.wait(isDisplayed, 5000);
</code>```

Body:
Can anyone suggest me how to get an element and how to click on it by using below code

    <button #btn type="button" class="refereFrnd"  (click)="refereFrndMenu.toggle($event)"></button>

I have tried with below code but getting error

let footer = element(by.css('div[class="ui-g"]'));
footer.element(by.tagName('i')).click();

Error: Failed: unknown error: Element  is not clickable at point (1079, 52). Other element would receive the click:
...

      (Session info: chrome=62.0.3202.94)

      (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)

Body:
You should use expected conditions (http://www.protractortest.org/#/api?view=ProtractorExpectedConditions):

var EC = protractor.ExpectedConditions;
var footer = element(by.css('div[class="ui-g"]'));
var isDisplayed = EC.visibilityOf(footer);

...

browser.wait(isDisplayed, 5000);


问:
Show complete arguments in strace even in curly brackets
I know the -s option should display longer arguments, but it doesn't work always (probably because of those curly brackets meaning array or nested arguments?).

Even after running strace -s1000 my_command this argument is still truncated:

```<code>ioctl(3, SNDCTL_TMR_TEMPO or TCGETA, {B9600 -opost -isig -icanon -echo ...}) = 0
</code>```

How can I see the complete arguments?

答: According to the manual and the source, the -v option should help you with large structures.

Body:
I know the -s option should display longer arguments, but it doesn't work always (probably because of those curly brackets meaning array or nested arguments?).

Even after running strace -s1000 my_command this argument is still truncated:

ioctl(3, SNDCTL_TMR_TEMPO or TCGETA, {B9600 -opost -isig -icanon -echo ...}) = 0

How can I see the complete arguments?


问:
How can I retrieve RequestMappingInfo from HttpServletRequest?
I have Spring MVC application and I need to get RequestMappingInfo in controller about current request or cast it from HttpServletRequest. Is there any way I can do it?</p>

```<code>@GetMapping
public void test(RequestMappingInfo requestMappingInfo,
                 Authentication auth) {
    service.verify(requestMappingInfo, auth);
}
</code>```

答:
I have just read spring document and found this.

@Nullable public RequestMappingInfo
  getMatchingCondition(HttpServletRequest request) Checks if all
  conditions in this request mapping info match the provided request and
  returns a potentially new request mapping info with conditions
  tailored to the current request. For example the returned instance may
  contain the subset of URL patterns that match to the current request,
  sorted with best matching patterns on top.

Specified by:

```<code>getMatchingCondition in interface RequestCondition<RequestMappingInfo>
</code>```

I didn't try this code , please can you check?

Exam:

```<code>private
@Autowired HttpServletRequest request;

@GetMapping
public void test(RequestMappingInfo requestMappingInfo, Authentication auth{
        assertEquals(requestMappingInfo, requestMappingInfo.getMatchingCondition(request));
}
</code>```

Body:
I have Spring MVC application and I need to get RequestMappingInfo in controller about current request or cast it from HttpServletRequest. Is there any way I can do it?

@GetMapping
public void test(RequestMappingInfo requestMappingInfo,
                 Authentication auth) {
    service.verify(requestMappingInfo, auth);
}

Body:
I have just read spring document and found this.

@Nullable public RequestMappingInfo
  getMatchingCondition(HttpServletRequest request) Checks if all
  conditions in this request mapping info match the provided request and
  returns a potentially new request mapping info with conditions
  tailored to the current request. For example the returned instance may
  contain the subset of URL patterns that match to the current request,
  sorted with best matching patterns on top.

Specified by:

getMatchingCondition in interface RequestCondition<RequestMappingInfo>

I didn't try this code , please can you check?

Exam:

private
@Autowired HttpServletRequest request;

@GetMapping
public void test(RequestMappingInfo requestMappingInfo, Authentication auth{
        assertEquals(requestMappingInfo, requestMappingInfo.getMatchingCondition(request));
}


问:
grep string when assigning variables
I have a file in a folder that needs to be removed in order to solve software conflicts.
I know that the folder path of the file is stored in a *.ini file and I want to grep that specific section of the line, have the script to cd into it and remove the offending file.

So far I've done:

```<code>#!/bin/bash
#

PROFFILE=$HOME/.mozilla/firefox/profiles.ini
DIRTEST=$HOME/.mozilla/firefox/

if [ -f $PROFFILE ]
        then
                echo "yes"
#               PROFPATH="$(cat $PROFFILE grep ^[[\s\S]*?(.default)$)"
                echo $PROFPATH

        else
                echo "no"
fi

#script ends here
#
#
</code>```

Im sure I'm doing something wrong with grep and regex by mixing them and not sure how to proceed.

This is an example of the ini file

```<code>Name=default
IsRelative=1
Path=l00jsdm9.default
Default=1
</code>```

答:
Use this:

```<code>PROFPATH=$( awk -F= '$1=="Path" {print $2}' $PROFFILE )
</code>```

or if you have many Path variables in file and need one that matches an expression:

```<code>PROFPATH=$( awk -F= '$1=="Path" && 2 ~ /default/ {print $2}' $PROFFILE )
</code>```

Title: grep string when assigning variables

Body:
I have a file in a folder that needs to be removed in order to solve software conflicts.
I know that the folder path of the file is stored in a *.ini file and I want to grep that specific section of the line, have the script to cd into it and remove the offending file.

So far I've done:

#!/bin/bash
#

PROFFILE=$HOME/.mozilla/firefox/profiles.ini
DIRTEST=$HOME/.mozilla/firefox/

if [ -f $PROFFILE ]
        then
                echo "yes"
#               PROFPATH="$(cat $PROFFILE grep ^[[\s\S]*?(.default)$)"
                echo $PROFPATH

        else
                echo "no"
fi

#script ends here
#
#

Im sure I'm doing something wrong with grep and regex by mixing them and not sure how to proceed.

This is an example of the ini file

Name=default
IsRelative=1
Path=l00jsdm9.default
Default=1

Body:
Use this:

PROFPATH=$( awk -F= '$1=="Path" {print $2}' $PROFFILE )

or if you have many Path variables in file and need one that matches an expression:

PROFPATH=$( awk -F= '$1=="Path" && 2 ~ /default/ {print $2}' $PROFFILE )


问:
Continuing in Python's unittest when an assertion fails
EDIT: switched to a better example, and clarified why this is a real problem.

I'd like to write unit tests in Python that continue executing when an assertion fails, so that I can see multiple failures in a single test. For example:

```<code>class Car(object):
  def __init__(self, make, model):
    self.make = make
    self.model = make  # Copy and paste error: should be model.
    self.has_seats = True
    self.wheel_count = 3  # Typo: should be 4.

class CarTest(unittest.TestCase):
  def test_init(self):
    make = "Ford"
    model = "Model T"
    car = Car(make=make, model=model)
    self.assertEqual(car.make, make)
    self.assertEqual(car.model, model)  # Failure!
    self.assertTrue(car.has_seats)
    self.assertEqual(car.wheel_count, 4)  # Failure!
</code>```

Here, the purpose of the test is to ensure that Car's __init__ sets its fields correctly. I could break it up into four methods (and that's often a great idea), but in this case I think it's more readable to keep it as a single method that tests a single concept ("the object is initialized correctly").

If we assume that it's best here to not break up the method, then I have a new problem: I can't see all of the errors at once. When I fix the model error and re-run the test, then the wheel_count error appears. It would save me time to see both errors when I first run the test.

For comparison, Google's C++ unit testing framework distinguishes between between non-fatal EXPECT_* assertions and fatal ASSERT_* assertions:

The assertions come in pairs that test the same thing but have different effects on the current function. ASSERT_* versions generate fatal failures when they fail, and abort the current function. EXPECT_* versions generate nonfatal failures, which don't abort the current function. Usually EXPECT_* are preferred, as they allow more than one failures to be reported in a test. However, you should use ASSERT_* if it doesn't make sense to continue when the assertion in question fails.

Is there a way to get EXPECT_*-like behavior in Python's unittest? If not in unittest, then is there another Python unit test framework that does support this behavior?

Incidentally, I was curious about how many real-life tests might benefit from non-fatal assertions, so I looked at some code examples (edited 2014-08-19 to use searchcode instead of Google Code Search, RIP). Out of 10 randomly selected results from the first page, all contained tests that made multiple independent assertions in the same test method. All would benefit from non-fatal assertions.

答:
I don't think there is a way to do this with PyUnit and wouldn't want to see PyUnit extended in this way.

I prefer to stick to one assertion per test function (or more specifically asserting one concept per test) and would rewrite test_addition() as four separate test functions. This would give more useful information on failure, viz:

```<code>.FF.
======================================================================
FAIL: test_addition_with_two_negatives (__main__.MathTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_addition.py", line 10, in test_addition_with_two_negatives
    self.assertEqual(-1 + (-1), -1)
AssertionError: -2 != -1

======================================================================
FAIL: test_addition_with_two_positives (__main__.MathTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_addition.py", line 6, in test_addition_with_two_positives
    self.assertEqual(1 + 1, 3)  # Failure!
AssertionError: 2 != 3

----------------------------------------------------------------------
Ran 4 tests in 0.000s

FAILED (failures=2)
</code>```

If you decide that this approach isn't for you, you may find this answer helpful.

Update

It looks like you are testing two concepts with your updated question and I would split these into two unit tests. The first being that the parameters are being stored on the creation of a new object. This would have two assertions, one for make and one for model. If the first fails, the that clearly needs to be fixed, whether the second passes or fails is irrelevant at this juncture.

The second concept is more questionable... You're testing whether some default values are initialised. Why? It would be more useful to test these values at the point that they are actually used (and if they are not used, then why are they there?).

Both of these tests fail, and both should. When I am unit-testing, I am far more interested in failure than I am in success as that is where I need to concentrate.

```<code>FF
======================================================================
FAIL: test_creation_defaults (__main__.CarTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_car.py", line 25, in test_creation_defaults
    self.assertEqual(self.car.wheel_count, 4)  # Failure!
AssertionError: 3 != 4

======================================================================
FAIL: test_creation_parameters (__main__.CarTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_car.py", line 20, in test_creation_parameters
    self.assertEqual(self.car.model, self.model)  # Failure!
AssertionError: 'Ford' != 'Model T'

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (failures=2)
</code>```

Body:
EDIT: switched to a better example, and clarified why this is a real problem.

I'd like to write unit tests in Python that continue executing when an assertion fails, so that I can see multiple failures in a single test. For example:

class Car(object):
  def __init__(self, make, model):
    self.make = make
    self.model = make  # Copy and paste error: should be model.
    self.has_seats = True
    self.wheel_count = 3  # Typo: should be 4.

class CarTest(unittest.TestCase):
  def test_init(self):
    make = "Ford"
    model = "Model T"
    car = Car(make=make, model=model)
    self.assertEqual(car.make, make)
    self.assertEqual(car.model, model)  # Failure!
    self.assertTrue(car.has_seats)
    self.assertEqual(car.wheel_count, 4)  # Failure!

Here, the purpose of the test is to ensure that Car's __init__ sets its fields correctly. I could break it up into four methods (and that's often a great idea), but in this case I think it's more readable to keep it as a single method that tests a single concept ("the object is initialized correctly").

If we assume that it's best here to not break up the method, then I have a new problem: I can't see all of the errors at once. When I fix the model error and re-run the test, then the wheel_count error appears. It would save me time to see both errors when I first run the test.

For comparison, Google's C++ unit testing framework distinguishes between between non-fatal EXPECT_* assertions and fatal ASSERT_* assertions:

The assertions come in pairs that test the same thing but have different effects on the current function. ASSERT_* versions generate fatal failures when they fail, and abort the current function. EXPECT_* versions generate nonfatal failures, which don't abort the current function. Usually EXPECT_* are preferred, as they allow more than one failures to be reported in a test. However, you should use ASSERT_* if it doesn't make sense to continue when the assertion in question fails.

Is there a way to get EXPECT_*-like behavior in Python's unittest? If not in unittest, then is there another Python unit test framework that does support this behavior?

Incidentally, I was curious about how many real-life tests might benefit from non-fatal assertions, so I looked at some code examples (edited 2014-08-19 to use searchcode instead of Google Code Search, RIP). Out of 10 randomly selected results from the first page, all contained tests that made multiple independent assertions in the same test method. All would benefit from non-fatal assertions.

Body:
I don't think there is a way to do this with PyUnit and wouldn't want to see PyUnit extended in this way.

I prefer to stick to one assertion per test function (or more specifically asserting one concept per test) and would rewrite test_addition() as four separate test functions. This would give more useful information on failure, viz:

.FF.
======================================================================
FAIL: test_addition_with_two_negatives (__main__.MathTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_addition.py", line 10, in test_addition_with_two_negatives
    self.assertEqual(-1 + (-1), -1)
AssertionError: -2 != -1

======================================================================
FAIL: test_addition_with_two_positives (__main__.MathTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_addition.py", line 6, in test_addition_with_two_positives
    self.assertEqual(1 + 1, 3)  # Failure!
AssertionError: 2 != 3

----------------------------------------------------------------------
Ran 4 tests in 0.000s

FAILED (failures=2)

If you decide that this approach isn't for you, you may find this answer helpful.

Update

It looks like you are testing two concepts with your updated question and I would split these into two unit tests. The first being that the parameters are being stored on the creation of a new object. This would have two assertions, one for make and one for model. If the first fails, the that clearly needs to be fixed, whether the second passes or fails is irrelevant at this juncture.

The second concept is more questionable... You're testing whether some default values are initialised. Why? It would be more useful to test these values at the point that they are actually used (and if they are not used, then why are they there?).

Both of these tests fail, and both should. When I am unit-testing, I am far more interested in failure than I am in success as that is where I need to concentrate.

FF
======================================================================
FAIL: test_creation_defaults (__main__.CarTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_car.py", line 25, in test_creation_defaults
    self.assertEqual(self.car.wheel_count, 4)  # Failure!
AssertionError: 3 != 4

======================================================================
FAIL: test_creation_parameters (__main__.CarTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_car.py", line 20, in test_creation_parameters
    self.assertEqual(self.car.model, self.model)  # Failure!
AssertionError: 'Ford' != 'Model T'

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (failures=2)


问:
why input type=date is different width to input type=text?
Within the same container input text with display: block stretches to fill available space as expected but if I change type to 'date' it becomes shorter. Why?

HTML:

```<code>  <div class="panel">
    <div class="input-group">
      <label for="text1">text1</label>
      <input id="text1" type="text"/>
    </div>
    <div class="input-group">
      <label for="date">date</label>
      <input id="date" type="date" />
    </div>
    <div class="input-group">
      <label for="text2">text2</label>
      <input id="text2" type="text" />
    </div>
  </div>
</code>```

CSS:

```<code>.panel {
    display: flex;
    flex-wrap: wrap;
}

.input-group {
    flex-grow: 1;
    text-align: left;
}

label, input {
  display: block;
}
</code>```

Result: text1 and text2 are the same size but date is shorter.

https://jsfiddle.net/e0v13ns3/

答:
Elements default width and height may differ from browser to another.

Specify the height and padding for the input element to make them all have the same height, and specify the width to make them all have the same width.

Give all the input elements a 100% width, and change the parent div width depending on your needs.

.panel {
    position: relative;
    display: flex;
    flex-wrap: wrap;
}

.input-group {
    flex-grow: 1;
    text-align: left;
    width: 30%;
    margin-right: 3%;
}

label, input {
  display: block;
  height: 20px;
  width: 100%;
  padding: 0;
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="panel">
    <div class="input-group">
      <label for="text1">text1</label>
      <input id="text1" type="text"/>
    </div>
    <div class="input-group">
      <label for="date">date</label>
      <input id="date" type="date" />
    </div>
    <div class="input-group">
      <label for="text2">text2</label>
      <input id="text2" type="text" />
    </div>
  </div></code>```

Body:
Within the same container input text with display: block stretches to fill available space as expected but if I change type to 'date' it becomes shorter. Why?

HTML:

      text1
      <input id="text1" type="text"/>

      date
      <input id="date" type="date" />

      text2
      <input id="text2" type="text" />

CSS:

.panel {
    display: flex;
    flex-wrap: wrap;
}

.input-group {
    flex-grow: 1;
    text-align: left;
}

label, input {
  display: block;
}

Result: text1 and text2 are the same size but date is shorter.

https://jsfiddle.net/e0v13ns3/

Body:
Elements default width and height may differ from browser to another.

Specify the height and padding for the input element to make them all have the same height, and specify the width to make them all have the same width.

Give all the input elements a 100% width, and change the parent div width depending on your needs.

.panel {
    position: relative;
    display: flex;
    flex-wrap: wrap;
}

.input-group {
    flex-grow: 1;
    text-align: left;
    width: 30%;
    margin-right: 3%;
}

label, input {
  display: block;
  height: 20px;
  width: 100%;
  padding: 0;
  margin: 0;
}

<div class="panel">
    <div class="input-group">
      <label for="text1">text1</label>
      <input id="text1" type="text"/>
    </div>
    <div class="input-group">
      <label for="date">date</label>
      <input id="date" type="date" />
    </div>
    <div class="input-group">
      <label for="text2">text2</label>
      <input id="text2" type="text" />
    </div>
  </div>


问:
Tkinter Python , Trying to load a string from a dictionary which is loaded from file
I have been coding this as a personal practice/test of Tkinter with python and I'm trying to load a file which contains a dictionary inside a dictionary and read that which shouldn't be the problem, however the problem is, that TempDict is not classed as defined.

I am also very sorry if some of the code is not indented properly it didn't copy and paste over very well so I had to make some corrections.

```<code>import tkinter as tk
from tkinter import *
from tkinter import ttk
import tkinter.messagebox as tm
import os
import pickle

class Quiz (tk.Tk):
    def __init__ (self, *args , **kwargs):

        tk.Tk.__init__(self, *args , **kwargs)
        tk.Tk.wm_title(self, "Quiz")

        container = tk.Frame (self)
        container.pack (side = "top" , fill = "both" , expand = True)
        container.grid_rowconfigure (0,weight = 1)
        container.grid_columnconfigure (0,weight = 1)

        self.frames = {}
        for F in (StartPage, Menu, Difficulty, QuestionsStart):

            frame = F(container, self)
            self.frames[F] = frame
            frame.grid (row = 0, column = 0 , sticky = "nsew")

        self.show_frame(StartPage)

    def show_frame(self,cont):

        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self,parent)
        label = tk.Label(self, text = "Login")
        label.pack(pady = 10 , padx = 10)

        global Username
        User = tk.Label (self, text = "Username")
        User.pack()

        Username = tk.Entry(self)
        Username.pack()
        Pass = tk.Label (self, text = "Password")
        Pass.pack()

        Password = tk.Entry (self, show = "*")
        Password.pack()

        button1 = ttk.Button(self, text = "Login",
                        command = lambda: Login(Username,Password,parent,controller,self) )
        button1.pack()

        button2 = ttk.Button(self, text = "Sign Up",
                        command = lambda: Signup())
        button2.pack()

class Menu(tk.Frame):

    def __init__ (self, parent, controller):

        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text = "Menu")
        label.pack()

        Label = tk.Label(self, text = "Please enter Maths or Chemsitry")
        Label.pack()

        Topic = tk.Entry(self)
        Topic.pack()

        Proceed = ttk.Button(self, text = "Proceed", command = lambda: controller.show_frame(Difficulty))
        Proceed.pack()

        Result = ttk.Button(self, text = "Results",
                       command = lambda: Results(controller))
        Result.pack()

        Logout = ttk.Button(self, text = "Log Out",
                        command = lambda: controller.show_frame(StartPage))
        Logout.pack()

class Difficulty(tk.Frame):

    def __init__ (self, parent, controller):

        tk.Frame.__init__(self,parent)
        label = tk.Label(self, text = "Difficulty")
        label.pack()

        Label = tk.Label(self, text = "Please enter Easy, Medium or Hard")
        Label.pack()

        DifficultyInput = tk.Entry(self)
        DifficultyInput.pack()

        StartQuiz = tk.Button(self , text = "Start Quiz", command = lambda: controller.show_frame(QuestionsStart))
        StartQuiz.pack()

        backtomenu = ttk.Button(self, text = "Back to Menu",
                           command = lambda: controller.show_frame(Menu))
        backtomenu.pack()

def DictFromFile ():
    TempDict = {}
    try:
        with open("Questions.txt" , "r") as file:
            TempDict = eval(file.read())
            file.close()
    except IOError as error:
        print (error)
    print(TempDict)
    return TempDict

DictFromFile()

def QuizType(Topic, DifficultyInput):

    QuizSelection = str(Topic.get().lower() + DifficultyInput.get().lower())
    return QuizSelection

class QuestionsStart (tk.Frame):
    def __init__(self , parent, controller):

        tk.Frame.__init__(self,parent)
        Label = tk.Label(self, text = DictFromFile(TempDict[QuizSelection(Topic, DifficultyInput)]["Question1"]))
        Label.pack()

def Login(Username,Password,parent,controller,self):

    Usernames = []
    Login = True
    Username = Username.get()
    Password = Password.get()

    try:

        with open ("Usernames&Passwords.txt" , "rb" ) as file:
            for each in pickle.load(file):
                Usernames.append(each.strip("\n"))
            file.close()

    except IOError as error:
        print (error)

    for each in range(len(Usernames)):
        if Usernames[each] == Username :
            if Usernames[each + 1] == Password:
                Login = True
                controller.show_frame(Menu)
                break
            else:
                Login = False
        else:
           Login = False
    if Login == False:
        tm.showinfo("Your Username or Password is incorrect" , "Your Usename or Password is incorrect")

def Results (controller):

    UsersResults = []
    Counter = 0
    Topic = []
    Difficulty = []
    Mark = []
    Percentage = []
    Grade = []

    try:
        with open(Username.get() + ".txt" , "r" , encoding = "UTF-8") as file:
            for each in file:
                UsersResults.append(each.strip("\n"))

    except IOError as error:
        print(error)
    print (UsersResults)
    print (Counter)
    for each in range (len(UsersResults)):
        Topic = UsersResults[Counter]
        Difficulty = UsersResults[Counter + 1]
        Mark = UsersResults[Counter + 2]
        Percentage = UsersResults[Counter + 3]
        Grade = UsersResults[Counter + 4]
        Counter += 5

    return UsersResults

app = Quiz()
app.geometry ("500x300")
app.mainloop()
</code>```

答:
You use DictFromFile() in wrong way in

```<code>tk.Label(self, text=DictFromFile(TempDict[QuizSelection(Topic, DifficultyInput)]["Question1"])
</code>```

You can't run DictFromFile() with arguments.

It returns dictionary which you have to assing to variable and then you can get question.

It should be something like

```<code>temp_dict = DictFromFile()

question = temp_dict[QuizSelection(Topic, DifficultyInput)]["Question1"]

tk.Label(self, text=question)
</code>```

Now you have dictionary TempDict in variable temp_dict.

But I see other problem - you use other variables which doesn't exists in this place - QuizSelection, Topic, DifficultyInput.

They exists as local variables in other functions and you can't use it like global variables.

You can get QuizSelection from function QuizType()

```<code>quiz_selection = QuizType(Topic, DifficultyInput)
question = temp_dict[quiz_selection]["Question1"]
</code>```

but still you don't have access to variables Topic, DifficultyInput.

It looks like you don't know how to use functions.

You have to learn how to use self. in classes, too.

Body:
I have been coding this as a personal practice/test of Tkinter with python and I'm trying to load a file which contains a dictionary inside a dictionary and read that which shouldn't be the problem, however the problem is, that TempDict is not classed as defined.

I am also very sorry if some of the code is not indented properly it didn't copy and paste over very well so I had to make some corrections.

import tkinter as tk
from tkinter import *
from tkinter import ttk
import tkinter.messagebox as tm
import os
import pickle

class Quiz (tk.Tk):
    def __init__ (self, *args , **kwargs):

        tk.Tk.__init__(self, *args , **kwargs)
        tk.Tk.wm_title(self, "Quiz")

        container = tk.Frame (self)
        container.pack (side = "top" , fill = "both" , expand = True)
        container.grid_rowconfigure (0,weight = 1)
        container.grid_columnconfigure (0,weight = 1)

        self.frames = {}
        for F in (StartPage, Menu, Difficulty, QuestionsStart):

            frame = F(container, self)
            self.frames[F] = frame
            frame.grid (row = 0, column = 0 , sticky = "nsew")

        self.show_frame(StartPage)

    def show_frame(self,cont):

        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self,parent)
        label = tk.Label(self, text = "Login")
        label.pack(pady = 10 , padx = 10)

        global Username
        User = tk.Label (self, text = "Username")
        User.pack()

        Username = tk.Entry(self)
        Username.pack()
        Pass = tk.Label (self, text = "Password")
        Pass.pack()

        Password = tk.Entry (self, show = "*")
        Password.pack()

        button1 = ttk.Button(self, text = "Login",
                        command = lambda: Login(Username,Password,parent,controller,self) )
        button1.pack()

        button2 = ttk.Button(self, text = "Sign Up",
                        command = lambda: Signup())
        button2.pack()

class Menu(tk.Frame):

    def __init__ (self, parent, controller):

        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text = "Menu")
        label.pack()

        Label = tk.Label(self, text = "Please enter Maths or Chemsitry")
        Label.pack()

        Topic = tk.Entry(self)
        Topic.pack()

        Proceed = ttk.Button(self, text = "Proceed", command = lambda: controller.show_frame(Difficulty))
        Proceed.pack()

        Result = ttk.Button(self, text = "Results",
                       command = lambda: Results(controller))
        Result.pack()

        Logout = ttk.Button(self, text = "Log Out",
                        command = lambda: controller.show_frame(StartPage))
        Logout.pack()

class Difficulty(tk.Frame):

    def __init__ (self, parent, controller):

        tk.Frame.__init__(self,parent)
        label = tk.Label(self, text = "Difficulty")
        label.pack()

        Label = tk.Label(self, text = "Please enter Easy, Medium or Hard")
        Label.pack()

        DifficultyInput = tk.Entry(self)
        DifficultyInput.pack()

        StartQuiz = tk.Button(self , text = "Start Quiz", command = lambda: controller.show_frame(QuestionsStart))
        StartQuiz.pack()

        backtomenu = ttk.Button(self, text = "Back to Menu",
                           command = lambda: controller.show_frame(Menu))
        backtomenu.pack()

def DictFromFile ():
    TempDict = {}
    try:
        with open("Questions.txt" , "r") as file:
            TempDict = eval(file.read())
            file.close()
    except IOError as error:
        print (error)
    print(TempDict)
    return TempDict

DictFromFile()

def QuizType(Topic, DifficultyInput):

    QuizSelection = str(Topic.get().lower() + DifficultyInput.get().lower())
    return QuizSelection

class QuestionsStart (tk.Frame):
    def __init__(self , parent, controller):

        tk.Frame.__init__(self,parent)
        Label = tk.Label(self, text = DictFromFile(TempDict[QuizSelection(Topic, DifficultyInput)]["Question1"]))
        Label.pack()

def Login(Username,Password,parent,controller,self):

    Usernames = []
    Login = True
    Username = Username.get()
    Password = Password.get()

    try:

        with open ("Usernames&Passwords.txt" , "rb" ) as file:
            for each in pickle.load(file):
                Usernames.append(each.strip("\n"))
            file.close()

    except IOError as error:
        print (error)

    for each in range(len(Usernames)):
        if Usernames[each] == Username :
            if Usernames[each + 1] == Password:
                Login = True
                controller.show_frame(Menu)
                break
            else:
                Login = False
        else:
           Login = False
    if Login == False:
        tm.showinfo("Your Username or Password is incorrect" , "Your Usename or Password is incorrect")

def Results (controller):

    UsersResults = []
    Counter = 0
    Topic = []
    Difficulty = []
    Mark = []
    Percentage = []
    Grade = []

    try:
        with open(Username.get() + ".txt" , "r" , encoding = "UTF-8") as file:
            for each in file:
                UsersResults.append(each.strip("\n"))

    except IOError as error:
        print(error)
    print (UsersResults)
    print (Counter)
    for each in range (len(UsersResults)):
        Topic = UsersResults[Counter]
        Difficulty = UsersResults[Counter + 1]
        Mark = UsersResults[Counter + 2]
        Percentage = UsersResults[Counter + 3]
        Grade = UsersResults[Counter + 4]
        Counter += 5

    return UsersResults

app = Quiz()
app.geometry ("500x300")
app.mainloop()

Body:
You use DictFromFile() in wrong way in

tk.Label(self, text=DictFromFile(TempDict[QuizSelection(Topic, DifficultyInput)]["Question1"])

You can't run DictFromFile() with arguments.

It returns dictionary which you have to assing to variable and then you can get question.

It should be something like

temp_dict = DictFromFile()

question = temp_dict[QuizSelection(Topic, DifficultyInput)]["Question1"]

tk.Label(self, text=question)

Now you have dictionary TempDict in variable temp_dict.

But I see other problem - you use other variables which doesn't exists in this place - QuizSelection, Topic, DifficultyInput.

They exists as local variables in other functions and you can't use it like global variables.

You can get QuizSelection from function QuizType()

quiz_selection = QuizType(Topic, DifficultyInput)
question = temp_dict[quiz_selection]["Question1"]

but still you don't have access to variables Topic, DifficultyInput.

It looks like you don't know how to use functions.

You have to learn how to use self. in classes, too.


问:
Change JS Show/hide to reorder
I have some perfectly working javascript here:

```<code><script type="text/javascript">
$(function(){

$('#filterText').on('change', function() {
  var currentVal = $(this).val();
  console.log(currentVal)

  $(".group-container").show();
  if (currentVal == 'popularity') {
  $('.group-container input[name="topseller"]').each(function (index, value){
  if($(this).val() == "0"){
        $(this).parent('.group-container').hide();
        //console.log(currentVal)
    }
    });
  } else if (currentVal == 'recently_ordered') {
    $('.group-container input[name="reorder"]').each(function (index, value){

        if($(this).val() == "0"){
                $(this).parent('.group-container').hide();
                // console.log(currentVal)
            }
      });
  }
});
});

</script>
</code>```

However, I'd like to change one thing. Currently, it checks the value of the select box and a hidden input name, and it then hides the divs containing the inputs with value of 0 and shows the ones with value of 1.

I want to just slightly refactor this to, rather than hide the div, just reorder them and basically show the divs that have input value of 1 first and the value of 0 last. SO no hide/show but rather just give the one's with value of 1 priority at top of the page. I'm thinking this should be a very minor change in my show/hide script, but don't know exactly how I should go about it.

UPDATE with HTML

```<code><div>
   <span style="color:#fff;"><strong>Sort by:</strong></span>
        <select id="filterText" class="uk-text-muted" style="margin-top:10px; width:33%; height:30px; font-size: 16px;" >
        <option id="allitems" class="uk-text-muted" style="font-size: 16px;" selected data-default value="" selected data-default>All Items</option>
                                      file
        <option id="recent" class="uk-text-muted" style="font-size: 16px;" value="recently_ordered">Recently Ordered </option>
       </select>
    </div>

@foreach ($orderFormData->pgroups as $pgroup)
<div class="group-container">
        <!-- <input type='hidden' name='search' value='{{ x.search }}' > -->
        <input type="hidden" name="topseller" value="{{$pgroup->topseller}}" />
        <input type="hidden" name="reorder" value="{{$pgroup->reorder}}"/>
</code>```

答:
try $(this).append($('.group-container'))
instead of $(this).parent('.group-container').hide();

look here for more details.

Title: Change JS Show/hide to reorder

Body:
I have some perfectly working javascript here:

However, I'd like to change one thing. Currently, it checks the value of the select box and a hidden input name, and it then hides the divs containing the inputs with value of 0 and shows the ones with value of 1.

I want to just slightly refactor this to, rather than hide the div, just reorder them and basically show the divs that have input value of 1 first and the value of 0 last. SO no hide/show but rather just give the one's with value of 1 priority at top of the page. I'm thinking this should be a very minor change in my show/hide script, but don't know exactly how I should go about it.

UPDATE with HTML

   Sort by:
        <select id="filterText" class="uk-text-muted" style="margin-top:10px; width:33%; height:30px; font-size: 16px;" >
        <option id="allitems" class="uk-text-muted" style="font-size: 16px;" selected data-default value="" selected data-default>All Items</option>
                                      file
        <option id="recent" class="uk-text-muted" style="font-size: 16px;" value="recently_ordered">Recently Ordered </option>
       </select>

@foreach ($orderFormData->pgroups as $pgroup)

        <input type="hidden" name="topseller" value="{{$pgroup->topseller}}" />
        <input type="hidden" name="reorder" value="{{$pgroup->reorder}}"/>


问:
Sort Events by Start Date
I need to be able to get the events in both directions ASC/DESC using Microsoft Graph API. I'm trying the following API to achieve that:

```<code>https://graph.microsoft.com/v1.0/me/events?$orderby=start
</code>```

However, when I perform the request I get the following error:

{
    "error": {
        "code": "BadRequest",
        "message": "The $orderby expression must evaluate to a single value of primitive type.",
        "innerError": {
            "request-id": "c00d676d-ef8e-418b-8561-80e08729da71",
            "date": "2017-11-16T13:31:59"
        }
    }
}
```

<p>Also, I tried to access the date directly:</p>

```https://graph.microsoft.com/v1.0/me/events?$orderby=start.dateTime
```

<p>Got the following error:</p>

<pre class="lang-json prettyprint-override"><code>{
    "error": {
        "code": "BadRequest",
        "message": "The child type 'start.dateTime' in a cast was not an entity type. Casts can only be performed on entity types.",
        "innerError": {
            "request-id": "240342f5-d7f6-430b-9bd0-190dc3e1f73b",
            "date": "2017-11-16T13:32:39"
        }
    }
}
</code>```

Is there a way to sort events by date in ASC/DESC order?

答:
You're very close but you're referencing DateTime incorrectly. The proper format is {parent}/{child}. These will work:

```<code>https://graph.microsoft.com/v1.0/me/events?$orderby=start/dateTime
https://graph.microsoft.com/v1.0/me/events?$orderby=start/dateTime desc
</code>```

Title: Sort Events by Start Date

Body:
I need to be able to get the events in both directions ASC/DESC using Microsoft Graph API. I'm trying the following API to achieve that:

https://graph.microsoft.com/v1.0/me/events?$orderby=start

However, when I perform the request I get the following error:

{
    "error": {
        "code": "BadRequest",
        "message": "The $orderby expression must evaluate to a single value of primitive type.",
        "innerError": {
            "request-id": "c00d676d-ef8e-418b-8561-80e08729da71",
            "date": "2017-11-16T13:31:59"
        }
    }
}

Also, I tried to access the date directly:

https://graph.microsoft.com/v1.0/me/events?$orderby=start.dateTime

Got the following error:

{
    "error": {
        "code": "BadRequest",
        "message": "The child type 'start.dateTime' in a cast was not an entity type. Casts can only be performed on entity types.",
        "innerError": {
            "request-id": "240342f5-d7f6-430b-9bd0-190dc3e1f73b",
            "date": "2017-11-16T13:32:39"
        }
    }
}

Is there a way to sort events by date in ASC/DESC order?

Body:
You're very close but you're referencing DateTime incorrectly. The proper format is {parent}/{child}. These will work:

https://graph.microsoft.com/v1.0/me/events?$orderby=start/dateTime
https://graph.microsoft.com/v1.0/me/events?$orderby=start/dateTime desc


问:
Hiding a div if a value is under 1
I want the application to behave this way so that when I click on "Show Order" if any of the values are 0 or blank, I don't want div id item * x be shown:

var divs = document.getElementsByTagName('div');

var toggle = function() {
  for (var i = 0, l = divs.length; i < l; i++) {
    if (divs[i].getAttribute('class') == 'problem')
      if (divs[i].style.display == 'none') divs[i].style.display = '';
      else divs[i].style.display = 'none';
    var x = document.getElementById("mySelect").value;
    var y = document.getElementById("item1").value;
    if (x < 1) {
      y.style.display === "none"
    } else {
      document.getElementById("demo").innerHTML = x;
    }
    var x = document.getElementById("mySelect1").value;
    document.getElementById("demo1").innerHTML = x;
    var x = document.getElementById("mySelect2").value;
    document.getElementById("demo2").innerHTML = x;
  }
}

document.getElementById('Toggle').onclick = toggle;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="problem">
  <div class="row">
    <div class="col-3">
      <form>
        <input type="number" id="mySelect" name="mySelect" autocomplete="off" style="width: 3em;"> Sausage
        <br>
      </form>
    </div>
    <div class="col-3">
      <form>
        <input type="number" id="mySelect1" name="mySelect1" autocomplete="off" style="width: 3em;"> Pancake
        <br>
      </form>
    </div>
    <div class="col-2">
      <form>
        <input type="number" id="mySelect2" name="mySelect2" autocomplete="off" style="width: 3em;"> Milk
      </form>
    </div>
    <div class="col-4">
    </div>
  </div>

  <div class="row">
    <div class="col-12">
      <p>
        <button type="button" class="button" id="Toggle" onclick="myFunction()">Show Order</button>
      </p>
    </div>
  </div>

</div>

<div class="row">
  <div class="col-12">
    <div style="display:none;" class="problem">Please show this to the cashier.</div>

    <div style="display:none;" class="problem">
      <h2>Hello, they ordered:</h2>
    </div>
    <div id="item1" style="display:none;" class="problem">
      <h2><span style="font-size: xx-large; color: green;" id="demo"></span>x Sausage(s)</h2>
    </div>
    <div id="item2" style="display:none;" class="problem">
      <h2><span style="font-size: xx-large; color: green;" id="demo1"></span>x Pancake(s)</h2>
    </div>
    <div id="item3" style="display:none;" class="problem">
      <h2><span style="font-size: xx-large; color: green;" id="demo2"></span>x Cup of Milk(s)</h2>
    </div>
    <div style="display:none;" class="problem">
      <h2>Thank you</h2>
    </div>

    <div style="display:none;" class="problem">Please refresh your browser to restart your order</div>
  </div>
</div></code>```

I have added my full code from JSFiddle here.

答:
Check this simpler approach

Give a display class to div to be div to be toggled

Check for any input values to be >= 1

Demo

var toggle = function() {
  var x1 = Number(document.getElementById("mySelect").value);
  var x2 = Number(document.getElementById("mySelect1").value);
  var x3 = Number(document.getElementById("mySelect2").value);
  document.querySelectorAll(".display .problem").forEach(function(el) {
    el.style.display = x1 >= 1 || x2 >= 1 || x3 >= 1 ? "block" : "none";
  });
  document.getElementById("demo").innerHTML = (x1 || 0);
  document.getElementById("demo1").innerHTML = (x2 || 0);
  document.getElementById("demo2").innerHTML = (x3 || 0);
}

document.getElementById('Toggle').onclick = toggle;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="problem">
  <div class="row">
    <div class="col-3">
      <form>
        <input type="number" id="mySelect" name="mySelect" autocomplete="off" style="width: 3em;"> Sausage
        <br>
      </form>
    </div>
    <div class="col-3">
      <form>
        <input type="number" id="mySelect1" name="mySelect1" autocomplete="off" style="width: 3em;"> Pancake
        <br>
      </form>
    </div>
    <div class="col-2">
      <form>
        <input type="number" id="mySelect2" name="mySelect2" autocomplete="off" style="width: 3em;"> Milk
      </form>
    </div>

    <div class="col-4">
    </div>
  </div>

  <div class="row">
    <div class="col-12">
      <p>
        <button type="button" class="button" id="Toggle" onclick="myFunction()">Show Order</button>
      </p>
    </div>
  </div>

</div>

<div class="row display">
  <div class="col-12">
    <div style="display:none;" class="problem">Please show this to the cashier.</div>

    <div style="display:none;" class="problem">
      <h2>Hello, they ordered:</h2>
    </div>
    <div id="item1" style="display:none;" class="problem">
      <h2><span style="font-size: xx-large; color: green;" id="demo"></span>x Sausage(s)</h2>
    </div>
    <div id="item2" style="display:none;" class="problem">
      <h2><span style="font-size: xx-large; color: green;" id="demo1"></span>x Pancake(s)</h2>
    </div>
    <div id="item3" style="display:none;" class="problem">
      <h2><span style="font-size: xx-large; color: green;" id="demo2"></span>x Cup of Milk(s)</h2>
    </div>
    <div style="display:none;" class="problem">
      <h2>Thank you</h2>
    </div>

    <div style="display:none;" class="problem">Please refresh your browser to restart your order</div>
  </div>
</div></code>```

Title: Hiding a div if a value is under 1

Body:
I want the application to behave this way so that when I click on "Show Order" if any of the values are 0 or blank, I don't want div id item * x be shown:

var divs = document.getElementsByTagName('div');

var toggle = function() {
  for (var i = 0, l = divs.length; i < l; i++) {
    if (divs[i].getAttribute('class') == 'problem')
      if (divs[i].style.display == 'none') divs[i].style.display = '';
      else divs[i].style.display = 'none';
    var x = document.getElementById("mySelect").value;
    var y = document.getElementById("item1").value;
    if (x < 1) {
      y.style.display === "none"
    } else {
      document.getElementById("demo").innerHTML = x;
    }
    var x = document.getElementById("mySelect1").value;
    document.getElementById("demo1").innerHTML = x;
    var x = document.getElementById("mySelect2").value;
    document.getElementById("demo2").innerHTML = x;
  }
}

document.getElementById('Toggle').onclick = toggle;

      <form>
        <input type="number" id="mySelect" name="mySelect" autocomplete="off" style="width: 3em;"> Sausage

      </form>

      <form>
        <input type="number" id="mySelect1" name="mySelect1" autocomplete="off" style="width: 3em;"> Pancake

      </form>

      <form>
        <input type="number" id="mySelect2" name="mySelect2" autocomplete="off" style="width: 3em;"> Milk
      </form>

        <button type="button" class="button" id="Toggle" onclick="myFunction()">Show Order</button>

Please show this to the cashier.

Hello, they ordered:

x Sausage(s)

x Pancake(s)

x Cup of Milk(s)

Thank you

Please refresh your browser to restart your order

I have added my full code from JSFiddle here.

Body:
Check this simpler approach

Give a display class to div to be div to be toggled

Check for any input values to be >= 1

Demo

var toggle = function() {
  var x1 = Number(document.getElementById("mySelect").value);
  var x2 = Number(document.getElementById("mySelect1").value);
  var x3 = Number(document.getElementById("mySelect2").value);
  document.querySelectorAll(".display .problem").forEach(function(el) {
    el.style.display = x1 >= 1 || x2 >= 1 || x3 >= 1 ? "block" : "none";
  });
  document.getElementById("demo").innerHTML = (x1 || 0);
  document.getElementById("demo1").innerHTML = (x2 || 0);
  document.getElementById("demo2").innerHTML = (x3 || 0);
}

document.getElementById('Toggle').onclick = toggle;

<div class="problem">
  <div class="row">
    <div class="col-3">
      <form>
        <input type="number" id="mySelect" name="mySelect" autocomplete="off" style="width: 3em;"> Sausage
        <br>
      </form>
    </div>
    <div class="col-3">
      <form>
        <input type="number" id="mySelect1" name="mySelect1" autocomplete="off" style="width: 3em;"> Pancake
        <br>
      </form>
    </div>
    <div class="col-2">
      <form>
        <input type="number" id="mySelect2" name="mySelect2" autocomplete="off" style="width: 3em;"> Milk
      </form>
    </div>

    <div class="col-4">
    </div>
  </div>

  <div class="row">
    <div class="col-12">
      <p>
        <button type="button" class="button" id="Toggle" onclick="myFunction()">Show Order</button>
      </p>
    </div>
  </div>

</div>

<div class="row display">
  <div class="col-12">
    <div style="display:none;" class="problem">Please show this to the cashier.</div>

    <div style="display:none;" class="problem">
      <h2>Hello, they ordered:</h2>
    </div>
    <div id="item1" style="display:none;" class="problem">
      <h2><span style="font-size: xx-large; color: green;" id="demo"></span>x&nbsp;Sausage(s)</h2>
    </div>
    <div id="item2" style="display:none;" class="problem">
      <h2><span style="font-size: xx-large; color: green;" id="demo1"></span>x&nbsp;Pancake(s)</h2>
    </div>
    <div id="item3" style="display:none;" class="problem">
      <h2><span style="font-size: xx-large; color: green;" id="demo2"></span>x&nbsp;Cup of Milk(s)</h2>
    </div>
    <div style="display:none;" class="problem">
      <h2>Thank you</h2>
    </div>

    <div style="display:none;" class="problem">Please refresh your browser to restart your order</div>
  </div>
</div>


问:
error: unpacking of archive failed: cpio: Bad magic when installing an rpm
I packaged an rpm using

```<code>  make package
</code>```

command, and copied the resulting rpm to another machine which has a company specific OS. Now when I try to install the rpm using

```<code>  rpm --nodeps -i filename.rpm
</code>```

I get the error the same as the one in the title.

So I ran

```<code>  rpm -qa | grep rpm
</code>```

on the machine used to build the rpm package, and got this:

```<code>  rpm-4.8.0-37.el6.x86_64
  rpm-devel-4.8.0-37.el6.x86_64
  rpm-python-4.8.0-37.el6.x86_64
  rpm-libs-4.8.0-37.el6.x86_64
  rpm-build-4.8.0-37.el6.x86_64
  redhat-rpm-config-9.0.3-51.el6.noarch
</code>```

After a bit of investigation, I tried removing the redhat-rpm-config package and bam, rpm installation worked on the other machine. Now, this is a solution and all but I don't think I can just uninstall this package for every machine that we're going to use in creating the rpm. Is there any other way to ignore this redhat-rpm-config-9.0.3-51.el6.noarch when creating an rpm package using cmake?

答:
To solve "error: unpacking of archive failed: cpio: Bad magic" issue at RPM package installation on your machine:

1/ List rpm pkgs which are installed on the server machine (the machine on which the rpm pkg is generated):
   $ rpm -qa | grep rpm
                 ….
                 ….
2/ If pkg redhat-rpm-config-9.0.3-51.el6.noarch is present in the given list,  desinstall it:

```<code>$ rpm -e redhat-rpm-config-9.0.3-51.el6.noarch
</code>```

3/ Generate now the pkg and tranfer it on your dev machine. Pkg installation should work.

```<code> Philippe.
</code>```

Body:
I packaged an rpm using

  make package

command, and copied the resulting rpm to another machine which has a company specific OS. Now when I try to install the rpm using

  rpm --nodeps -i filename.rpm

I get the error the same as the one in the title.

So I ran

  rpm -qa | grep rpm

on the machine used to build the rpm package, and got this:

  rpm-4.8.0-37.el6.x86_64
  rpm-devel-4.8.0-37.el6.x86_64
  rpm-python-4.8.0-37.el6.x86_64
  rpm-libs-4.8.0-37.el6.x86_64
  rpm-build-4.8.0-37.el6.x86_64
  redhat-rpm-config-9.0.3-51.el6.noarch

After a bit of investigation, I tried removing the redhat-rpm-config package and bam, rpm installation worked on the other machine. Now, this is a solution and all but I don't think I can just uninstall this package for every machine that we're going to use in creating the rpm. Is there any other way to ignore this redhat-rpm-config-9.0.3-51.el6.noarch when creating an rpm package using cmake?

Body:
To solve "error: unpacking of archive failed: cpio: Bad magic" issue at RPM package installation on your machine:

1/ List rpm pkgs which are installed on the server machine (the machine on which the rpm pkg is generated):
   $ rpm -qa | grep rpm
                 ….
                 ….
2/ If pkg redhat-rpm-config-9.0.3-51.el6.noarch is present in the given list,  desinstall it:

$ rpm -e redhat-rpm-config-9.0.3-51.el6.noarch

3/ Generate now the pkg and tranfer it on your dev machine. Pkg installation should work.

 Philippe.


问:
Formatting Floating Point Numbers
I have a variable of type double, I need to print it in upto 3 decimals of precision but it shouldn't have any trailing zeros...

eg. I need

```<code>2.5 // not 2.500
2   // not 2.000
1.375 // exactly till 3 decimals
2.12  // not 2.120
</code>```

I tried using DecimalFormatter, Am i doing it wrong?

```<code>DecimalFormat myFormatter = new DecimalFormat("0.000");
myFormatter.setDecimalSeparatorAlwaysShown(false);
</code>```

Thanks. :)

答:
Your solution is almost correct, but you should replace zeros '0' in decimal format pattern by hashes "#".

So it should look like this:

```<code>DecimalFormat myFormatter = new DecimalFormat("#.###");
</code>```

And that line is not necesary (as decimalSeparatorAlwaysShown is false by default):

```<code>myFormatter.setDecimalSeparatorAlwaysShown(false);
</code>```

Here is short summary from javadocs:

```<code>Symbol  Location    Localized?  Meaning
0   Number  Yes Digit
#   Number  Yes Digit, zero shows as absent
</code>```

And the link to javadoc: DecimalFormat

Title: Formatting Floating Point Numbers

Body:
I have a variable of type double, I need to print it in upto 3 decimals of precision but it shouldn't have any trailing zeros...

eg. I need

2.5 // not 2.500
2   // not 2.000
1.375 // exactly till 3 decimals
2.12  // not 2.120

I tried using DecimalFormatter, Am i doing it wrong?

DecimalFormat myFormatter = new DecimalFormat("0.000");
myFormatter.setDecimalSeparatorAlwaysShown(false);

Thanks. :)

Body:
Your solution is almost correct, but you should replace zeros '0' in decimal format pattern by hashes "#".

So it should look like this:

DecimalFormat myFormatter = new DecimalFormat("#.###");

And that line is not necesary (as decimalSeparatorAlwaysShown is false by default):

myFormatter.setDecimalSeparatorAlwaysShown(false);

Here is short summary from javadocs:

Symbol  Location    Localized?  Meaning
0   Number  Yes Digit
#   Number  Yes Digit, zero shows as absent

And the link to javadoc: DecimalFormat


问:
What does axis in pandas mean?
Here is my code to generate a dataframe:

```<code>import pandas as pd
import numpy as np

dff = pd.DataFrame(np.random.randn(1,2),columns=list('AB'))
</code>```

then I got the dataframe:

```<code>+------------+---------+--------+
|            |  A      |  B     |
+------------+---------+---------
|      0     | 0.626386| 1.52325|
+------------+---------+--------+
</code>```

When I type the commmand :

```<code>dff.mean(axis=1)
</code>```

I got :

```<code>0    1.074821
dtype: float64
</code>```

According to the reference of pandas, axis=1 stands for columns and I expect the result of the command to be

```<code>A    0.626386
B    1.523255
dtype: float64
</code>```

So here is my question: what does axis in pandas mean?

答:
axis = 0 means up to down
axis = 1 means left to right

```<code>sums[key] = lang_sets[key].iloc[:,1:].sum(axis=0)
</code>```

Given example is taking sum of all the data in column == key.

Title: What does axis in pandas mean?

Body:
Here is my code to generate a dataframe:

import pandas as pd
import numpy as np

dff = pd.DataFrame(np.random.randn(1,2),columns=list('AB'))

then I got the dataframe:

+------------+---------+--------+
|            |  A      |  B     |
+------------+---------+---------
|      0     | 0.626386| 1.52325|
+------------+---------+--------+

When I type the commmand :

dff.mean(axis=1)

I got :

0    1.074821
dtype: float64

According to the reference of pandas, axis=1 stands for columns and I expect the result of the command to be

A    0.626386
B    1.523255
dtype: float64

So here is my question: what does axis in pandas mean?

Body:
axis = 0 means up to down
axis = 1 means left to right

sums[key] = lang_sets[key].iloc[:,1:].sum(axis=0)

Given example is taking sum of all the data in column == key.


问:
Changing urls in visual composer's raw html block
Visual Composer saves the raw HTML block as a base64 encoded (and url encoded) string in the database. My site needs to go from http to https, and I would need to change asset URL's used in these raw HTML blocks to be served with https. Clearly the Wordpress search/replace tool won't work here.

Does anybody know a solution for this?

答: use https://wordpress.org/plugins/velvet-blues-update-urls/ and update the url from admin panel this will change all the Urls in the site either in content or url links.</p>


问:
Spring Boot microservice response issue with Angular 2 http call
I am trying to call a GET request from my Angular 2 front-end app to a Spring Boot REST microservice, But when I calling, I am getting error like:

No Access-Control-Allow-Origin header is present on the requested resource

Here is my controller actions:

```<code>@RequestMapping(value = "/checkUsers", method = RequestMethod.POST)
public String checkLogin(@RequestBody Users user) throws Exception{

    ObjectMapper mapper = new ObjectMapper();
    List<Users> useObj = (List<Users>) userRepo.findAll();
    return(mapper.writeValueAsString(useObj));
}
</code>```

And when I am running my Angular, I am getting the above error. I added its screenshot

Is this from an Angular problem or from a Spring Boot microservice response problem?

答:
Since they are running on different ports, you have to allow Cross-origin resource sharing (CORS) on server side.
In spring boot you can do that by adding @CrossOrigin annotation to the handler method:

```<code>@CrossOrigin(origins = "http://localhost:4200")
</code>```

It is also possible to add this annotation at controller class level as well, in order to enable CORS on all handler methods of that class.

Body:
I am trying to call a GET request from my Angular 2 front-end app to a Spring Boot REST microservice, But when I calling, I am getting error like:

No Access-Control-Allow-Origin header is present on the requested resource

Here is my controller actions:

@RequestMapping(value = "/checkUsers", method = RequestMethod.POST)
public String checkLogin(@RequestBody Users user) throws Exception{

    ObjectMapper mapper = new ObjectMapper();
    List<Users> useObj = (List<Users>) userRepo.findAll();
    return(mapper.writeValueAsString(useObj));
}

And when I am running my Angular, I am getting the above error. I added its screenshot

Is this from an Angular problem or from a Spring Boot microservice response problem?

Body:
Since they are running on different ports, you have to allow Cross-origin resource sharing (CORS) on server side.
In spring boot you can do that by adding @CrossOrigin annotation to the handler method:

@CrossOrigin(origins = "http://localhost:4200")

It is also possible to add this annotation at controller class level as well, in order to enable CORS on all handler methods of that class.


问:
C compile error: Id returned 1 exit status
For some reason, when I try compiling a program, the compiler says permission denied and Id returned 1 exit status.  Could anyone tell me what that means? Thank you

```<code>#include <stdio.h>                                               /* Library inclusions */
#include "genlib.h"
#include "simpio.h"

int binSearch(int val, int numbers[], int size1);                /* prototypes */
void sortArray (int numbers[], int size1);
int indexMax (int numbers[], int low, int high);
void swap (int numbers[], int loc, int loc1);
void getArray (int numbers[], int size1);
void displayArray (int numbers[], int size1);

main()
{
  int value, size1;

  printf("Enter the number of elements: ");
  size1=GetInteger();
  int numbers[size1];
  getArray(numbers, size1);
  sortArray(numbers, size1);
  displayArray(numbers, size1);
  printf("\nEnter value to find: ");
  value=GetInteger();
  binSearch(value, numbers, size1);
  getchar();
}

void sortArray (int numbers[], int size1)                        /*Function sortArray*/
{
 int i , maxInd;

 for (i= size1-1; i>=0;i--)
 {
     maxInd=indexMax(numbers, 0, i);
     swap (numbers, i, maxInd);
 }
}

void displayArray (int numbers[], int size1)                     /*Function displayArray*/
{
 int i;

 printf("This is the sorted set of numbers: \n");
 for (i=0; i< size1; i++)
 {
         printf ("%d\t", numbers[i]);
     }
}

void getArray (int numbers[], int size1)                         /*Function getArray*/
{
 int i;

 for (i=0; i<size1; i++)
 {
     printf ("Enter the values of the %d elements: ", size1);
     numbers[i]=GetInteger();
 }
}

int indexMax (int numbers[], int low, int high)                  /*Function indexMax*/
{
int i, maxInd;

maxInd=high;
for (i=low;i<=high;i++)
{
    if (numbers[i]>numbers[maxInd])
    {
                   maxInd =i;
    }
    }
    return (maxInd);
}

void swap (int numbers[], int loc, int loc1)                     /*Function swap*/
{
 int temp;

 temp=numbers[loc];
 numbers[loc]=numbers[loc1];
 numbers[loc1]=temp;
}

int binSearch(int val, int numbers[], int size1)                 /*Function binSearch*/
{
 int low, high, mid;

 low=0;
 high=size1-1;
 while(low<=high)
 {
                 mid=(low+high)/2;
                 if(val<numbers[mid])
                 {
                                 high=mid-1;
                 }
                 else if(val>numbers[mid])
                 {
                                 low=mid+1;
                 }
                 else if(val==numbers[mid])
                 {
                                 printf("Your number is in location %d\n", mid+1);break;
                 }
                 else
                 {
                                 printf("Your value is not in the array.");
                 }
   }
}
</code>```

The above is the binary search algorithm code I tried to compile.

答:
I bet for sure, that this is because you didn't close the running instance of the program before trying to re-compile it.

Generally, ld.exe returns 1 when it can't access required files. This usually includes

Can't find the object file to be linked (or Access denied)

Can't find one or more symbols to link

Can't open the executable for writing (or AD)

The program looks completely fine, so the second point should not hit. In usual cases, it's impossible for ld to fail to open the object file (unless you have a faulty drive and a dirty filesystem), so the first point is also nearly impossible.

Now we get to the third point. Note that Windows not allow writing to a file when it's in use, so the running instance of your program prevents ld.exe from writing the new linked program to it.

So next time be sure to close running programs before compiling.

Body:
For some reason, when I try compiling a program, the compiler says permission denied and Id returned 1 exit status.  Could anyone tell me what that means? Thank you

#include <stdio.h>                                               /* Library inclusions */
#include "genlib.h"
#include "simpio.h"

int binSearch(int val, int numbers[], int size1);                /* prototypes */
void sortArray (int numbers[], int size1);
int indexMax (int numbers[], int low, int high);
void swap (int numbers[], int loc, int loc1);
void getArray (int numbers[], int size1);
void displayArray (int numbers[], int size1);

main()
{
  int value, size1;

  printf("Enter the number of elements: ");
  size1=GetInteger();
  int numbers[size1];
  getArray(numbers, size1);
  sortArray(numbers, size1);
  displayArray(numbers, size1);
  printf("\nEnter value to find: ");
  value=GetInteger();
  binSearch(value, numbers, size1);
  getchar();
}

void sortArray (int numbers[], int size1)                        /*Function sortArray*/
{
 int i , maxInd;

 for (i= size1-1; i>=0;i--)
 {
     maxInd=indexMax(numbers, 0, i);
     swap (numbers, i, maxInd);
 }
}

void displayArray (int numbers[], int size1)                     /*Function displayArray*/
{
 int i;

 printf("This is the sorted set of numbers: \n");
 for (i=0; i< size1; i++)
 {
         printf ("%d\t", numbers[i]);
     }
}

void getArray (int numbers[], int size1)                         /*Function getArray*/
{
 int i;

 for (i=0; i<size1; i++)
 {
     printf ("Enter the values of the %d elements: ", size1);
     numbers[i]=GetInteger();
 }
}

int indexMax (int numbers[], int low, int high)                  /*Function indexMax*/
{
int i, maxInd;

maxInd=high;
for (i=low;i<=high;i++)
{
    if (numbers[i]>numbers[maxInd])
    {
                   maxInd =i;
    }
    }
    return (maxInd);
}

void swap (int numbers[], int loc, int loc1)                     /*Function swap*/
{
 int temp;

 temp=numbers[loc];
 numbers[loc]=numbers[loc1];
 numbers[loc1]=temp;
}

int binSearch(int val, int numbers[], int size1)                 /*Function binSearch*/
{
 int low, high, mid;

 low=0;
 high=size1-1;
 while(low<=high)
 {
                 mid=(low+high)/2;
                 if(val<numbers[mid])
                 {
                                 high=mid-1;
                 }
                 else if(val>numbers[mid])
                 {
                                 low=mid+1;
                 }
                 else if(val==numbers[mid])
                 {
                                 printf("Your number is in location %d\n", mid+1);break;
                 }
                 else
                 {
                                 printf("Your value is not in the array.");
                 }
   }
}

The above is the binary search algorithm code I tried to compile.