问:
How to add watermark on existing Word Document using PHPWord?
I'm trying to add a watermark on my existing Word document but am unable to add it. There are a lot of examples of creating new docs & then editing them according to your need. But I could not find any tutorial to edit a pre-existing Word document.

Below is my Code:

```<code><?php
require_once '../PHPWord.php';

// New Word Document
$PHPWord = new PHPWord();

// New portrait section
$section = $PHPWord->createSection();

// Create header
$header = $section->createHeader();

// Add a watermark to the header
$header->addWatermark('_earth.jpg', array('marginTop'=>200, 'marginLeft'=>55));

$section->addText("Hello World");

// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('Watermark.docx');
?>
</code>```

答:
You can find an example here:
https://github.com/PHPOffice/PHPWord/blob/develop/samples/Sample_11_ReadWord2007.php

Particular to your question, to open the document, you need to replace the line

```<code>$PHPWord = new PHPWord();
</code>```

with

```<code>$PHPWord = PhpWord\IOFactory::load('<file path of your MSWord document>'); // or \PhpOffice\PhpWord\IOFactory depending on your environment
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to add a watermark on my existing Word document but am unable to add it. There are a lot of examples of creating new docs & then editing them according to your need. But I could not find any tutorial to edit a pre-existing Word document.

Below is my Code:

<?php
require_once '../PHPWord.php';

// New Word Document
$PHPWord = new PHPWord();

// New portrait section
$section = $PHPWord->createSection();

// Create header
$header = $section->createHeader();

// Add a watermark to the header
$header->addWatermark('_earth.jpg', array('marginTop'=>200, 'marginLeft'=>55));

$section->addText("Hello World");

// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('Watermark.docx');
?>

Body:
You can find an example here:
https://github.com/PHPOffice/PHPWord/blob/develop/samples/Sample_11_ReadWord2007.php

Particular to your question, to open the document, you need to replace the line

$PHPWord = new PHPWord();

with

$PHPWord = PhpWord\IOFactory::load('<file path of your MSWord document>'); // or \PhpOffice\PhpWord\IOFactory depending on your environment


来源: stackexchange

问:
UITableViewCell Buttons with action
Hi I have a custom UITableViewCell with three buttons to handle a shopping cart function, Plus,Minus and Delete button and I need to know which cell has been touched.

I've already tried to use the "tag solution" but it isn't working due to the lifecycle of the cells.

Can anyone please help me find a solution?

Thanks in advance

答:
I came across the same problem after making the IBOutlets private as has been broadly suggested by the community.

Here is my solution:

< In your cell class >

```<code>protocol YourCellDelegate: class {
    func didTapButton(_ sender: UIButton)
}

class YourCell: UITableViewCell {

    weak var delegate: YourCellDelegate?

    @IBAction func buttonTapped(_ sender: UIButton) {
        delegate?.didTapButton(sender)
    }
}
</code>```

< In your ViewController >

```<code>class ViewController: UIViewController, YourCellDelegate {

    func didTapButton(_ sender: UIButton) {
        if let indexPath = getCurrentCellIndexPath(sender) {
            item = items[indexPath.row]
        }
    }

    func getCurrentCellIndexPath(_ sender: UIButton) -> IndexPath? {
        let buttonPosition = sender.convert(CGPoint.zero, to: tableView)
        if let indexPath: IndexPath = tableView.indexPathForRow(at: buttonPosition) {
            return indexPath
        }
        return nil
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: UITableViewCell Buttons with action

Body:
I came across the same problem after making the IBOutlets private as has been broadly suggested by the community.

Here is my solution:

< In your cell class >

protocol YourCellDelegate: class {
    func didTapButton(_ sender: UIButton)
}

class YourCell: UITableViewCell {

    weak var delegate: YourCellDelegate?

    @IBAction func buttonTapped(_ sender: UIButton) {
        delegate?.didTapButton(sender)
    }
}

< In your ViewController >

class ViewController: UIViewController, YourCellDelegate {

    func didTapButton(_ sender: UIButton) {
        if let indexPath = getCurrentCellIndexPath(sender) {
            item = items[indexPath.row]
        }
    }

    func getCurrentCellIndexPath(_ sender: UIButton) -> IndexPath? {
        let buttonPosition = sender.convert(CGPoint.zero, to: tableView)
        if let indexPath: IndexPath = tableView.indexPathForRow(at: buttonPosition) {
            return indexPath
        }
        return nil
    }
}


问:
How to reduce the size of google spreadsheet using SQL?
I have a google spreadsheet which is about 9MB in size and I want to reduce its size using SQL.
What are the possible ways to reduce Spreadsheet's size if I cannot use SQL?</p>

答:
From the Format menu there's an option for Font Size - by default this is set to 10 but if you make it smaller you can reduce the size of the spreadsheet.

Or as recommended by Neil you can delete some/all of the data.


问:
Select all categories with COUNT of sub-categories
I need to select all categories with count of its sub-categories.

Assume here are my tables:

categories

```<code>id | title
----------
1  | colors
2  | animals
3  | plants
</code>```

sub_categories

```<code>id | category_id | title | confirmed
------------------------------------
1        1          red       1
2        1          blue      1
3        1          pink      1
4        2          cat       1
5        2          tiger     0
6        2          lion      0
</code>```

What I want is :

```<code>id |  title  | count
------------------
1    colors     3
2    animals    1
3    plants     0
</code>```

What I have tried so far:

```<code>SELECT c.id, c.title, count(s.category_id) as count from categories c
LEFT JOIN sub_categories s on c.id = s.category_id
WHERE c.confirmed = 't' AND s.confirmed='t'
GROUP BY c.id, c.title
ORDER BY count DESC
</code>```

The only problem with this query is that this query does not show categories with 0 sub categories!

You also can check that on SqlFiddle

Any help would be great appreciated.

答:
The reason you don't get rows with zero counts is that WHERE clause checks s.confirmed to be t, thus eliminating rows with NULLs from the outer join result.

Move s.confirmed check into join expression to fix this problem:

```<code>SELECT c.id, c.title, count(s.category_id) as count from categories c
LEFT JOIN sub_categories s on c.id = s.category_id AND s.confirmed='t'
WHERE c.confirmed = 't'
GROUP BY c.id, c.title
ORDER BY count DESC
</code>```

Adding Sql Fiddle: http://sqlfiddle.com/#!17/83add/13

Body:
I need to select all categories with count of its sub-categories.

Assume here are my tables:

categories

id | title
----------
1  | colors
2  | animals
3  | plants

sub_categories

id | category_id | title | confirmed
------------------------------------
1        1          red       1
2        1          blue      1
3        1          pink      1
4        2          cat       1
5        2          tiger     0
6        2          lion      0

What I want is :

id |  title  | count
------------------
1    colors     3
2    animals    1
3    plants     0

What I have tried so far:

SELECT c.id, c.title, count(s.category_id) as count from categories c
LEFT JOIN sub_categories s on c.id = s.category_id
WHERE c.confirmed = 't' AND s.confirmed='t'
GROUP BY c.id, c.title
ORDER BY count DESC

The only problem with this query is that this query does not show categories with 0 sub categories!

You also can check that on SqlFiddle

Any help would be great appreciated.

Body:
The reason you don't get rows with zero counts is that WHERE clause checks s.confirmed to be t, thus eliminating rows with NULLs from the outer join result.

Move s.confirmed check into join expression to fix this problem:

SELECT c.id, c.title, count(s.category_id) as count from categories c
LEFT JOIN sub_categories s on c.id = s.category_id AND s.confirmed='t'
WHERE c.confirmed = 't'
GROUP BY c.id, c.title
ORDER BY count DESC

Adding Sql Fiddle: http://sqlfiddle.com/#!17/83add/13


问:
Retail POS return transaction double tax inclusion
I want to customize the method that fetches transaction data from HQ while we return a transaction from POS.

Is it allowed or is it the part of some DLL that we do not have code available in retail SDK of ?

答:
I  resolved the issue.
I subtracted the tax amount from the actual amount if the transaction was a return transaction and it was fetched from HQ.
It worked for me.</p>


问:
REST Calls with Http2.0 over Http1.1
I was reading through HTTP2.0 as new HTTP protocol and advantages with binary header and multiplexing. But i would like to know for Rest calls does migrating from HTTP1.1 to HTTP2.0 provide any reasonable advantage. I am not able to find any specific gain for REST full calls with HTTP2.0

Thanks in advance.

答:
It does, in several ways:

Better support for streaming transfers. The conventional alternative is a combination of HTTP/1.1's chunked transfer encoding, connection header Voodoo and the willingness or not of any of the parts to implement HTTP pipelining (which, e.g., curl enables by default). In my experience it takes a lot more of work to get the three to work well together than to just slap HTTP/2. There is no need for chunked transfer-encoding with HTTP/2, and the protocol does not support it.

With HTTP/2, you can have many requests in flight, REST or not, with zero time for establishing connections. This is a blessing both for the browser and for the server, which has to allocate less files descriptors per client.

Header compression also applies to HTTP/2 REST requests, together with the associated bandwidth reduction.

So, if in doubt, go always for HTTP/2. There are also excellent tools out there to develop HTTP/2 applications. Some, like ShimmerCat, even remove the drudgery of setting up certificates and DNS alias, so that starting with HTTP/2 from day one becomes a no-brainer.

Title: REST Calls with Http2.0 over Http1.1


问:
Ensuring the latest SQL record is always chosen for a calculation
We have a financial log of transactions made by our customers stored in a database table, the table includes information on:

Transaction ID

Customer ID

Date/time of transaction

Amount

Balance

The balance of a new transaction is calculated by taking the latest, previous transaction (using date/time of a transaction) with the same customer ID and summing this with the amount of the new transaction.

As this is a transaction log, none of the details can be modified by a user.

We are using SQL Server's GETDATE to derive the customer's current balance. Is this sufficient to ensure we are always choosing the customer's latest transaction to do the balance calculation? Important for us to do this since if we pick the incorrect transaction, the customers' transaction log would not add up.

Example of what the table could look like (an image since it doesn't look like I can use markdown to create the table):

Our system also has screens to do bulk add of transactions, here we insert the transactions as a SQL batch. Are these any possibilities here where two or more transactions entered for a customer could have same date/time and therefore cause problems with our balance calculations for subsequent transactions?

答:
For this sort of problem, my starting point is always to try to create a table structure that cannot store wrong data. With that as the starting point, you then can add additional structures around it to try to make it more useful.

So, if we've decided having a running total around is a good idea (I'd usually advise against this, as indicated in the comments, and just compute it on demand), we need to create a table structure that promotes this:

```<code>create table dbo._Ledger (
    CustomerID int not null,
    TransactionID int not null,
    OccurredAt datetime2 not null,
    TransactionAmount decimal(22,5) not null,
    PreviousTransactionID as CASE WHEN TransactionID > 1
                                  THEN TransactionID - 1 END persisted,
    PreviousBalance decimal(22,5) null,
    Balance as CONVERT(decimal(22,5),
                      ISNULL(PreviousBalance,0.0) + TransactionAmount) persisted,
    constraint PK_Ledger PRIMARY KEY (CustomerID,TransactionID),
    constraint CK_Ledger_IDs CHECK (TransactionID > 0),
    constraint CK_Ledger_Continuous CHECK (TransactionID=1 and PreviousBalance is null or
                                       TransactionID > 1 and PreviousBalance is not null),
    constraint UQ_Ledger_XRef UNIQUE (CustomerID,TransactionID,Balance),
    constraint FK_Ledger_XRef
        FOREIGN KEY (CustomerID,PreviousTransactionID,PreviousBalance)
        references dbo._Ledger(CustomerID,TransactionID,Balance)
)
</code>```

With the above structure, what we have is a table that builds up a ledger for each customer. The Balance column is a computed column - computed by adding the transaction amount to the previous balance. And we ensure that the previous balance is correct by making it part of a foreign key that references the previous row(UQ_Ledger_XRef and FK_Ledger_XRef).

We also have some check constraints that ensure that the history we build up is unique and unambiguous - every customers transactions must be numbered from 1 upwards, with no gaps.

Having created that structure, though, we find its considerably more complex than what we wanted to expose to the users - so we create a view:

```<code>create view dbo.Ledger
with schemabinding
as
    select
        CustomerID,
        ISNULL(TransactionID,0) as TransactionID,
        OccurredAt,
        TransactionAmount,
        Balance
    from
        dbo._Ledger
</code>```

This now just shows the columns that the users will care about and hides the complexity from them. When users insert into this view, they'll just populate CustomerID, OccurredAt and TransactionAmount - the other columns (TransactionID and Balance) are computed.

However, insertion into this view is not straightforward, so we also need to supply a trigger:

```<code>create trigger Ledger_I
on dbo.Ledger
instead of insert
as
    ;With Ordered as (
        select
            *,
            ROW_NUMBER() OVER (PARTITION BY CustomerID order by OccurredAt) as rn,
            SUM(TransactionAmount) OVER (PARTITION BY CustomerID
                                         order by OccurredAt
                                         rows between unbounded preceding and current row)
             - TransactionAmount as Running
        from
            inserted
    ), Historic as (
        select
            *,
            ROW_NUMBER() OVER (PARTITION BY CustomerID Order by TransactionID desc) as rn
        from
            dbo._Ledger
        where
            CustomerID in (select CustomerID from inserted)
    )
    insert into dbo._Ledger
    (CustomerID,TransactionID,OccurredAt,TransactionAmount,PreviousBalance)
    select o.CustomerID,
           o.rn + COALESCE(h.TransactionID,0),
           o.OccurredAt,o.TransactionAmount,
        CASE WHEN o.rn > 1 or h.Balance is not null THEN h.Balance + o.Running END
    from
        Ordered o
            left join
        Historic h
            on
                o.CustomerID = h.CustomerID and
                h.rn = 1
</code>```

And hopefully you can see how the common table expressions are working together to assign correct TransactionIDs and populate the correct PreviousBalance amounts.

(By the way, the _ prefix on the table is just my convention for objects which I don't intend for users to access directly. There's no specific significance to it)

Body:
For this sort of problem, my starting point is always to try to create a table structure that cannot store wrong data. With that as the starting point, you then can add additional structures around it to try to make it more useful.

So, if we've decided having a running total around is a good idea (I'd usually advise against this, as indicated in the comments, and just compute it on demand), we need to create a table structure that promotes this:

create table dbo._Ledger (
    CustomerID int not null,
    TransactionID int not null,
    OccurredAt datetime2 not null,
    TransactionAmount decimal(22,5) not null,
    PreviousTransactionID as CASE WHEN TransactionID > 1
                                  THEN TransactionID - 1 END persisted,
    PreviousBalance decimal(22,5) null,
    Balance as CONVERT(decimal(22,5),
                      ISNULL(PreviousBalance,0.0) + TransactionAmount) persisted,
    constraint PK_Ledger PRIMARY KEY (CustomerID,TransactionID),
    constraint CK_Ledger_IDs CHECK (TransactionID > 0),
    constraint CK_Ledger_Continuous CHECK (TransactionID=1 and PreviousBalance is null or
                                       TransactionID > 1 and PreviousBalance is not null),
    constraint UQ_Ledger_XRef UNIQUE (CustomerID,TransactionID,Balance),
    constraint FK_Ledger_XRef
        FOREIGN KEY (CustomerID,PreviousTransactionID,PreviousBalance)
        references dbo._Ledger(CustomerID,TransactionID,Balance)
)

With the above structure, what we have is a table that builds up a ledger for each customer. The Balance column is a computed column - computed by adding the transaction amount to the previous balance. And we ensure that the previous balance is correct by making it part of a foreign key that references the previous row(UQ_Ledger_XRef and FK_Ledger_XRef).

We also have some check constraints that ensure that the history we build up is unique and unambiguous - every customers transactions must be numbered from 1 upwards, with no gaps.

Having created that structure, though, we find its considerably more complex than what we wanted to expose to the users - so we create a view:

create view dbo.Ledger
with schemabinding
as
    select
        CustomerID,
        ISNULL(TransactionID,0) as TransactionID,
        OccurredAt,
        TransactionAmount,
        Balance
    from
        dbo._Ledger

This now just shows the columns that the users will care about and hides the complexity from them. When users insert into this view, they'll just populate CustomerID, OccurredAt and TransactionAmount - the other columns (TransactionID and Balance) are computed.

However, insertion into this view is not straightforward, so we also need to supply a trigger:

create trigger Ledger_I
on dbo.Ledger
instead of insert
as
    ;With Ordered as (
        select
            *,
            ROW_NUMBER() OVER (PARTITION BY CustomerID order by OccurredAt) as rn,
            SUM(TransactionAmount) OVER (PARTITION BY CustomerID
                                         order by OccurredAt
                                         rows between unbounded preceding and current row)
             - TransactionAmount as Running
        from
            inserted
    ), Historic as (
        select
            *,
            ROW_NUMBER() OVER (PARTITION BY CustomerID Order by TransactionID desc) as rn
        from
            dbo._Ledger
        where
            CustomerID in (select CustomerID from inserted)
    )
    insert into dbo._Ledger
    (CustomerID,TransactionID,OccurredAt,TransactionAmount,PreviousBalance)
    select o.CustomerID,
           o.rn + COALESCE(h.TransactionID,0),
           o.OccurredAt,o.TransactionAmount,
        CASE WHEN o.rn > 1 or h.Balance is not null THEN h.Balance + o.Running END
    from
        Ordered o
            left join
        Historic h
            on
                o.CustomerID = h.CustomerID and
                h.rn = 1

And hopefully you can see how the common table expressions are working together to assign correct TransactionIDs and populate the correct PreviousBalance amounts.

(By the way, the _ prefix on the table is just my convention for objects which I don't intend for users to access directly. There's no specific significance to it)


问:
How to calculate means and std at once in pandas?
For example, we have data like :

```<code>>>> df
   name  score  times
0   tom    100      1
1   tom     99      2
2   tom    100      3
3  jack     99      1
4  jack     99      2
5  tony    100      1
6  tony    100      2
7  tony    100      3
</code>```

I want to get a result like

```<code>   name       score std
0  jack   99.000000  0
1   tom   99.666667  0.57
2  tony  100.000000  0
</code>```

Is it possible to get the result at once?
Now I have to calculate them seperately and combine the result

答:
To get exactly what you need, you can group by name first, calculate mean and std on score and then rename and reindex.</p>

```<code>(
     df.groupby('name').score.agg(['mean','std'])
       .rename(columns={'mean':'score'}).reset_index()
)
Out[204]:
   name       score      std
0  jack   99.000000  0.00000
1   tom   99.666667  0.57735
2  tony  100.000000  0.00000
</code>```

Body:
For example, we have data like :

>>> df
   name  score  times
0   tom    100      1
1   tom     99      2
2   tom    100      3
3  jack     99      1
4  jack     99      2
5  tony    100      1
6  tony    100      2
7  tony    100      3

I want to get a result like

   name       score std
0  jack   99.000000  0
1   tom   99.666667  0.57
2  tony  100.000000  0

Is it possible to get the result at once?
Now I have to calculate them seperately and combine the result

Body:
To get exactly what you need, you can group by name first, calculate mean and std on score and then rename and reindex.

(
     df.groupby('name').score.agg(['mean','std'])
       .rename(columns={'mean':'score'}).reset_index()
)
Out[204]:
   name       score      std
0  jack   99.000000  0.00000
1   tom   99.666667  0.57735
2  tony  100.000000  0.00000


问:
Matplotlib: How to make a stacked plot of count of values in a Numpy array
Hey I have the following problem. I have a array like this:

```<code> arr1=
[[4 4 4]
 [4 4 6]
 [4 3 4]
 [4 4 7]
 [4 4 3]
 [4 4 1]
 [3 4 7]
 [4 3 7]
 [4 4 5]
 [4 3 6]]
</code>```

Now i want to get a stacked bar plot(histogram), that shows the number of different elements,, like this:

My frist approach was to bincount the elements, fill the arrays up, but then i dont know what to do.

```<code>arr2=
    [[0 0 0]
     [0 0 1]
     [0 0 0]
     [1 3 1]
     [9 7 2]
     [0 0 1]
     [0 0 2]
     [0 0 3]]
</code>```

答:
Adding an Altair based answer as well.

```<code>import numpy as np
import pandas as pd
from altair import *
data = np.array([[4, 4, 4],
 [4, 4, 6],
 [4, 3, 4],
 [4, 4, 7],
 [4, 4, 3],
 [4, 4, 1],
 [3, 4, 7],
 [4, 3, 7],
 [4, 4, 5],
 [4, 3, 6]])

columns = ['Col1', 'Col2', 'Col3']
df = pd.DataFrame(data, columns=columns)
df = df.T.stack().reset_index(level=[0,1])
df.columns = ['Col','RowNum','Value']
Chart(df).mark_bar().encode(y='count(*)', x='Col:N', color='Value:N')
</code>```

Body:
Hey I have the following problem. I have a array like this:

 arr1=
[[4 4 4]
 [4 4 6]
 [4 3 4]
 [4 4 7]
 [4 4 3]
 [4 4 1]
 [3 4 7]
 [4 3 7]
 [4 4 5]
 [4 3 6]]

Now i want to get a stacked bar plot(histogram), that shows the number of different elements,, like this:

My frist approach was to bincount the elements, fill the arrays up, but then i dont know what to do.

arr2=
    [[0 0 0]
     [0 0 1]
     [0 0 0]
     [1 3 1]
     [9 7 2]
     [0 0 1]
     [0 0 2]
     [0 0 3]]

Body:
Adding an Altair based answer as well.

import numpy as np
import pandas as pd
from altair import *
data = np.array([[4, 4, 4],
 [4, 4, 6],
 [4, 3, 4],
 [4, 4, 7],
 [4, 4, 3],
 [4, 4, 1],
 [3, 4, 7],
 [4, 3, 7],
 [4, 4, 5],
 [4, 3, 6]])

columns = ['Col1', 'Col2', 'Col3']
df = pd.DataFrame(data, columns=columns)
df = df.T.stack().reset_index(level=[0,1])
df.columns = ['Col','RowNum','Value']
Chart(df).mark_bar().encode(y='count(*)', x='Col:N', color='Value:N')


问:
Single dictionary initialization with different types of keys
Has anyone used class initialization like this:

```<code>var dictionary = new Dictionary {
    [address] = address,
    [person] = person,
    [biz] = biz
};
</code>```

How do I declare such class Dictionary which initializes using above line,
Never used [] in dictionary initialization which takes different types as key

address, person, biz are objects off different classes Address, Person and Biz

reference: problem I am solving

Updates

```<code>public class BaseEntity
{
    public string Id { get; set; }

    public bool Save()
    {
        return true;
    }

    public bool Delete()
    {
        return true;
    }
}

public class Address : BaseEntity
{
    public Address() { }

    public Address(string addressLine1, string addressLine2, string state, string zip)
    {
        this.AddressLine1 = addressLine1;
        this.AddressLine2 = addressLine2;
        this.State = state;
        this.ZipCode = zip;
    }

    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }

    public static Address Find(string id)
    {
        return null;
    }
}

public class Business : BaseEntity
{
    public Business() { }

    public Business(string businessName, Address address)
    {
        this.Name = businessName;
        this.Address = address;
    }

    public string Name { get; set; }
    public Address Address { get; set; }

    public static Business Find(string id)
    {
        return null;
    }
}

public class Person : BaseEntity
{
    public Person() { }

    public Person(string fname, string lname, Address address)
    {
        this.FirstName = fname;
        this.LastName = lname;
        this.Address = address;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }

    public static Person Find(string id)
    {
        return null;
    }
}
</code>```

答:
Never used [] in dictionary initialization which takes different types as key

Index initializers are available since C# 6.0

```<code>new Dictionary<int, string> { [7] = "seven" };
</code>```

This uses the indexer instead of the Add method so adding the same key multiple times will not throw exception but replaces the original instance.

And the support of different types can be achieved by using object for keys and values. The Dictionary type in the source must be something like this:

```<code>public class Dictionary : Dictionary<object, object> {}
</code>```

Body:
Has anyone used class initialization like this:

var dictionary = new Dictionary {
    [address] = address,
    [person] = person,
    [biz] = biz
};

How do I declare such class Dictionary which initializes using above line,
Never used [] in dictionary initialization which takes different types as key

address, person, biz are objects off different classes Address, Person and Biz

reference: problem I am solving

Updates

public class BaseEntity
{
    public string Id { get; set; }

    public bool Save()
    {
        return true;
    }

    public bool Delete()
    {
        return true;
    }
}

public class Address : BaseEntity
{
    public Address() { }

    public Address(string addressLine1, string addressLine2, string state, string zip)
    {
        this.AddressLine1 = addressLine1;
        this.AddressLine2 = addressLine2;
        this.State = state;
        this.ZipCode = zip;
    }

    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }

    public static Address Find(string id)
    {
        return null;
    }
}

public class Business : BaseEntity
{
    public Business() { }

    public Business(string businessName, Address address)
    {
        this.Name = businessName;
        this.Address = address;
    }

    public string Name { get; set; }
    public Address Address { get; set; }

    public static Business Find(string id)
    {
        return null;
    }
}

public class Person : BaseEntity
{
    public Person() { }

    public Person(string fname, string lname, Address address)
    {
        this.FirstName = fname;
        this.LastName = lname;
        this.Address = address;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }

    public static Person Find(string id)
    {
        return null;
    }
}

Body:
Never used [] in dictionary initialization which takes different types as key

Index initializers are available since C# 6.0

new Dictionary<int, string> { [7] = "seven" };

This uses the indexer instead of the Add method so adding the same key multiple times will not throw exception but replaces the original instance.

And the support of different types can be achieved by using object for keys and values. The Dictionary type in the source must be something like this:

public class Dictionary : Dictionary<object, object> {}


问:
What is the point of this line of code?
I found this line of code in the Virtuemart plugin for Joomla on line 2136 in administrator/components/com_virtuemart/classes/ps_product.php</p>

```<code>eval ("\$text_including_tax = \"$text_including_tax\";");
</code>```

答:
This code seems to be a bad way of forcing $text_including_tax to be a string.

The reason it is bad is because if $text_including_tax can contain data entered by a user it is possible for them to execute arbitrary code.

For example if $text_include_tax was set to equal:

```<code>"\"; readfile('/etc/passwd'); $_dummy = \"";
</code>```

The eval would become:

```<code>eval("$text_include_tax = \"\"; readfile('/etc/passwd'); $_dummy =\"\";");
</code>```

Giving the malicious user a dump of the passwd file.

A more correct method for doing this would be to cast the variable to string:

```<code>$text_include_tax = (string) $text_include_tax;
</code>```

or even just:

```<code>$text_include_tax = "$text_include_tax";
</code>```

If the data $text_include_tax is only an internal variable or contains already validated content there isn't a security risk. But it's still a bad way to convert a variable to a string because there are more obvious and safer ways to do it.

OwnerDisplayName: mk

ContentLicense: CC BY-SA 2.5

Title: What is the point of this line of code?

Body:
I found this line of code in the Virtuemart plugin for Joomla on line 2136 in administrator/components/com_virtuemart/classes/ps_product.php

eval ("\$text_including_tax = \"$text_including_tax\";");

Body:
This code seems to be a bad way of forcing $text_including_tax to be a string.

The reason it is bad is because if $text_including_tax can contain data entered by a user it is possible for them to execute arbitrary code.

For example if $text_include_tax was set to equal:

"\"; readfile('/etc/passwd'); $_dummy = \"";

The eval would become:

eval("$text_include_tax = \"\"; readfile('/etc/passwd'); $_dummy =\"\";");

Giving the malicious user a dump of the passwd file.

A more correct method for doing this would be to cast the variable to string:

$text_include_tax = (string) $text_include_tax;

or even just:

$text_include_tax = "$text_include_tax";

If the data $text_include_tax is only an internal variable or contains already validated content there isn't a security risk. But it's still a bad way to convert a variable to a string because there are more obvious and safer ways to do it.

OwnerDisplayName: calebbrown

LastEditorDisplayName: calebbrown


问:
GWT and Search Engines
Does GWT app are indexed by search engines???? if yes, how to accomplish that?

Thanks.

答: Search engines don't prefer html that generated on client side by javascript(Ajax). They prefer static html that generated from server side. That is why, AJAX applications are difficult to index because they are generated dynamically on the client side.</p>

Title: GWT and Search Engines


问:
Hide div while scrolling down
I just want to hide an image when scroll down and show another image. When scroll to top of the page, first image needs to show and other image needs to be hide.

I tried with this code.

```<code>//This is the image I just want to show at first
<img src="images/logo-wh.png" alt="" class="logo-white">

//This is the image I just want to show when scroll down
<img src="images/logo.png" alt="" class="logo-default">

.logo-default{
  display:none;
}

$(window).scroll(function() {
    if ($(this).scrollTop() > 0) {
        $('.logo-white').hide();
    } else {
        $('.logo-default').show();
    }
 });
</code>```

But it isn't working as I expected. Any suggestions?

答:
```<code>$("window ").scroll(function(){
if($(window).scrollTop()>0){
$(".logo-white").attr("src","images/logo-wh.png");
}
else{
$(".logo-white").attr("src","images/logo.png");
}
});
</code>```

Delete the second img tag

Title: Hide div while scrolling down

Body:
I just want to hide an image when scroll down and show another image. When scroll to top of the page, first image needs to show and other image needs to be hide.

I tried with this code.

//This is the image I just want to show at first

//This is the image I just want to show when scroll down

.logo-default{
  display:none;
}

$(window).scroll(function() {
    if ($(this).scrollTop() > 0) {
        $('.logo-white').hide();
    } else {
        $('.logo-default').show();
    }
 });

But it isn't working as I expected. Any suggestions?

Body:
$("window ").scroll(function(){
if($(window).scrollTop()>0){
$(".logo-white").attr("src","images/logo-wh.png");
}
else{
$(".logo-white").attr("src","images/logo.png");
}
});

Delete the second img tag


问:
"Peer's certificate issuer has been marked as not trusted by the user" in Openshift3
If S2I - "Source-to-image" resource in Openshift3 tries to connect to a TLS Gitlab repository shows the following message: "Peer's certificate issuer has been marked as not trusted by the user".

How can I instruct Openshift3 which certificates authorities are able to use there? Is there any config/option to bypass this error?

The command entered was:

```<code>oc new-app tomcat~https://gitlab.xxx/test/test.git --name=test --strategy=docker
</code>```

答:
For security reasons,  you should add a trusted CA source secret to the BuildConfig. To answer your question, you can disable TLS verification by setting an environment variable GIT_SSL_NO_VERIFY to false in the BuildConfig. Checks the docs here for more info.

To pass this directly to the oc new-app command run oc new-app --build-env GIT_SSL_NO_VERIFY=false

Body:
If S2I - "Source-to-image" resource in Openshift3 tries to connect to a TLS Gitlab repository shows the following message: "Peer's certificate issuer has been marked as not trusted by the user".

How can I instruct Openshift3 which certificates authorities are able to use there? Is there any config/option to bypass this error?

The command entered was:

oc new-app tomcat~https://gitlab.xxx/test/test.git --name=test --strategy=docker


答:
Here is a sample code :

$(window).scroll(function() {
    if ($(this).scrollTop() > 0) {
        $('.logo-white').hide();
         $('.logo-default').show();
    } else {
        $('.logo-default').hide();
        $('.logo-white').show();
    }
 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.logo-default {
  display: none;
}</code>```

```

Title: Hide div while scrolling down

Body:
Here is a sample code :

$(window).scroll(function() {
    if ($(this).scrollTop() > 0) {
        $('.logo-white').hide();
         $('.logo-default').show();
    } else {
        $('.logo-default').hide();
        $('.logo-white').show();
    }
 });

.logo-default {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://cdn.pixabay.com/photo/2015/02/07/22/31/golden-eagle-627943_960_720.jpg" alt="" class="logo-white">

<img src="https://cdn.pixabay.com/photo/2014/08/12/17/13/white-tailed-eagle-416795_960_720.jpg" alt="" class="logo-default">


问:
How to check the Emoji property of a character in Python?
In unicode a character can have an Emoji property.

Is there a standard way in Python to determine if a character is an Emoji?

I know of unicodedata, but it doesn't appear to expose all these extra character details.

Note: I'm asking about the specific attribute called "Emoji" in the unicdoe standard, as provided in the link. I don't want to have an arbitrary list of pattern ranges, and preferably use a standard library.

答:
I have used the following regex pattern successfully before

```<code>import re

emoji_pattern = re.compile("["
                               u"\U0001F600-\U0001F64F"  # emoticons
                               u"\U0001F300-\U0001F5FF"  # symbols & pictographs
                               u"\U0001F680-\U0001F6FF"  # transport & map symbols
                               u"\U0001F1E0-\U0001F1FF"  # flags (iOS)
                               "]+", flags=re.UNICODE)
</code>```

Also check out this question: removing emojis from a string in Python

Body:
I have used the following regex pattern successfully before

import re

emoji_pattern = re.compile("["
                               u"\U0001F600-\U0001F64F"  # emoticons
                               u"\U0001F300-\U0001F5FF"  # symbols & pictographs
                               u"\U0001F680-\U0001F6FF"  # transport & map symbols
                               u"\U0001F1E0-\U0001F1FF"  # flags (iOS)
                               "]+", flags=re.UNICODE)

Also check out this question: removing emojis from a string in Python


问:
Is there any way to know the physical address of attached shared memory?
I want to know the "physical" address of a newly attached shared memory on Linux kernel.

As far as I know, do_shmat() returns the "virtual" address of shared memory.
So I tried to translate the return value of do_shamt() using TLB, by modifying shmat in the kernel like below.

```<code>SYSCALL_DEFINE3(shmat, int, shmid, char __user *, shmaddr, int, shmflg)

{
    unsigned long ret;
    unsigned long phys_ret;
    unsigned int regVal;

    long err;

    pgd_t *pgd;
    pud_t *pud;
    pmd_t *pmd;
    pte_t *pte;

    err = do_shmat(shmid, shmaddr, shmflg, &ret, SHMLBA);
    if (err)
            return err;
    force_successful_syscall_return();

    pgd = pgd_offset(current->mm, ret);
    pmd = pmd_offset(pgd, ret);
    pte = pte_offset_kernel(pmd, ret);

    printk("*pte = 0x%lx\n", *pte);

    return (long)ret;
}
</code>```

But pte points to an address which has 0 so I cannot actually get the physical address.
Why can't I get the right pte in my code?

答:
Try this:</p>

```<code>#include <linux/module.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/cma.h>
#include <linux/dma-contiguous.h>
#include <linux/cdev.h>
#include <linux/sched.h>
#include <linux/delay.h>
#include <linux/highmem.h>

/***************************************************************************************
 * phys_addr_t getPhysicalPageAddress(unsigned long va)
 *
 * Description
 *  Virtual to Physical address translation method.
 *  Performs a page walk to translate the given virtual address
 *  to its physical page address.
 *
 ***************************************************************************************/
phys_addr_t getPhysicalPageAddress(unsigned long va)
{
    phys_addr_t pa;
    pgd_t *pgd;
    pud_t *pud;
    pmd_t *pmd;
    pte_t *ptep , pte;
    struct page *pagina;
    struct mm_struct * mm;
    int pfn;
    pa = 0;
    mm = current->mm;
    //  Variable initialization
    pagina = NULL;
    pgd    = NULL;
    pmd    = NULL;
    ptep   = NULL;

    // Using Page Tables (this mechanism is known as "Page Walk"), we find the page that corresponds to Virtual Address
    pgd = pgd_offset(mm, va);
    if (!pgd_none(*pgd) || !pgd_bad(*pgd))
    {
        pud = pud_offset(pgd , va);
        if (!pud_none(*pud) || !pud_bad(*pud))
        {
            pmd = pmd_offset(pud, va);
            if (!pmd_none(*pmd) || !pmd_bad(*pmd))
            {
                ptep = pte_offset_map(pmd, va);
                if (ptep)
                {
                    pte = *ptep;
                    pte_unmap(ptep);
                    pagina = pte_page(pte);
                    //  The page has been found
                    //  Seek Page Frame Number for this page
                    pfn = page_to_pfn(pagina);
                    //  Seek Physical Address for this page, using "page_to_phys()" macro
                    pa = page_to_phys(pagina);
                } else printk(KERN_ERR, "Page Walk exception at pte entry. The Virtual Address 0x%lx cannot be translated for this process", va );
            } else printk(KERN_ERR, "Page Walk exception at pmd entry. The Virtual Address 0x%lx cannot be translated for this process", va );
        } else printk(KERN_ERR, "Page Walk exception at pud entry. The Virtual Address 0x%lx cannot be translated for this process", va );
    } else printk(KERN_ERR, "Page Walk exception at pgd entry. The Virtual Address 0x%lx cannot be translated for this process", va );

    return pa;
}
</code>```

Body:
I want to know the "physical" address of a newly attached shared memory on Linux kernel.

As far as I know, do_shmat() returns the "virtual" address of shared memory.
So I tried to translate the return value of do_shamt() using TLB, by modifying shmat in the kernel like below.

SYSCALL_DEFINE3(shmat, int, shmid, char __user *, shmaddr, int, shmflg)

{
    unsigned long ret;
    unsigned long phys_ret;
    unsigned int regVal;

    long err;

    pgd_t *pgd;
    pud_t *pud;
    pmd_t *pmd;
    pte_t *pte;

    err = do_shmat(shmid, shmaddr, shmflg, &ret, SHMLBA);
    if (err)
            return err;
    force_successful_syscall_return();

    pgd = pgd_offset(current->mm, ret);
    pmd = pmd_offset(pgd, ret);
    pte = pte_offset_kernel(pmd, ret);

    printk("*pte = 0x%lx\n", *pte);

    return (long)ret;
}

But pte points to an address which has 0 so I cannot actually get the physical address.
Why can't I get the right pte in my code?

Body:
Try this:

#include <linux/module.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/cma.h>
#include <linux/dma-contiguous.h>
#include <linux/cdev.h>
#include <linux/sched.h>
#include <linux/delay.h>
#include <linux/highmem.h>

/***************************************************************************************
 * phys_addr_t getPhysicalPageAddress(unsigned long va)
 *
 * Description
 *  Virtual to Physical address translation method.
 *  Performs a page walk to translate the given virtual address
 *  to its physical page address.
 *
 ***************************************************************************************/
phys_addr_t getPhysicalPageAddress(unsigned long va)
{
    phys_addr_t pa;
    pgd_t *pgd;
    pud_t *pud;
    pmd_t *pmd;
    pte_t *ptep , pte;
    struct page *pagina;
    struct mm_struct * mm;
    int pfn;
    pa = 0;
    mm = current->mm;
    //  Variable initialization
    pagina = NULL;
    pgd    = NULL;
    pmd    = NULL;
    ptep   = NULL;

    // Using Page Tables (this mechanism is known as "Page Walk"), we find the page that corresponds to Virtual Address
    pgd = pgd_offset(mm, va);
    if (!pgd_none(*pgd) || !pgd_bad(*pgd))
    {
        pud = pud_offset(pgd , va);
        if (!pud_none(*pud) || !pud_bad(*pud))
        {
            pmd = pmd_offset(pud, va);
            if (!pmd_none(*pmd) || !pmd_bad(*pmd))
            {
                ptep = pte_offset_map(pmd, va);
                if (ptep)
                {
                    pte = *ptep;
                    pte_unmap(ptep);
                    pagina = pte_page(pte);
                    //  The page has been found
                    //  Seek Page Frame Number for this page
                    pfn = page_to_pfn(pagina);
                    //  Seek Physical Address for this page, using "page_to_phys()" macro
                    pa = page_to_phys(pagina);
                } else printk(KERN_ERR, "Page Walk exception at pte entry. The Virtual Address 0x%lx cannot be translated for this process", va );
            } else printk(KERN_ERR, "Page Walk exception at pmd entry. The Virtual Address 0x%lx cannot be translated for this process", va );
        } else printk(KERN_ERR, "Page Walk exception at pud entry. The Virtual Address 0x%lx cannot be translated for this process", va );
    } else printk(KERN_ERR, "Page Walk exception at pgd entry. The Virtual Address 0x%lx cannot be translated for this process", va );

    return pa;
}


问:
Grok formatting for a custom timestamp
```<code>[04-21 12:57:04]
</code>```

this is the timestamp generated by python written logs.
I hav tried

SYSLOGTIMESTAMP, DATESTAMP_EVENTLOG, DATESTAMP_RFC2822,TIMESTAMP_ISO8601

and many more. Can anyone please provide the correct grok format for this.
If not possible how can i use this as a timestamp

答:
You can try these Groks:

```<code>\[(?<timestamp>%{MONTHNUM}-%{MONTHDAY} %{TIME})\]
</code>```

or

```<code>\[(?<timestamp>[^\]]+)\]
</code>```

Title: Grok formatting for a custom timestamp

Body:
[04-21 12:57:04]

this is the timestamp generated by python written logs.
I hav tried

SYSLOGTIMESTAMP, DATESTAMP_EVENTLOG, DATESTAMP_RFC2822,TIMESTAMP_ISO8601

and many more. Can anyone please provide the correct grok format for this.
If not possible how can i use this as a timestamp

Body:
You can try these Groks:

\[(?<timestamp>%{MONTHNUM}-%{MONTHDAY} %{TIME})\]

or

\[(?<timestamp>[^\]]+)\]


问:
Is there a Java class that is a cross between a Map and a List?
I am looking for a Java class that offers both Map (fast lookup) and List (determinate order) characteristics.  Any advice?

Thanks!

答: java.util.SortedMap keeps the keys in order</p>


问:
Unable to Inject ServletContext in application scoped CDI bean
I'm trying to inject ServletContext in application Scooped bean.

```<code>@Named("propertyProducer")
@ApplicationScoped
public class PropertyProducer {
    private Properties properties;
    @Inject
    private ServletContext servletContext;

    private String fileName = "app.properties";
</code>```

Its giving following exception-

```<code>#|2017-07-05T14:24:46.424+0530|SEVERE|glassfish3.1.2|javax.enterprise.system.tools.admin.org.glassfish.deployment.admin|_ThreadID=76;_ThreadName=Thread-2;|Exception while loading the app : WELD-001408 Unsatisfied dependencies for type [ServletContext] with qualifiers [@Default] at injection point [[field] @Inject com.advisory.compass.webapps.blocks.security.PropertyProducer.servletContext]
org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [ServletContext] with qualifiers [@Default] at injection point [[field] @Inject com.advisory.compass.webapps.blocks.security.PropertyProducer.servletContext]
    at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:311)
    at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:280)
    at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:143)
    at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:163)
    at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:382)
    at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:367)
    at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:380)
    at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:199)
    at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:128)
    at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:313)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:461)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:389)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:348)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:363)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1085)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:95)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1291)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1259)
    at org.glassfish.admin.rest.ResourceUtil.runCommand(ResourceUtil.java:214)
    at org.glassfish.admin.rest.ResourceUtil.runCommand(ResourceUtil.java:207)
    at org.glassfish.admin.rest.resources.TemplateListOfResource.createResource(TemplateListOfResource.java:148)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
    at com.sun.jersey.server.impl.uri.rules.SubLocatorRule.accept(SubLocatorRule.java:134)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.SubLocatorRule.accept(SubLocatorRule.java:134)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
    at com.sun.jersey.server.impl.container.grizzly.GrizzlyContainer._service(GrizzlyContainer.java:182)
    at com.sun.jersey.server.impl.container.grizzly.GrizzlyContainer.service(GrizzlyContainer.java:147)
    at org.glassfish.admin.rest.adapter.RestAdapter.service(RestAdapter.java:148)
    at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:179)
    at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$Hk2DispatcherCallable.call(ContainerMapper.java:354)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:745)
</code>```

答:
You inject ServletContext from package com.advisory.compass.webapps.blocks.security.PropertyProducer.servletContext

That is wrong. You should import javax.servlet.ServletContext.

```<code>package somePackage;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.servlet.ServletContext;

@ApplicationScoped
public class Appbean {

@Inject
private ServletContext servletContext;

public String greet() {
    return "Hello";
}

}
</code>```

Body:
I'm trying to inject ServletContext in application Scooped bean.

@Named("propertyProducer")
@ApplicationScoped
public class PropertyProducer {
    private Properties properties;
    @Inject
    private ServletContext servletContext;

    private String fileName = "app.properties";

Its giving following exception-

#|2017-07-05T14:24:46.424+0530|SEVERE|glassfish3.1.2|javax.enterprise.system.tools.admin.org.glassfish.deployment.admin|_ThreadID=76;_ThreadName=Thread-2;|Exception while loading the app : WELD-001408 Unsatisfied dependencies for type [ServletContext] with qualifiers [@Default] at injection point [[field] @Inject com.advisory.compass.webapps.blocks.security.PropertyProducer.servletContext]
org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [ServletContext] with qualifiers [@Default] at injection point [[field] @Inject com.advisory.compass.webapps.blocks.security.PropertyProducer.servletContext]
    at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:311)
    at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:280)
    at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:143)
    at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:163)
    at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:382)
    at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:367)
    at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:380)
    at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:199)
    at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:128)
    at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:313)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:461)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:389)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:348)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:363)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1085)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:95)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1291)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1259)
    at org.glassfish.admin.rest.ResourceUtil.runCommand(ResourceUtil.java:214)
    at org.glassfish.admin.rest.ResourceUtil.runCommand(ResourceUtil.java:207)
    at org.glassfish.admin.rest.resources.TemplateListOfResource.createResource(TemplateListOfResource.java:148)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
    at com.sun.jersey.server.impl.uri.rules.SubLocatorRule.accept(SubLocatorRule.java:134)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.SubLocatorRule.accept(SubLocatorRule.java:134)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
    at com.sun.jersey.server.impl.container.grizzly.GrizzlyContainer._service(GrizzlyContainer.java:182)
    at com.sun.jersey.server.impl.container.grizzly.GrizzlyContainer.service(GrizzlyContainer.java:147)
    at org.glassfish.admin.rest.adapter.RestAdapter.service(RestAdapter.java:148)
    at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:179)
    at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$Hk2DispatcherCallable.call(ContainerMapper.java:354)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:745)

Body:
You inject ServletContext from package com.advisory.compass.webapps.blocks.security.PropertyProducer.servletContext

That is wrong. You should import javax.servlet.ServletContext.

package somePackage;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.servlet.ServletContext;

@ApplicationScoped
public class Appbean {

@Inject
private ServletContext servletContext;

public String greet() {
    return "Hello";
}

}


问:
RxAndroidBle - RxBleDevice getName() always returns null
Having the following code

```<code>rxBleClient = RxBleClient.create(this);
        scanSubscription = rxBleClient.scanBleDevices(
                new ScanSettings.Builder()
                        .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                        .build())
                .subscribe(new Observer<ScanResult>() {
                               @Override
                               public void onCompleted() {
                                   Log.d(TAG_BT, "Scan completed");
                               }

                               @Override
                               public void onError(Throwable e) {
                                   Log.d(TAG_BT, "Scan onError", e);
                               }

                               @Override
                               public void onNext(ScanResult scanResult) {
                                   RxBleDevice device = scanResult.getBleDevice();
                                   Log.d(TAG_BT, "Scan - " + device.getName());
                                   if (device.getName() != null &&
                                           device.getName().contains(
                                                   SMParameters.SM_BLUETOOTH_SSID_PREFIX)) {
                                       connectToDevice(device);
                                   }
                               }
                           }
                );
</code>```

The results I get on every onNext() event are the following:

```<code>07-05 13:06:24.065 24390-24390/com.example.app D/TAG_BT: Scan - null
07-05 13:06:24.416 24390-24390/com.example.app D/TAG_BT: Scan - null
07-05 13:06:25.670 24390-24390/com.example.app D/TAG_BT: Scan - null
07-05 13:06:25.706 24390-24390/com.example.app D/TAG_BT: Scan - null
07-05 13:06:26.930 24390-24390/com.example.app D/TAG_BT: Scan - null
07-05 13:08:18.339 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:19.567 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:24.810 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:25.981 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:26.024 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:26.027 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:26.029 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:26.042 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:26.098 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:26.101 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:26.123 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:26.130 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:27.246 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:28.508 26550-26550/com.example.app D/TAG_BT: Scan - null
</code>```

Do I miss any configuration parameter? No error is thrown so if anyone has any clue...

Thanks!

答:
BluetoothDevice may have a null name if it is not broadcasted. You may alternatively check for a name from scanResult.getScanRecord().getDeviceName() though it also can be null.

This question was answered already
here or here.

Body:
Having the following code

rxBleClient = RxBleClient.create(this);
        scanSubscription = rxBleClient.scanBleDevices(
                new ScanSettings.Builder()
                        .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                        .build())
                .subscribe(new Observer<ScanResult>() {
                               @Override
                               public void onCompleted() {
                                   Log.d(TAG_BT, "Scan completed");
                               }

                               @Override
                               public void onError(Throwable e) {
                                   Log.d(TAG_BT, "Scan onError", e);
                               }

                               @Override
                               public void onNext(ScanResult scanResult) {
                                   RxBleDevice device = scanResult.getBleDevice();
                                   Log.d(TAG_BT, "Scan - " + device.getName());
                                   if (device.getName() != null &&
                                           device.getName().contains(
                                                   SMParameters.SM_BLUETOOTH_SSID_PREFIX)) {
                                       connectToDevice(device);
                                   }
                               }
                           }
                );

The results I get on every onNext() event are the following:

07-05 13:06:24.065 24390-24390/com.example.app D/TAG_BT: Scan - null
07-05 13:06:24.416 24390-24390/com.example.app D/TAG_BT: Scan - null
07-05 13:06:25.670 24390-24390/com.example.app D/TAG_BT: Scan - null
07-05 13:06:25.706 24390-24390/com.example.app D/TAG_BT: Scan - null
07-05 13:06:26.930 24390-24390/com.example.app D/TAG_BT: Scan - null
07-05 13:08:18.339 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:19.567 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:24.810 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:25.981 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:26.024 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:26.027 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:26.029 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:26.042 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:26.098 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:26.101 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:26.123 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:26.130 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:27.246 26550-26550/com.example.app D/TAG_BT: Scan - null
07-05 13:08:28.508 26550-26550/com.example.app D/TAG_BT: Scan - null

Do I miss any configuration parameter? No error is thrown so if anyone has any clue...

Thanks!


问:
Add classpath in manifest using Gradle
I would like my Gradle build script to add the complete Classpath to the manifest file contained in JAR file created after the build.

Example:

```<code>Manifest-Version: 1.0
Class-Path: MyProject.jar SomeLibrary.jar AnotherLib.jar
</code>```

My build script already add some information to the manifest this way:

```<code>jar {
    manifest {
        attributes("Implementation-Title": project.name,
            "Implementation-Version": version,
            "Main-Class": mainClassName,
    }
}
</code>```

How do I get the list of dependencies to add to the manifest?

This page of Java tutorials describes more in detail how and why adding classpath to the manifest: Adding Classes to the JAR File's Classpath

答:
In the latest versions of gradle, compile and runtime becomes deprecated. Instead, use runtimeClasspath as follows:

```<code>'Class-Path': configurations.runtimeClasspath.files.collect { it.getName() }.join(' ')
</code>```

EDIT:

Note that if you are using Kotlin DSL, you can configure the manifest as follows:

```<code>configure<JavaPluginConvention> {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8
    manifest {
        attributes(
                "Manifest-Version" to "1.0",
                "Main-Class" to "io.fouad.AppLauncher")
    }
}
</code>```

```<code>tasks.withType(Jar::class) {
    manifest {
        attributes["Manifest-Version"] = "1.0"
        attributes["Main-Class"] = "io.fouad.AppLauncher"
    }
}
</code>```

Title: Add classpath in manifest using Gradle

Body:
I would like my Gradle build script to add the complete Classpath to the manifest file contained in JAR file created after the build.

Example:

Manifest-Version: 1.0
Class-Path: MyProject.jar SomeLibrary.jar AnotherLib.jar

My build script already add some information to the manifest this way:

jar {
    manifest {
        attributes("Implementation-Title": project.name,
            "Implementation-Version": version,
            "Main-Class": mainClassName,
    }
}

How do I get the list of dependencies to add to the manifest?

This page of Java tutorials describes more in detail how and why adding classpath to the manifest: Adding Classes to the JAR File's Classpath

Body:
In the latest versions of gradle, compile and runtime becomes deprecated. Instead, use runtimeClasspath as follows:

'Class-Path': configurations.runtimeClasspath.files.collect { it.getName() }.join(' ')

EDIT:

Note that if you are using Kotlin DSL, you can configure the manifest as follows:

configure<JavaPluginConvention> {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8
    manifest {
        attributes(
                "Manifest-Version" to "1.0",
                "Main-Class" to "io.fouad.AppLauncher")
    }
}

tasks.withType(Jar::class) {
    manifest {
        attributes["Manifest-Version"] = "1.0"
        attributes["Main-Class"] = "io.fouad.AppLauncher"
    }
}


问:
Appropriate encryption for financial data
I'm currently building a web application(PHP/MySQL) which saves data from persons. Most of this data is not worth protecting with encryption but some of it is financial information like income and so on. It is not a payment application and does not store information that could be turned into money directly like credit card information but still stuff you don't want to have in a possible leak. This platform has to be sold to customers that want "security", but that can mean anything as the customers themselves do not have any knowledge what they really want, since they are business people and not cryptographers(like me neither).

It is a management platform so the people that have their financial data saved there are not the users of the platform. Users of the platform are merely a login with permissions attached to them. The server itself never has to have access the data. Every operation is done by a user(could also be an admin) that is logged in. Multiple users need to have access to the same data given they have enough permissions.

My question is now how I can protect the financial data from these threats:

Somebody finds an SQL-injection and dumps all tables remotely

Somebody steals the hard drive of the server (database + code)

Where I'm certainly not going: Large scale sniffing attack or compromised servers(like sniffing all traffic on the server itself where SSL doesn't matter) or social engineering/phishing.

I would also like to have a quick summary how much more information(keys, data, etc.) I have to store in comparison to the current system, where there is one simple field for income etc. and a standard login system with username and hashed password.

EDIT: Reformulated question almost entirely following the suggestion of comments/answers

答:
From your question, the following key points stand out.

The server itself never has to have access to the data.

Multiple users need to have access to the same data given they have enough permissions.

Maintain security even if:

Somebody finds an SQL-injection and dumps all tables remotely.

Somebody steals the hard drive of the server (database + code).

This is possible to achieve, but not trivial.  The thing that makes this possible is the fact that the server does not require access to the data.  This allows us to use user passwords to derive keys.

Each level in your permission structure will have an associated key.  This key will be used to encrypt data that can be viewed with those permissions.  When the first administrative account is created, generate a key for each level in your permission structure and use the administrative password as an input for a KDF and derive a key.  Use this password-derived key to encrypt each permission key and store the resulting ciphertexts alongside the administrative account.

As new users are created and assigned ranks by the administrative account, pull the highest level permission key that the new user will have access to, as well as any keys at a lower permission, decrypt them with the administrative password (which will be required for creating users) and then encrypt them again with the new users password and store alongside the new user in the database.

This system allows you to pass the required encryption keys to each user and makes accessing data above the users permission level cryptographically impossible.

At this point, it is rather straight forward for you to allow users to access data by simply taking their password, decrypting the relevant permission key and then using that key to decrypt the data.  Users changing their password is also trivial as it simply means you have to decrypt the permission keys with the old password then re-encrypt with the new password.

At a more technical level, I would recommend the following:

Use AES.  AES-256 tends to be the most common but AES-128 is just as secure in the grand scheme of things.  Use of an authenticated block mode (GCM) isn't as important here but is still recommended.   If not, use a mode like CBC or CTR with an HMAC.

Never use a password directly as a key.  Use PBKDF2 to generate keys from passwords.  Using AES-256 fits in nicely here because you can use SHA-256 as the primitive to PBKDF2 and get output the same length as the internal hash function.

Generate a new random IV every time you encrypt using a CSPRNG.  Prefix the IV to the ciphertext.  Don't derive an IV from PBKDF2 like the key.


答:
Have you tried #rightbutton { float: right; }?

Edit: hunter beat me to it!

Title: What CSS would get two buttons to line up, respectively, on the left and right side of a 3-colspan table cell?

Body:
I have a table like this:

    short text
    long long long text
    short text

      <button id='leftbutton'/>
      <button id='rightbutton'/>

What CSS styles should I apply to get my buttons to lay out like this:

-----------------------------------------------------------------
|short text       |      long long long text     |  short text  |
-----------------------------------------------------------------
| button left     |                              | button right |
-----------------------------------------------------------------

instead of their current layout:

-----------------------------------------------------------------
|short text       |      long long long text     |  short text  |
-----------------------------------------------------------------
|button left|button right|
-----------------------------------------------------------------


问:
javascript onclick create element (label)
I am currently developing a webapp, draft link: http://webtrickssolutions.in/ayna/new-Building.html#

i have problem with javascript coding, when pressing on "OK" button, it should add a row underneath the filled data "Language" and "Text" / the new row should be Label. for example if i added two times:

English "BuildingName01" (delete icon)
Arabic  "XXXXX05" (delete icon)

and it should remove the English and Arabic from the drop down menu as i cant select the language twice.

current javascript code is:

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

        $('.del').live('click',function(){
            $(this).parent().parent().remove();
        });

        $('.add').live('click',function(){
            $(this).val('Delete');
            $(this).attr('class','del');

            var appendTxt = "<tr><td><select class='form-control form-control-bottom lang' name='input_box_one[]'><option>Language</option><option>English</option><option>Hindi</option></select></td> <td><input type='text' name='input_box_two[]' /></td> <td><input type='button' class='add' value='Ok' /></td></tr>";

            $("#options-table tr:first").before(appendTxt);
        });
    });
</script>
</code>```

答:
On click of the OK button you can remove the particular option:</p>

```<code>var item = "Hindi";
$("select option:contains('"+item+"')").remove();
</code>```

Body:
On click of the OK button you can remove the particular option:

var item = "Hindi";
$("select option:contains('"+item+"')").remove();


问:
JQuery .on works on first html but doesn't work on the second(same form)
So, I have this form that I used on both my html page and .on works on the first one but doesn't work on the second one even though all properties are same.

First HTML:

```<code><div id="page1" class="row" style="text-align: center;">
            <h2 style="text-align: center;">Category</h2>
            <div class="btn-group" data-toggle="buttons" >
              <label class="btn btn-primary <?php echo $_SESSION['editEntry'][0]['category']=='Food'?'active':''; ?>">
                <input type="radio" name="category" id="food" autocomplete="off" <?php echo $_SESSION['editEntry'][0]['category']=='Food'?'checked':''; ?> value="Food"> Food
              </label>
              <label class="btn btn-primary <?php echo $_SESSION['editEntry'][0]['category']=='Non-Food'?'active':''; ?>">
                <input type="radio" name="category" id="non-food" autocomplete="off" <?php echo $_SESSION['editEntry'][0]['category']=='Non-Food'?'checked':''; ?> value="Non-Food"> Non-Food
              </label>
              <label class="btn btn-primary <?php echo $_SESSION['editEntry'][0]['category']=='Services'?'active':''; ?>">
                <input type="radio" name="category" id="services" autocomplete="off" <?php echo $_SESSION['editEntry'][0]['category']=='Services'?'checked':''; ?> value="Services"> Services
              </label>
              <label class="btn btn-primary <?php echo $_SESSION['editEntry'][0]['category']=='Technology'?'active':''; ?>">
                <input type="radio" name="category" id="technology" autocomplete="off" <?php echo $_SESSION['editEntry'][0]['category']=='Technology'?'checked':''; ?> value="Technology"> Technology
              </label>
            </div>

            <div class="box-footer">
              <div class="pull-right">
                <button type="button" id="next1" class="btn btn-primary"><i class="glyphicon glyphicon-chevron-right"></i> Next</button>
              </div>
            </div>
            <!-- /.box-footer -->
        </div>
</code>```

Second HTML:

```<code><div id="page1" class="row" style="text-align: center;">
                <h2 style="text-align: center;">Category</h2>
                <div class="btn-group" data-toggle="buttons" >
                  <label class="btn btn-primary active">
                    <input type="radio" name="category" id="food" autocomplete="off" checked value="Food"> Food
                  </label>
                  <label class="btn btn-primary">
                    <input type="radio" name="category" id="non-food" autocomplete="off" value="Non-Food"> Non-Food
                  </label>
                  <label class="btn btn-primary">
                    <input type="radio" name="category" id="services" autocomplete="off" value="Services"> Services
                  </label>
                  <label class="btn btn-primary">
                    <input type="radio" name="category" id="technology" autocomplete="off" value="Technology"> Technology
                  </label>
                </div>

                <div class="box-footer">
                  <div class="pull-right">
                      <button type="button" id="next1" class="btn btn-primary"><i class="glyphicon glyphicon-chevron-right"></i> Next</button>
                  </div>
                </div>
                <!-- /.box-footer -->
            </div>
</code>```

JS:

```<code>$("#page1").on('click', '#next1, #next2, #next3, #next4, #next5', function(e){
e.preventDefault();
nextPage($(this).attr('id'));
});

function nextPage(selector){
switch(selector){
    case 'next1':
        $("#page1").attr("hidden", "hidden");
        $("#page2").removeAttr("hidden");
        break;
    case 'next2':
        if($("input[name='title']").val() == '' || $("textarea[name='description']").val() == ''){
            alert("Fill up the fields to continue..");
        }else{
            $("#page2").attr("hidden", "hidden");
            $("#page3").removeAttr("hidden");
            $(".certTitle").html($('#page2 input[name="title"]').val());
        }
        break;
    case 'next3':
        if($("input[name='college']").val() == '' || $("input[name='collegeAddress']").val() == '' || $("input[name='collegeDean']").val() == '' || $("input[name='coach']").val() == '' || $("input[name='contactPerson']").val() == '' || $("input[name='landline']").val() == '' || $("input[name='mobile']").val() == '' || $("input[name='email']").val() == ''){
            alert("Fill up the fields to continue..");
        }else{
            $("#page3").attr("hidden", "hidden");
            $("#page4").removeAttr("hidden");
            $("#certDean").html($("input[name='collegeDean']").val().toUpperCase());
            $("#certCoach").html($("input[name='coach']").val());
        }
        break;
    case 'next4':
        var empty = $("#students").find("input").filter(function() {
            if($(".setContact").val() == ""){
                return this.value = 1;
            }else{
                return this.value === "";
            }
        });
        if(contactPersonCount < 2){
            alert("Please select at least 2 alternative contact persons..");
        }else if($("input[name='firstname']").val() == '' || $("input[name='lastname']").val() == '' || $("input[name='email']").val() == '' || $("input[name='studentMobile']").val() == '' || $("input[name='dob']").val() == '' || empty.length){
            alert("Fill up the fields to continue..");
        }else{
            $("#page4").attr("hidden", "hidden");
            $("#page5").removeAttr("hidden");
            var currentCount = $("#students div").length;
            var studentsList = [];
            console.log(currentCount);
            for(var i = 1; i <= currentCount; i++){
                studentsList[i] = $("#students input[name='firstname"+i+"']").val() + " " + $("#students input[name='lastname"+i+"']").val();

            }
            $("#studentsList").children().remove();
            for(var i = 1; i <= currentCount; i++){
                $("#studentsList").append("<li>"+ studentsList[i] +"</li>");
            }
        }
        break;
    case 'next5':
        if($("input[name='presentationUpload']").val() == '' || $("input[name='documentUpload']").val() == ''){
            alert("Fill up the fields to continue..");
        }else{
            $("#page5").attr("hidden", "hidden");
            $("#page6").removeAttr("hidden");
        }
        break;
    default:
        console.log("Invalid Selector: " + selector);
        break;
   }
 }
</code>```

I'm not sure why it doesn't trigger on the second one even if both of them have the same attributes.

NOTE: Those HTML codes resides on different HTML files but uses the same JS.

答:
If you replace the whole
 then you lose the event listener attached to $("#page1") because that element is removed...even though it is replaced with a new one with same ID

Move the delegation higher to an asset that is permanent

Try:

```<code>$(document).on('click', '#next1, #next2, #next3, #next4, #next5', function(e){
    e.preventDefault();
    nextPage($(this).attr('id'));
});
</code>```

Body:
So, I have this form that I used on both my html page and .on works on the first one but doesn't work on the second one even though all properties are same.

First HTML:

Category

              <label class="btn btn-primary <?php echo $_SESSION['editEntry'][0]['category']=='Food'?'active':''; ?>">
                <input type="radio" name="category" id="food" autocomplete="off" <?php echo $_SESSION['editEntry'][0]['category']=='Food'?'checked':''; ?> value="Food"> Food

              <label class="btn btn-primary <?php echo $_SESSION['editEntry'][0]['category']=='Non-Food'?'active':''; ?>">
                <input type="radio" name="category" id="non-food" autocomplete="off" <?php echo $_SESSION['editEntry'][0]['category']=='Non-Food'?'checked':''; ?> value="Non-Food"> Non-Food

              <label class="btn btn-primary <?php echo $_SESSION['editEntry'][0]['category']=='Services'?'active':''; ?>">
                <input type="radio" name="category" id="services" autocomplete="off" <?php echo $_SESSION['editEntry'][0]['category']=='Services'?'checked':''; ?> value="Services"> Services

              <label class="btn btn-primary <?php echo $_SESSION['editEntry'][0]['category']=='Technology'?'active':''; ?>">
                <input type="radio" name="category" id="technology" autocomplete="off" <?php echo $_SESSION['editEntry'][0]['category']=='Technology'?'checked':''; ?> value="Technology"> Technology

                <button type="button" id="next1" class="btn btn-primary"> Next</button>

Second HTML:

Category

                    <input type="radio" name="category" id="food" autocomplete="off" checked value="Food"> Food

                    <input type="radio" name="category" id="non-food" autocomplete="off" value="Non-Food"> Non-Food

                    <input type="radio" name="category" id="services" autocomplete="off" value="Services"> Services

                    <input type="radio" name="category" id="technology" autocomplete="off" value="Technology"> Technology

                      <button type="button" id="next1" class="btn btn-primary"> Next</button>

JS:

$("#page1").on('click', '#next1, #next2, #next3, #next4, #next5', function(e){
e.preventDefault();
nextPage($(this).attr('id'));
});

function nextPage(selector){
switch(selector){
    case 'next1':
        $("#page1").attr("hidden", "hidden");
        $("#page2").removeAttr("hidden");
        break;
    case 'next2':
        if($("input[name='title']").val() == '' || $("textarea[name='description']").val() == ''){
            alert("Fill up the fields to continue..");
        }else{
            $("#page2").attr("hidden", "hidden");
            $("#page3").removeAttr("hidden");
            $(".certTitle").html($('#page2 input[name="title"]').val());
        }
        break;
    case 'next3':
        if($("input[name='college']").val() == '' || $("input[name='collegeAddress']").val() == '' || $("input[name='collegeDean']").val() == '' || $("input[name='coach']").val() == '' || $("input[name='contactPerson']").val() == '' || $("input[name='landline']").val() == '' || $("input[name='mobile']").val() == '' || $("input[name='email']").val() == ''){
            alert("Fill up the fields to continue..");
        }else{
            $("#page3").attr("hidden", "hidden");
            $("#page4").removeAttr("hidden");
            $("#certDean").html($("input[name='collegeDean']").val().toUpperCase());
            $("#certCoach").html($("input[name='coach']").val());
        }
        break;
    case 'next4':
        var empty = $("#students").find("input").filter(function() {
            if($(".setContact").val() == ""){
                return this.value = 1;
            }else{
                return this.value === "";
            }
        });
        if(contactPersonCount < 2){
            alert("Please select at least 2 alternative contact persons..");
        }else if($("input[name='firstname']").val() == '' || $("input[name='lastname']").val() == '' || $("input[name='email']").val() == '' || $("input[name='studentMobile']").val() == '' || $("input[name='dob']").val() == '' || empty.length){
            alert("Fill up the fields to continue..");
        }else{
            $("#page4").attr("hidden", "hidden");
            $("#page5").removeAttr("hidden");
            var currentCount = $("#students div").length;
            var studentsList = [];
            console.log(currentCount);
            for(var i = 1; i <= currentCount; i++){
                studentsList[i] = $("#students input[name='firstname"+i+"']").val() + " " + $("#students input[name='lastname"+i+"']").val();

            }
            $("#studentsList").children().remove();
            for(var i = 1; i <= currentCount; i++){
                $("#studentsList").append("
"+ studentsList[i] +"
");
            }
        }
        break;
    case 'next5':
        if($("input[name='presentationUpload']").val() == '' || $("input[name='documentUpload']").val() == ''){
            alert("Fill up the fields to continue..");
        }else{
            $("#page5").attr("hidden", "hidden");
            $("#page6").removeAttr("hidden");
        }
        break;
    default:
        console.log("Invalid Selector: " + selector);
        break;
   }
 }

I'm not sure why it doesn't trigger on the second one even if both of them have the same attributes.

NOTE: Those HTML codes resides on different HTML files but uses the same JS.

Body:
If you replace the whole <div id="page1"> then you lose the event listener attached to $("#page1") because that element is removed...even though it is replaced with a new one with same ID

Move the delegation higher to an asset that is permanent

Try:

$(document).on('click', '#next1, #next2, #next3, #next4, #next5', function(e){
    e.preventDefault();
    nextPage($(this).attr('id'));
});


问:
Invalid Token 'String' in class, struct or interface member declaration
I'm having error with my code "Invalid Token 'String' in class, struct or interface member declaration" please help.

```<code>private void string InsertRecords(TextBox textboxname, string qryname, string parametername)
{
    string msg;

    if (textboxname.Text != "")
    {
        ConnString conn = new ConnString();
        string MyConn = conn.GetConn(); // Get Connection String

        using (SqlConnection sqlconn = new SqlConnection(MyConn))
        {
            try
            {
                SqlCommand cmd = new SqlCommand();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = qryname;
                cmd.Parameters.AddWithValue("@" + parametername, SqlDbType.VarChar).Value = textboxname.Text;
                cmd.Connection = sqlconn;
                sqlconn.Open();
                cmd.ExecuteNonQuery();

                msg = $"<strong>Record Successfully Added!</strong>";
                return msg;
            }
            catch (Exception ex)
            {
                if (ex.HResult == -2146232060)
                {
                    msg = $"<strong>Record already exist in the database!</strong>";
                    return msg;
                }
                else
                {
                    msg = $"<strong>Error Message: {ex.HResult}</strong>";
                    return msg;
                }
            }
        }
    }
    else
    {
        msg = $"<strong>Please complete required fields</strong>";
        return msg;
    }
}
</code>```

I'm trying to just return the message string and grab that message once called. thank you!

答:
You can't return string and have no return value (void) at the same time. Since you want to return a value remove void

```<code>private string InsertRecords(TextBox textboxname, string qryname, string parametername) { }
</code>```

Body:
I'm having error with my code "Invalid Token 'String' in class, struct or interface member declaration" please help.

private void string InsertRecords(TextBox textboxname, string qryname, string parametername)
{
    string msg;

    if (textboxname.Text != "")
    {
        ConnString conn = new ConnString();
        string MyConn = conn.GetConn(); // Get Connection String

        using (SqlConnection sqlconn = new SqlConnection(MyConn))
        {
            try
            {
                SqlCommand cmd = new SqlCommand();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = qryname;
                cmd.Parameters.AddWithValue("@" + parametername, SqlDbType.VarChar).Value = textboxname.Text;
                cmd.Connection = sqlconn;
                sqlconn.Open();
                cmd.ExecuteNonQuery();

                msg = $"Record Successfully Added!";
                return msg;
            }
            catch (Exception ex)
            {
                if (ex.HResult == -2146232060)
                {
                    msg = $"Record already exist in the database!";
                    return msg;
                }
                else
                {
                    msg = $"Error Message: {ex.HResult}";
                    return msg;
                }
            }
        }
    }
    else
    {
        msg = $"Please complete required fields";
        return msg;
    }
}

I'm trying to just return the message string and grab that message once called. thank you!

Body:
You can't return string and have no return value (void) at the same time. Since you want to return a value remove void

private string InsertRecords(TextBox textboxname, string qryname, string parametername) { }


问:
How to use express-mysql-session in Typescript projects?
I'm trying to use express-session and express-mysql-session within a Typescript project. Here's the relevant part of my code:

```<code>import * as express from "express";
import * as expressSession from "express-session";
import * as expressMySqlSession from "express-mysql-session";

this.express = express();
const sessionStore = new expressMySqlSession(sessionStoreConfig, this.dbConnection);
const sessionHandler = expressSession({
                ...,
                store: sessionStore
            });
this.express.use(sessionHandler);
</code>```

It does not compile because the store option is of type expressSession.Store | expressSession.MemoryStore | undefined while sessionStore is of type MySQLStore.
What am I doing wrong?

Regards

答:
Try this:</p>

```<code>import * as express        from "express";
import * as expressSession from "express-session";
import expressMySqlSession from "express-mysql-session";

const MySQLStore   = expressMySqlSession(expressSession);
const sessionStore = new MySQLStore(sessionStoreConfig, this.dbConnection);
...
</code>```

Body:
I'm trying to use express-session and express-mysql-session within a Typescript project. Here's the relevant part of my code:

import * as express from "express";
import * as expressSession from "express-session";
import * as expressMySqlSession from "express-mysql-session";

this.express = express();
const sessionStore = new expressMySqlSession(sessionStoreConfig, this.dbConnection);
const sessionHandler = expressSession({
                ...,
                store: sessionStore
            });
this.express.use(sessionHandler);

It does not compile because the store option is of type expressSession.Store | expressSession.MemoryStore | undefined while sessionStore is of type MySQLStore.
What am I doing wrong?

Regards

Body:
Try this:

import * as express        from "express";
import * as expressSession from "express-session";
import expressMySqlSession from "express-mysql-session";

const MySQLStore   = expressMySqlSession(expressSession);
const sessionStore = new MySQLStore(sessionStoreConfig, this.dbConnection);
...


问:
How can we take more than one input values in python language by using comma or space between two numbers or character
How can we take more than one input values in python language by using comma or space between two numbers or character??</p>

答:
Simply try:

In Python2:

```<code>i = raw_input("Whatever:")

u , c= i.split()
</code>```

In Python3:

```<code>i = input("Whatever:")

u ,c = i.split()
</code>```

Hope this helps :)

Body:
Simply try:

In Python2:

i = raw_input("Whatever:")

u , c= i.split()

In Python3:

i = input("Whatever:")

u ,c = i.split()

Hope this helps :)


问:
Visual Basic format number to hower many number on left of decimal and 1 decimal without rounding
I am acutally using SSRS but it is for an expression so this is VB code. I am wondering how I would get a number such as 236.4723423 to appear at 236.4 instead of 236.5, so basically I jsut want to truncate it always after 1 decimal.

I tried Format = "N1" this rounds it
I tried Formate = "#######.0" and "######.#" and this rounds it as well.

Any ideas?

答: You will probably want to implement a custom IFormatProvider interface to do this. There is a great example on MSDN here.</p>