问:
Get derived class with base class function
I need to do some equality checks with different types on a class hierarchy. In pseudo code:

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

using namespace std;

class ComplexType {};

class Property {};

class IntegerProperty : public Property {
public:
    int inner;
};

class StringProperty : public Property {
public:
    string inner;
};

class ComplexTypeProperty : public Property {
    ComplexType inner;
};

int main() {
    shared_ptr<Property> p1 = getSomewhere(); //this is in fact a pointer on IntegerProperty
    shared_ptr<Property> p2 = getSomewhere(); // this is in fact a pointer on StringProperty
    shared_ptr<Property> p3 = getSomewhere(); // this is in fact a pointer on CompleyTypeProperty

    ComplexType c;

    cout << ((*p1) == 2);
    cout << ((*p2) == "foo");
    cout << ((*p3) == c);
}
</code>```

It it simple to provide a operator== for the derived classes, but I cannot cast before checking, because the type of p1 and p2 is not clear at compile time.

Another way I know is to write the operator== function in the Property base class and throw some exceptions if the type is wrong, but I want, that the Property class can be subclassed later without changing the code for Property and it will work, too.

Templating Property is also not (directly) possible, because e.g. in my code a vector<shared_ptr<Property>> has to exist.

Is there some (generic) way to implement main() to get the equality checks, so that later subclassing of Property without changing the class itself is possible?

答:
Have found some way of solving this. I'm not quite happy with the code. So if anyone has a better solution, please provide it.</p>

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

using namespace std;

class ComplexType {
public:
    bool operator==(const ComplexType& i) {
        return true;
    }
};
inline ostream& operator<<(ostream& os, const ComplexType& c) {
    os << "ComplexType";
    return os;
}

class Property {
public:
    virtual ~Property() {}
};

template <class T>
class LayerProperty : public Property {
private:
    T inner;

public:
    LayerProperty(T t) : inner(t) {}
    bool operator==(const T i) {
        return inner == i;
    }
};

int main() {
    shared_ptr<Property> p1 = make_shared<LayerProperty<int>>(LayerProperty<int>(5));
    shared_ptr<Property> p2 = make_shared<LayerProperty<string>>(LayerProperty<string>("foo"));
    shared_ptr<Property> p3 = make_shared<LayerProperty<ComplexType>>(LayerProperty<ComplexType>(ComplexType()));

    ComplexType c;

    cout << ((*dynamic_pointer_cast<LayerProperty<decltype(2)>>(p1)) == 2) << "\n";
    // special case std::string
    auto a = "foo";
    auto s = "";
    if (typeid(a) == typeid(s)) {
        cout << ((*dynamic_pointer_cast<LayerProperty<decltype(string(a))>>(p2)) == a) << "\n";
    }
    cout << ((*dynamic_pointer_cast<LayerProperty<decltype(c)>>(p3)) == c) << "\n";
    return 0;
}
</code>```

Body:
I need to do some equality checks with different types on a class hierarchy. In pseudo code:

#include <string>
#include <memory>
#include <iostream>

using namespace std;

class ComplexType {};

class Property {};

class IntegerProperty : public Property {
public:
    int inner;
};

class StringProperty : public Property {
public:
    string inner;
};

class ComplexTypeProperty : public Property {
    ComplexType inner;
};

int main() {
    shared_ptr<Property> p1 = getSomewhere(); //this is in fact a pointer on IntegerProperty
    shared_ptr<Property> p2 = getSomewhere(); // this is in fact a pointer on StringProperty
    shared_ptr<Property> p3 = getSomewhere(); // this is in fact a pointer on CompleyTypeProperty

    ComplexType c;

    cout << ((*p1) == 2);
    cout << ((*p2) == "foo");
    cout << ((*p3) == c);
}

It it simple to provide a operator== for the derived classes, but I cannot cast before checking, because the type of p1 and p2 is not clear at compile time.

Another way I know is to write the operator== function in the Property base class and throw some exceptions if the type is wrong, but I want, that the Property class can be subclassed later without changing the code for Property and it will work, too.

Templating Property is also not (directly) possible, because e.g. in my code a vector<shared_ptr<Property>> has to exist.

Is there some (generic) way to implement main() to get the equality checks, so that later subclassing of Property without changing the class itself is possible?

Body:
Have found some way of solving this. I'm not quite happy with the code. So if anyone has a better solution, please provide it.

#include <string>
#include <memory>
#include <iostream>

using namespace std;

class ComplexType {
public:
    bool operator==(const ComplexType& i) {
        return true;
    }
};
inline ostream& operator<<(ostream& os, const ComplexType& c) {
    os << "ComplexType";
    return os;
}

class Property {
public:
    virtual ~Property() {}
};

template <class T>
class LayerProperty : public Property {
private:
    T inner;

public:
    LayerProperty(T t) : inner(t) {}
    bool operator==(const T i) {
        return inner == i;
    }
};

int main() {
    shared_ptr<Property> p1 = make_shared<LayerProperty<int>>(LayerProperty<int>(5));
    shared_ptr<Property> p2 = make_shared<LayerProperty<string>>(LayerProperty<string>("foo"));
    shared_ptr<Property> p3 = make_shared<LayerProperty<ComplexType>>(LayerProperty<ComplexType>(ComplexType()));

    ComplexType c;

    cout << ((*dynamic_pointer_cast<LayerProperty<decltype(2)>>(p1)) == 2) << "\n";
    // special case std::string
    auto a = "foo";
    auto s = "";
    if (typeid(a) == typeid(s)) {
        cout << ((*dynamic_pointer_cast<LayerProperty<decltype(string(a))>>(p2)) == a) << "\n";
    }
    cout << ((*dynamic_pointer_cast<LayerProperty<decltype(c)>>(p3)) == c) << "\n";
    return 0;
}


来源: stackexchange

问:
Formatted toString()
I am beginner using the toString() method to return a formatted String. I am printing a deck of cards where each column is the different suit. Does anyone have any ideas? Here is the code I have:

```<code>public class DeckOfCards {
  public static void main(String[] args) {
    int[] deck = new int[52];
    //String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
    String[] suits = {"Clubs","Diamonds","Hearts","Spades"};
    //String[] ranks = {"Ace","King", "Queen", "Jack", "10", "9", "8", "7", "6", "5", "4", "3", "2"};
    String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King","Ace"};

    // Initialize cards
        for (int i = 0; i < deck.length; i++) {
            deck[i] = i;
        }

        // Shuffle the cards
        for (int i = 0; i < deck.length; i++) {
            int index = (int)(Math.random() * deck.length);
            int temp = deck[i];
            deck[i] = deck[index];
            deck[index] = temp;
        }

        // Display the all the cards
        for (int i = 0; i < 52; i++) {
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.println( rank + " of " + suit);
        }

        System.out.println("------------------------------");

        for(int i=0;i<deck.length;i++){
            for(int j=i;j<deck.length;j++){
                if(deck[j]==51-i){
                    int temp = deck[i];
                    deck[i] = deck[j];
                    deck[j] = temp;
                }
            }
        }

        // Display the all the cards
        for (int i = 0; i < 52; i++) {
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.printf( rank + " of " + suit + "\t");
        }

    }
  }
</code>```

The main area I believe will be in the toString() is here:

```<code>// Display the all the cards
        for (int i = 0; i < 52; i++) {
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.println( rank + " of " + suit);
        }
</code>```

How would I use this in the toString() method and also instantiate an object that can print this toString() method? Thank you for your time. So that it displays in order in a game of bridge I was thinking of an output like this:

```<code>Ace of Spades     Ace of Hearts     Ace of Diamonds     Ace of Clubs
...
// And so on until it reaches two of clubs
</code>```

Do any of these ways print it like such without one being extra spaced or if not what could be modified in the toString() to have it come out like that? Thank you for your time, again.

答:
You must create a new class of Cards and have a overriden string class

so like below

```<code>public class Cards {

    private int numb;
    private int suite;

    public Cards(int suite, int numb) {
        this.numb = numb;
        this.suite = suite;
    }

    public int getNumb() {

        if (numb == 0){
            return 11;
        }

        if (numb >= 9 && numb <=12){
            return 10;
        }

        return numb + 1;
    }

    @Override
    public String toString() {

        String arbNumb = null;
        String arbSuite = null;

        switch (suite){

        case 0:
            arbSuite = "Heart";
            break;

        case 1:
            arbSuite = "Diamond";
            break;

        case 2:
            arbSuite = "Spades";
            break;

        case 3:
            arbSuite = "Clubs";
            break;

        }

        switch (numb){

        case 0:
            arbNumb = "Ace";
            break;

        case 10:
            arbNumb = "Jack";
            break;

        case 11:
            arbNumb = "Queen";
            break;

        case 12:
            arbNumb = "King";
            break;

        }

        if (numb > 0 && numb < 10){
            arbNumb = String.valueOf(numb+1);
        }

        return arbNumb + " of " + arbSuite;
    }

}
</code>```

What it means is that when you instantiate the class Cards, numbers will be converted to the corresponding strings when you call yourInstanceOfClass.toString. You can do it for both suite and number.

The numbers that I have assigned is just how I would do it but you can change them to your preference of course.

The getNumb() class is just there to reflect the shift of numbers that I have made.

ContentLicense: CC BY-SA 3.0

Title: Formatted toString()

Body:
I am beginner using the toString() method to return a formatted String. I am printing a deck of cards where each column is the different suit. Does anyone have any ideas? Here is the code I have:

public class DeckOfCards {
  public static void main(String[] args) {
    int[] deck = new int[52];
    //String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
    String[] suits = {"Clubs","Diamonds","Hearts","Spades"};
    //String[] ranks = {"Ace","King", "Queen", "Jack", "10", "9", "8", "7", "6", "5", "4", "3", "2"};
    String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King","Ace"};

    // Initialize cards
        for (int i = 0; i < deck.length; i++) {
            deck[i] = i;
        }

        // Shuffle the cards
        for (int i = 0; i < deck.length; i++) {
            int index = (int)(Math.random() * deck.length);
            int temp = deck[i];
            deck[i] = deck[index];
            deck[index] = temp;
        }

        // Display the all the cards
        for (int i = 0; i < 52; i++) {
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.println( rank + " of " + suit);
        }

        System.out.println("------------------------------");

        for(int i=0;i<deck.length;i++){
            for(int j=i;j<deck.length;j++){
                if(deck[j]==51-i){
                    int temp = deck[i];
                    deck[i] = deck[j];
                    deck[j] = temp;
                }
            }
        }

        // Display the all the cards
        for (int i = 0; i < 52; i++) {
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.printf( rank + " of " + suit + "\t");
        }

    }
  }

The main area I believe will be in the toString() is here:

// Display the all the cards
        for (int i = 0; i < 52; i++) {
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.println( rank + " of " + suit);
        }

How would I use this in the toString() method and also instantiate an object that can print this toString() method? Thank you for your time. So that it displays in order in a game of bridge I was thinking of an output like this:

Ace of Spades     Ace of Hearts     Ace of Diamonds     Ace of Clubs
...
// And so on until it reaches two of clubs

Do any of these ways print it like such without one being extra spaced or if not what could be modified in the toString() to have it come out like that? Thank you for your time, again.

Body:
You must create a new class of Cards and have a overriden string class

so like below

public class Cards {

    private int numb;
    private int suite;

    public Cards(int suite, int numb) {
        this.numb = numb;
        this.suite = suite;
    }

    public int getNumb() {

        if (numb == 0){
            return 11;
        }

        if (numb >= 9 && numb <=12){
            return 10;
        }

        return numb + 1;
    }

    @Override
    public String toString() {

        String arbNumb = null;
        String arbSuite = null;

        switch (suite){

        case 0:
            arbSuite = "Heart";
            break;

        case 1:
            arbSuite = "Diamond";
            break;

        case 2:
            arbSuite = "Spades";
            break;

        case 3:
            arbSuite = "Clubs";
            break;

        }

        switch (numb){

        case 0:
            arbNumb = "Ace";
            break;

        case 10:
            arbNumb = "Jack";
            break;

        case 11:
            arbNumb = "Queen";
            break;

        case 12:
            arbNumb = "King";
            break;

        }

        if (numb > 0 && numb < 10){
            arbNumb = String.valueOf(numb+1);
        }

        return arbNumb + " of " + arbSuite;
    }

}

What it means is that when you instantiate the class Cards, numbers will be converted to the corresponding strings when you call yourInstanceOfClass.toString. You can do it for both suite and number.

The numbers that I have assigned is just how I would do it but you can change them to your preference of course.

The getNumb() class is just there to reflect the shift of numbers that I have made.


问:
SQL Generate Group Number Base on Parent Line
I have a ordered table here, the Parent_Flag column tells you which row is the parent and the following child would be put in the same group.
How can I create the desired_result column in SQL?

Example:

```<code>ID   Parent_Flag Desired_Result
001      P           1
001      C           1
001      C           1
002      P           2
002      C           2
002      P           3
</code>```

答:
For SQL server 2012+:

using a conditional aggregation window function sum() or count() with over():

note: I added an identity column to the sample data to derive an order for the rows.

```<code>select *
  , grp = sum(case when Parent_flag = 'P' then 1 else 0 end) over (order by i)
  , cgrp = count(case when Parent_flag = 'P' then 1 end) over (order by i)
from t
</code>```

rextester demo: http://rextester.com/SMLN40470

returns:

```<code>+---+-----+-------------+-----+------+
| i | id  | parent_flag | grp | cgrp |
+---+-----+-------------+-----+------+
| 1 | 001 | P           |   1 |    1 |
| 2 | 001 | C           |   1 |    1 |
| 3 | 001 | C           |   1 |    1 |
| 4 | 002 | P           |   2 |    2 |
| 5 | 002 | C           |   2 |    2 |
| 6 | 002 | P           |   3 |    3 |
+---+-----+-------------+-----+------+
</code>```

Body:
I have a ordered table here, the Parent_Flag column tells you which row is the parent and the following child would be put in the same group.
How can I create the desired_result column in SQL?

Example:

ID   Parent_Flag Desired_Result
001      P           1
001      C           1
001      C           1
002      P           2
002      C           2
002      P           3

Body:
For SQL server 2012+:

using a conditional aggregation window function sum() or count() with over():

note: I added an identity column to the sample data to derive an order for the rows.

select *
  , grp = sum(case when Parent_flag = 'P' then 1 else 0 end) over (order by i)
  , cgrp = count(case when Parent_flag = 'P' then 1 end) over (order by i)
from t

rextester demo: http://rextester.com/SMLN40470

returns:

+---+-----+-------------+-----+------+
| i | id  | parent_flag | grp | cgrp |
+---+-----+-------------+-----+------+
| 1 | 001 | P           |   1 |    1 |
| 2 | 001 | C           |   1 |    1 |
| 3 | 001 | C           |   1 |    1 |
| 4 | 002 | P           |   2 |    2 |
| 5 | 002 | C           |   2 |    2 |
| 6 | 002 | P           |   3 |    3 |
+---+-----+-------------+-----+------+


问:
ASP.NET MVC DbContext
I am new to MVC and I'm currently studying Entity Framework as a way to extract data from a database.

```<code>public ActionResult Index()
{
    EmployeeContext employeeContext = new EmployeeContext();
    Employee[] employees = employeeContext.Employees;
    return View();
}
</code>```

But I'm kindda confused in what variable should I put my employeeContext.Employees so that after that I can pass it to the view. I thought something like array.

答:
You are getting a type mismatch on the Employee[] employees = employeeContext.Employees because employeeContext.Employees is a DbSet<Employee> and not an array.

You need to pass a model to your view, you can do this with the overload of method View().

You need to dispose of the DbContext in a using block, (it implements IDisposable and you should follow that pattern for almost everything that implements this interface to ensure resources are freed when no longer in use)

Also you probably really do not want to pass ALL of your employees each time, what if there are thousands?

Updated code.

```<code>public ActionResult Index()
{
    using(EmployeeContext employeeContext = new EmployeeContext())
    {
        Employee[] employees = employeeContext.Employees.ToArray(); // now it will return an array
        return View(employees); // pass employees to your view
    }
}
</code>```

Title: ASP.NET MVC DbContext

Body:
I am new to MVC and I'm currently studying Entity Framework as a way to extract data from a database.

public ActionResult Index()
{
    EmployeeContext employeeContext = new EmployeeContext();
    Employee[] employees = employeeContext.Employees;
    return View();
}

But I'm kindda confused in what variable should I put my employeeContext.Employees so that after that I can pass it to the view. I thought something like array.

Body:
You are getting a type mismatch on the Employee[] employees = employeeContext.Employees because employeeContext.Employees is a DbSet<Employee> and not an array.

You need to pass a model to your view, you can do this with the overload of method View().

You need to dispose of the DbContext in a using block, (it implements IDisposable and you should follow that pattern for almost everything that implements this interface to ensure resources are freed when no longer in use)

Also you probably really do not want to pass ALL of your employees each time, what if there are thousands?

Updated code.

public ActionResult Index()
{
    using(EmployeeContext employeeContext = new EmployeeContext())
    {
        Employee[] employees = employeeContext.Employees.ToArray(); // now it will return an array
        return View(employees); // pass employees to your view
    }
}


问:
ERROR 1064 iYou have an error in your SQL syntax;
Hi I have an error when I am inserting data into my database:

1064 You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'User,hello,2017-03-30 10:42:43,0)' at line 3 SQL=INSERT INTO
  #__registentrys (name,type_entry,date_regist,published)
  VALUES (Super User,hello,2017-03-30 10:42:43,0)

My code:

```<code>$greating1=$this->item->greeting;
                $datetime = new Jdate('now + 1 hour'); //GTM hour Lisbon
                $this->item->menssage1 = $datetime;
                //session portection
                $user = JFactory::getUser();
                if($user->guest)
                {
                    $this->item->menssage2 = "You are not allowed to enter this site";
                }
                else
                {
                    $username = $user->name;
                    $this->item->menssage2 = $username;
                    $db1 = JFactory::getDbo();
                    $query1 = $db1->getQuery(true);

                    // Insert columns.
                    $columns = array('name', 'type_entry', 'date_regist', 'published');

                    // Insert values.
                    $values = array($username, $greating1, $datetime, 0);

                    // Build the query
                    $query1
                    ->insert($db1->quoteName('#__registentrys'))
                    ->columns($db1->quoteName($columns))
                    ->values(implode(',', $values));

                    $db1->setQuery($query1);
                    $db1->execute();
</code>```

Thanks in advance for your answers.

答:
Joomla database uses $db->quote to save the strings, else it will assume the values as columns. So you need to change the query like this, as per joomla syntax.
This line

```<code> $values = array($username, $greating1, $datetime, 0);
</code>```

Needs to be changed to

```<code> $values = array($db1->quote($username), $db1->quote($greating1), $db1->quote($datetime), 0);
</code>```

Body:
Hi I have an error when I am inserting data into my database:

1064 You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'User,hello,2017-03-30 10:42:43,0)' at line 3 SQL=INSERT INTO
  #__registentrys (name,type_entry,date_regist,published)
  VALUES (Super User,hello,2017-03-30 10:42:43,0)

My code:

$greating1=$this->item->greeting;
                $datetime = new Jdate('now + 1 hour'); //GTM hour Lisbon
                $this->item->menssage1 = $datetime;
                //session portection
                $user = JFactory::getUser();
                if($user->guest)
                {
                    $this->item->menssage2 = "You are not allowed to enter this site";
                }
                else
                {
                    $username = $user->name;
                    $this->item->menssage2 = $username;
                    $db1 = JFactory::getDbo();
                    $query1 = $db1->getQuery(true);

                    // Insert columns.
                    $columns = array('name', 'type_entry', 'date_regist', 'published');

                    // Insert values.
                    $values = array($username, $greating1, $datetime, 0);

                    // Build the query
                    $query1
                    ->insert($db1->quoteName('#__registentrys'))
                    ->columns($db1->quoteName($columns))
                    ->values(implode(',', $values));

                    $db1->setQuery($query1);
                    $db1->execute();

Thanks in advance for your answers.

Body:
Joomla database uses $db->quote to save the strings, else it will assume the values as columns. So you need to change the query like this, as per joomla syntax.
This line

 $values = array($username, $greating1, $datetime, 0);

Needs to be changed to

 $values = array($db1->quote($username), $db1->quote($greating1), $db1->quote($datetime), 0);


问:
Mongodb authentication not working from config file
I am trying to enable authentication in my mongodb version v3.4.3  from the config file but it doesn't work.

The following works:
sudo mongod --auth --port 27017 --dbpath /var/lib/mongodb

I can access via authentication

The following works as well

sudo service mongod start
but only when in the config file (which is /etc/mongod.conf) I don't put authorization: enabled

When I add authorization: enabled (as described in the documentation for that version), I can no longer launch mongod. It gives an error saying that my database folder does not exist, so I assume the config file is corrupt and it doesn't read anymore that the database folder is in /var/lib/mongodb.

Any suggestions are appreciated.

Here the full config file (standard config file, except that I added authorization)

ubuntu@ip-172-31-28-105:~$ cat /etc/mongod.conf

```<code># mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0

#processManagement:

#security:
    authorization: enabled

#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options:

#auditLog:

#snmp:
</code>```

答:
There were a few problems:

First of all, the config file always has to be stated when running mongod. Otherwise it takes /data/db as database folder. So the way to run it is via mongod --config /etc/mongod.conf, and the standard configuration contains dbPath: /var/lib/mongodb as database folder.

Second, the config file needs to look like the below. The # in front of the security needs to be removed.

```<code>security:
  authorization: enabled
</code>```

And thirdly, in order for start service mongod start to work, it is necessary to adjust the permission in the mongodb database folder, so the mongodb user has permission to write to them (this is not in the documentation, but probably self-explanatory with anybody who has enough experience). This needs to be done with chown, as the script will use mongdb as user (and no longer sudo).

And fourth, I'm using ubuntu 16, so sudo service mongod start won't work. It needs to be done via sudo systemctl start mongodb. This is also not correctly mentioned in the mongodb documentation.

Body:
I am trying to enable authentication in my mongodb version v3.4.3  from the config file but it doesn't work.

The following works:
sudo mongod --auth --port 27017 --dbpath /var/lib/mongodb

I can access via authentication

The following works as well

sudo service mongod start
but only when in the config file (which is /etc/mongod.conf) I don't put authorization: enabled

When I add authorization: enabled (as described in the documentation for that version), I can no longer launch mongod. It gives an error saying that my database folder does not exist, so I assume the config file is corrupt and it doesn't read anymore that the database folder is in /var/lib/mongodb.

Any suggestions are appreciated.

Here the full config file (standard config file, except that I added authorization)

ubuntu@ip-172-31-28-105:~$ cat /etc/mongod.conf

# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0

#processManagement:

#security:
    authorization: enabled

#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options:

#auditLog:

#snmp:

Body:
There were a few problems:

First of all, the config file always has to be stated when running mongod. Otherwise it takes /data/db as database folder. So the way to run it is via mongod --config /etc/mongod.conf, and the standard configuration contains dbPath: /var/lib/mongodb as database folder.

Second, the config file needs to look like the below. The # in front of the security needs to be removed.

security:
  authorization: enabled

And thirdly, in order for start service mongod start to work, it is necessary to adjust the permission in the mongodb database folder, so the mongodb user has permission to write to them (this is not in the documentation, but probably self-explanatory with anybody who has enough experience). This needs to be done with chown, as the script will use mongdb as user (and no longer sudo).

And fourth, I'm using ubuntu 16, so sudo service mongod start won't work. It needs to be done via sudo systemctl start mongodb. This is also not correctly mentioned in the mongodb documentation.


问:
Obtianing output of NeurophStudio - import error (java)
I am trying to abtain the output (for example: cat: 0,988; dog: 0.012) from NeurophStudio using java. The neural net recognises the images well. I found the code below. I get errors in the first two import lines. Does anyone know where I can find/download these packages? I searched through all my directories already and didn't find it.

```<code>import org.neuroph.core.NeuralNetwork; // ! error
import org.neuroph.contrib.imgrec.ImageRecognitionPlugin; // ! error
import java.util.HashMap;
import java.io.File;
import java.io.IOException;

public class ImageRecognitionSample {

 public static void main(String[] args) {
    // load trained neural network saved with Neuroph Studio (specify some existing neural network file here)
    NeuralNetwork nnet = NeuralNetwork.load("Neural Networks/Iconnet25-8.nnet"); // load trained neural network saved with Neuroph Studio
    // get the image recognition plugin from neural network
    ImageRecognitionPlugin imageRecognition = (ImageRecognitionPlugin)nnet.getPlugin(ImageRecognitionPlugin.class); // get the image recognition plugin from neural network

    try {
         // image recognition is done here (specify some existing image file)
        HashMap<String, Double> output = imageRecognition.recognizeImage(new File("testimage.png"));
        System.out.println(output.toString());
    } catch(IOException ioe) {
        ioe.printStackTrace();
    }
 }
}
</code>```

source : http://neuroph.sourceforge.net/image_recognition.html

I found the package code here : https://github.com/neuroph/neuroph/tree/master/neuroph-2.9/Core/src/main/java/org/neuroph/core
Problem: this is not downloadable and I will probably need multiple files/entire package.

Does anyone have experience with this? Any solutions?

答:
download neuroph.jar
then locate it to your project
like this
right click on your project
properties
Libraries
add jar/folder
then show the path where you put the neuroph.jar

hope it will help you!!!!

Body:
I am trying to abtain the output (for example: cat: 0,988; dog: 0.012) from NeurophStudio using java. The neural net recognises the images well. I found the code below. I get errors in the first two import lines. Does anyone know where I can find/download these packages? I searched through all my directories already and didn't find it.

import org.neuroph.core.NeuralNetwork; // ! error
import org.neuroph.contrib.imgrec.ImageRecognitionPlugin; // ! error
import java.util.HashMap;
import java.io.File;
import java.io.IOException;

public class ImageRecognitionSample {

 public static void main(String[] args) {
    // load trained neural network saved with Neuroph Studio (specify some existing neural network file here)
    NeuralNetwork nnet = NeuralNetwork.load("Neural Networks/Iconnet25-8.nnet"); // load trained neural network saved with Neuroph Studio
    // get the image recognition plugin from neural network
    ImageRecognitionPlugin imageRecognition = (ImageRecognitionPlugin)nnet.getPlugin(ImageRecognitionPlugin.class); // get the image recognition plugin from neural network

    try {
         // image recognition is done here (specify some existing image file)
        HashMap<String, Double> output = imageRecognition.recognizeImage(new File("testimage.png"));
        System.out.println(output.toString());
    } catch(IOException ioe) {
        ioe.printStackTrace();
    }
 }
}

source : http://neuroph.sourceforge.net/image_recognition.html

I found the package code here : https://github.com/neuroph/neuroph/tree/master/neuroph-2.9/Core/src/main/java/org/neuroph/core
Problem: this is not downloadable and I will probably need multiple files/entire package.

Does anyone have experience with this? Any solutions?


问:
Recursion of template arguments
```<code>template <class T> class circuit{
private:
    vector<T> components;
    string type;
public:
    complex<double> getImpedance();
};

complex<double> circuit<circuitComponent>::getImpedance() {
// function to calculate impedance in trivial case of components all in series/parallel
}

complex<double> circuit<circuit>::getImpedance() {}
</code>```

I'm trying to write a program that will be able to calulate the (complex) impedance of an arbitrary circuit of resistors, capacitors, and inductors.

For a circuit in which all the components are in series/parallel with one another, this is trivial. However, this isn't generally true. For more complex circuits with a mixture of series and parallel components, I want to be able to describe the circuit as a collection of circuits (i.e. sub-circuits/nested circuits).

So, I'm trying to write a class for circuits that can contain a vector of components, or a vector of circuits. I have attempted to write a template class to do this, but when I try to define the getImpedance() function for the case of a circuit of circuits (which I was planning on doing recursively), I get an error because the compiler doesn't know what type to give the sub-circuits (i.e. in circuit, the inner circuit doesn't have a known type).

So, my question is, is there a way to recursively provide template arguments?

Any help would be greatly appreciated.

Will

EDIT: My complete code so far is

```<code>#include<iostream>
#include<string>
#include<stdlib.h>
#include<cmath>
#include<vector>
#include <type_traits>
#include<complex>
using namespace std;

// Declare pi as const.
const double pi(3.1415927);

// A class for general circuit components.
class circuitComponent {
protected:
    // The component type, its impedance, and the frequency of the AC current passing through it.
    string componentType;
    complex<double> impedance;
    double frequency;
public:
    circuitComponent(string compName, complex<double> imp, double freq) : componentType(compName), impedance(imp), frequency(freq) {}
    virtual ~circuitComponent() {};
    virtual void setImpedance(const complex<double>&) = 0;
    // Functions to return the impedance and the frequency.
    virtual complex<double> getImpedance() = 0;
    virtual double getFrequency() = 0;
};

// A class for resistors, derived from circuitComponent.
class resistor : public circuitComponent{
protected:
    double resistance;
public:
    resistor() : circuitComponent("resistor",complex<double>(0,0), 0), resistance(0) {}
    resistor(double res, double freq) : circuitComponent("resistor", complex<double>(res, 0), freq), resistance(res) {}
    ~resistor() {}
    // A function to set the impedance of the component. Also alters the resistance accordingly.
    void setImpedance(const complex<double>& imp){
        // Deals with case of non-pure-real impedance assignment.
        if (imp.imag() != 0){
            cerr << "Cannot assign impedance with non-zero imaginary component to a resistor." << endl;
        }
        else {
            resistance = imp.real(); impedance = resistance;
        }
    }
    // Functions to return the impedace and the frequency of the resistance.
    complex<double> getImpedance() { return impedance; }
    double getFrequency() { return frequency; }
};

// A class for capacitors.
class capacitor : public circuitComponent{
private:
    double capacitance;
public:
    capacitor() : circuitComponent("capacitor", complex<double>(0, 0), 0), capacitance(0) {}
    capacitor(double cap, double freq) : circuitComponent("capacitor", complex<double>(0, -1 / (2.0*pi*frequency*cap)), freq), capacitance(cap) {}
    ~capacitor() {}
    void setImpedance(const complex<double>& imp){
        if (imp.real() != 0){
            cerr << "Cannot assgn impedance with non-zero real component to a capacitor." << endl;
        }
        else{
            impedance = imp; capacitance = imp.imag(); // THIS IS INCORRECT
        }
    }
    complex<double> getImpedance() { return impedance; }
    double getFrequency() { return frequency; }
};

// A class for inductors.
class inductor : public circuitComponent{
private:
    double inductance;
public:
    inductor() : circuitComponent("inductor", complex<double>(0, 0), 0), inductance(0) {}
    inductor(double ind, double freq) : circuitComponent("inductor", complex<double>(0,2*pi*frequency*ind), freq), inductance(ind) {}
    ~inductor() {}
    void setImpedance(const complex<double>& imp){
        if (imp.real() != 0){
            cerr << "Cannot assign impedance with non-zero real component to an inductor." << endl;
        }
        else{
            impedance = imp; inductance = imp.imag(); // THIS IS INCORRECT
        }
    }
    complex<double> getImpedance() { return impedance; }
    double getFrequency() { return frequency; }
};

template <class T> class circuit{
private:
    vector<T> components;
    string type;
public:
    complex<double> getImpedance();
};

// For the case where the circuit (or sub-circuit) has no subcircuits, and hence is a collection of components that are ALL in parallel/series with one another.
complex<double> circuit<circuitComponent>::getImpedance() {
    complex<double> impedance(0);
    vector<circuitComponent>::iterator componentIter;
    if (type == "s"){
        for (componentIter = components.begin(); componentIter != components.end(); ++componentIter){
            impedance += componentIter->getImpedance();
        }
    }
    else if (type == "p") {
        complex<double> reciprocolImpedance(0);
        for (componentIter = components.begin(); componentIter != components.end(); ++componentIter){
            // complex<double>(1,0) is just the number 1 expressed as a complex number.
            reciprocolImpedance += (complex<double>(1,0)/componentIter->getImpedance());
        }
        impedance = (complex<double>(1, 0)) / reciprocolImpedance;
    }
    return impedance;
}

// THIS is the problem line.
complex<double> circuit<circuit>::getImpedance() {}

int main(){

    string exitStr;
    cin >> exitStr;
    return 0;
}
</code>```

答:
You should remember that circuit is a template class; so you can't write something as

```<code>complex<double> circuit<circuit>::getImpedance() {}
</code>```

beacuse (1) lacks of template <> before and (2) lacks of template parameter in the inner circuit.

A way to write getImpedance is to write a generic version, by example

```<code>template <typename T>
std::complex<double> circuit<T>::getImpedance()
 { return components.size() ? components[0].getImpedance() : 1.0; }
</code>```

and a specialized version for circuitComponent, by example

```<code>template <>
std::complex<double> circuit<circuitComponent>::getImpedance()
 { return components.size() ? components[0].val : 0.0; }
</code>```

A full working example

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

struct circuitComponent
 { std::complex<double> val; };

template <typename T>
class circuit
 {
   private:
      std::vector<T> components;
      std::string type;

   public:
      std::complex<double> getImpedance();
 };

template <>
std::complex<double> circuit<circuitComponent>::getImpedance()
 { return components.size() ? components[0].val : 0.0; }

template <typename T>
std::complex<double> circuit<T>::getImpedance()
 { return components.size() ? components[0].getImpedance() : 1.0; }

int main ()
 {
   circuit<circuitComponent>  c0;

   std::cout << c0.getImpedance() << std::endl;

   circuit<circuit<circuitComponent>>  c1;

   std::cout << c1.getImpedance() << std::endl;
 }
</code>```

Title: Recursion of template arguments

Body:
template <class T> class circuit{
private:
    vector<T> components;
    string type;
public:
    complex<double> getImpedance();
};

complex<double> circuit<circuitComponent>::getImpedance() {
// function to calculate impedance in trivial case of components all in series/parallel
}

complex<double> circuit<circuit>::getImpedance() {}

I'm trying to write a program that will be able to calulate the (complex) impedance of an arbitrary circuit of resistors, capacitors, and inductors.

For a circuit in which all the components are in series/parallel with one another, this is trivial. However, this isn't generally true. For more complex circuits with a mixture of series and parallel components, I want to be able to describe the circuit as a collection of circuits (i.e. sub-circuits/nested circuits).

So, I'm trying to write a class for circuits that can contain a vector of components, or a vector of circuits. I have attempted to write a template class to do this, but when I try to define the getImpedance() function for the case of a circuit of circuits (which I was planning on doing recursively), I get an error because the compiler doesn't know what type to give the sub-circuits (i.e. in circuit, the inner circuit doesn't have a known type).

So, my question is, is there a way to recursively provide template arguments?

Any help would be greatly appreciated.

Will

EDIT: My complete code so far is

#include<iostream>
#include<string>
#include<stdlib.h>
#include<cmath>
#include<vector>
#include <type_traits>
#include<complex>
using namespace std;

// Declare pi as const.
const double pi(3.1415927);

// A class for general circuit components.
class circuitComponent {
protected:
    // The component type, its impedance, and the frequency of the AC current passing through it.
    string componentType;
    complex<double> impedance;
    double frequency;
public:
    circuitComponent(string compName, complex<double> imp, double freq) : componentType(compName), impedance(imp), frequency(freq) {}
    virtual ~circuitComponent() {};
    virtual void setImpedance(const complex<double>&) = 0;
    // Functions to return the impedance and the frequency.
    virtual complex<double> getImpedance() = 0;
    virtual double getFrequency() = 0;
};

// A class for resistors, derived from circuitComponent.
class resistor : public circuitComponent{
protected:
    double resistance;
public:
    resistor() : circuitComponent("resistor",complex<double>(0,0), 0), resistance(0) {}
    resistor(double res, double freq) : circuitComponent("resistor", complex<double>(res, 0), freq), resistance(res) {}
    ~resistor() {}
    // A function to set the impedance of the component. Also alters the resistance accordingly.
    void setImpedance(const complex<double>& imp){
        // Deals with case of non-pure-real impedance assignment.
        if (imp.imag() != 0){
            cerr << "Cannot assign impedance with non-zero imaginary component to a resistor." << endl;
        }
        else {
            resistance = imp.real(); impedance = resistance;
        }
    }
    // Functions to return the impedace and the frequency of the resistance.
    complex<double> getImpedance() { return impedance; }
    double getFrequency() { return frequency; }
};

// A class for capacitors.
class capacitor : public circuitComponent{
private:
    double capacitance;
public:
    capacitor() : circuitComponent("capacitor", complex<double>(0, 0), 0), capacitance(0) {}
    capacitor(double cap, double freq) : circuitComponent("capacitor", complex<double>(0, -1 / (2.0*pi*frequency*cap)), freq), capacitance(cap) {}
    ~capacitor() {}
    void setImpedance(const complex<double>& imp){
        if (imp.real() != 0){
            cerr << "Cannot assgn impedance with non-zero real component to a capacitor." << endl;
        }
        else{
            impedance = imp; capacitance = imp.imag(); // THIS IS INCORRECT
        }
    }
    complex<double> getImpedance() { return impedance; }
    double getFrequency() { return frequency; }
};

// A class for inductors.
class inductor : public circuitComponent{
private:
    double inductance;
public:
    inductor() : circuitComponent("inductor", complex<double>(0, 0), 0), inductance(0) {}
    inductor(double ind, double freq) : circuitComponent("inductor", complex<double>(0,2*pi*frequency*ind), freq), inductance(ind) {}
    ~inductor() {}
    void setImpedance(const complex<double>& imp){
        if (imp.real() != 0){
            cerr << "Cannot assign impedance with non-zero real component to an inductor." << endl;
        }
        else{
            impedance = imp; inductance = imp.imag(); // THIS IS INCORRECT
        }
    }
    complex<double> getImpedance() { return impedance; }
    double getFrequency() { return frequency; }
};

template <class T> class circuit{
private:
    vector<T> components;
    string type;
public:
    complex<double> getImpedance();
};

// For the case where the circuit (or sub-circuit) has no subcircuits, and hence is a collection of components that are ALL in parallel/series with one another.
complex<double> circuit<circuitComponent>::getImpedance() {
    complex<double> impedance(0);
    vector<circuitComponent>::iterator componentIter;
    if (type == "s"){
        for (componentIter = components.begin(); componentIter != components.end(); ++componentIter){
            impedance += componentIter->getImpedance();
        }
    }
    else if (type == "p") {
        complex<double> reciprocolImpedance(0);
        for (componentIter = components.begin(); componentIter != components.end(); ++componentIter){
            // complex<double>(1,0) is just the number 1 expressed as a complex number.
            reciprocolImpedance += (complex<double>(1,0)/componentIter->getImpedance());
        }
        impedance = (complex<double>(1, 0)) / reciprocolImpedance;
    }
    return impedance;
}

// THIS is the problem line.
complex<double> circuit<circuit>::getImpedance() {}

int main(){

    string exitStr;
    cin >> exitStr;
    return 0;
}

Body:
You should remember that circuit is a template class; so you can't write something as

complex<double> circuit<circuit>::getImpedance() {}

beacuse (1) lacks of template <> before and (2) lacks of template parameter in the inner circuit.

A way to write getImpedance is to write a generic version, by example

template <typename T>
std::complex<double> circuit<T>::getImpedance()
 { return components.size() ? components[0].getImpedance() : 1.0; }

and a specialized version for circuitComponent, by example

template <>
std::complex<double> circuit<circuitComponent>::getImpedance()
 { return components.size() ? components[0].val : 0.0; }

A full working example

#include <string>
#include <vector>
#include <complex>
#include <iostream>

struct circuitComponent
 { std::complex<double> val; };

template <typename T>
class circuit
 {
   private:
      std::vector<T> components;
      std::string type;

   public:
      std::complex<double> getImpedance();
 };

template <>
std::complex<double> circuit<circuitComponent>::getImpedance()
 { return components.size() ? components[0].val : 0.0; }

template <typename T>
std::complex<double> circuit<T>::getImpedance()
 { return components.size() ? components[0].getImpedance() : 1.0; }

int main ()
 {
   circuit<circuitComponent>  c0;

   std::cout << c0.getImpedance() << std::endl;

   circuit<circuit<circuitComponent>>  c1;

   std::cout << c1.getImpedance() << std::endl;
 }


问:
Angular ControlValueAccessor registerOnChange callback being overwritten
Update: Link to Plunker

Running into a weird problem. I'm using Angular 2.4.1. When the component initially loads, the value setter runs and onChangeCallback correctly fires. However, I am console-logging onChangeCallback, and after it is initially set, it is being replaced with an anonymous function.

Here are the results of the console.log:

function (_) { }

function (newValue) {
                dir.viewToModelUpdate(newValue);
                control.markAsDirty();
                control.setValue(newValue, { emitModelToViewChange: false });
            }

function (_) { }

The first happens on page load, immediately followed by 2. I'm assuming Angular is handling the token and implementing ControlValueAccessor correctly at this point. When I then make a change on the select element, onChangeCallback is being called as the anonymous function again without the ControlValueAccessor additions.

Any idea on how to fix this? It is only this form-control that I'm having this problem with.

```<code>import { Component, Input, Output, EventEmitter, forwardRef, ViewChild, ElementRef, Renderer, ChangeDetectorRef, OnChanges } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'select-resizable',
  template:`
    <select #mainSelectElement [(ngModel)]="value" (change)="updateSelected($event.target.value)" style="width: initial;">
      <ng-content></ng-content>
    </select>
    <select class="usa-sr-only" aria-hidden="true" role="presentation" #hiddenSelectElement style="width: initial;">
      <option>{{value}}</option>
    </select>
  `,
  providers: [
    { provide: NG_VALUE_ACCESSOR, useClass: forwardRef(() => SelectResizableComponent), multi: true }
  ]
})
export class SelectResizableComponent implements ControlValueAccessor {

  @ViewChild('hiddenSelectElement') hiddenSelectElement: ElementRef;
  @ViewChild('mainSelectElement') mainSelectElement: ElementRef;

  private _selected: any;

  private onChangeCallback: (_: any) => void = (_: any) => {};
  private onTouchedCallback: () => void = () => {};

  get value(): any {
    return this._selected;
  }

  set value(val: any) {
    this._selected = val;
    this.onChangeCallback(val);
    console.log(this.onChangeCallback);
  }

  constructor(private renderer: Renderer, private ref: ChangeDetectorRef) {}

  updateSelected(event) {
    this.ref.detectChanges();
    const width = (this.hiddenSelectElement.nativeElement.clientWidth * 1.02) + 'px';
    this.renderer.setElementStyle(this.mainSelectElement.nativeElement, 'width', width);
  }

  writeValue(val: any) {
    this.value = val;
  }

  registerOnChange(fn: any) {
    this.onChangeCallback = fn;
  }

  registerOnTouched(fn: any) {
    this.onTouchedCallback = fn;
  }
}
</code>```

答:
```<code>  providers: [
    { provide: NG_VALUE_ACCESSOR, useClass: forwardRef(() => SelectResizableComponent), multi: true }
  ]
</code>```

The problem was right there. I provided the token with useClass rather than useExisting. So after the component was instantiated, a new value was created from the components class for the NG_VALUE_ACCESSOR token.

Thanks, Adam, for spotting that I had two values.

Body:
Update: Link to Plunker

Running into a weird problem. I'm using Angular 2.4.1. When the component initially loads, the value setter runs and onChangeCallback correctly fires. However, I am console-logging onChangeCallback, and after it is initially set, it is being replaced with an anonymous function.

Here are the results of the console.log:

function (_) { }

function (newValue) {
                dir.viewToModelUpdate(newValue);
                control.markAsDirty();
                control.setValue(newValue, { emitModelToViewChange: false });
            }

function (_) { }

The first happens on page load, immediately followed by 2. I'm assuming Angular is handling the token and implementing ControlValueAccessor correctly at this point. When I then make a change on the select element, onChangeCallback is being called as the anonymous function again without the ControlValueAccessor additions.

Any idea on how to fix this? It is only this form-control that I'm having this problem with.

import { Component, Input, Output, EventEmitter, forwardRef, ViewChild, ElementRef, Renderer, ChangeDetectorRef, OnChanges } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'select-resizable',
  template:`
    <select #mainSelectElement [(ngModel)]="value" (change)="updateSelected($event.target.value)" style="width: initial;">
      <ng-content></ng-content>
    </select>
    <select class="usa-sr-only" aria-hidden="true" role="presentation" #hiddenSelectElement style="width: initial;">
      <option>{{value}}</option>
    </select>
  `,
  providers: [
    { provide: NG_VALUE_ACCESSOR, useClass: forwardRef(() => SelectResizableComponent), multi: true }
  ]
})
export class SelectResizableComponent implements ControlValueAccessor {

  @ViewChild('hiddenSelectElement') hiddenSelectElement: ElementRef;
  @ViewChild('mainSelectElement') mainSelectElement: ElementRef;

  private _selected: any;

  private onChangeCallback: (_: any) => void = (_: any) => {};
  private onTouchedCallback: () => void = () => {};

  get value(): any {
    return this._selected;
  }

  set value(val: any) {
    this._selected = val;
    this.onChangeCallback(val);
    console.log(this.onChangeCallback);
  }

  constructor(private renderer: Renderer, private ref: ChangeDetectorRef) {}

  updateSelected(event) {
    this.ref.detectChanges();
    const width = (this.hiddenSelectElement.nativeElement.clientWidth * 1.02) + 'px';
    this.renderer.setElementStyle(this.mainSelectElement.nativeElement, 'width', width);
  }

  writeValue(val: any) {
    this.value = val;
  }

  registerOnChange(fn: any) {
    this.onChangeCallback = fn;
  }

  registerOnTouched(fn: any) {
    this.onTouchedCallback = fn;
  }
}

Body:
  providers: [
    { provide: NG_VALUE_ACCESSOR, useClass: forwardRef(() => SelectResizableComponent), multi: true }
  ]

The problem was right there. I provided the token with useClass rather than useExisting. So after the component was instantiated, a new value was created from the components class for the NG_VALUE_ACCESSOR token.

Thanks, Adam, for spotting that I had two values.


问:
Why I see this in my URL
My wordpress site have this weird #not-set:all suffix after update. I don't know what's that. Some plugin? Anyone have similar thing?

https://meanttomove.pl

答: try deactivating all plugins and then put them on one by one until you find the one which does it</p>

Title: Why I see this in my URL


问:
unable to ping/send http requests to RHEL tomcat server on Azure
Note - I am fully aware that there are lot of similar issues posted before, but I tried NSG settings, psping but nothing seem to work

All, I brought up a RHEL7.3 server on Azure and installed JDK1.8 and Tomcat8. After starting Tomcat, I tried an http request from my browser:

http://XX.yy.zz.abc:8080/ but I was unable to get the index page

I also created an inbound security rule to allow HTTP and also allow IP range from our company.

Even worse is, when I tried pinging to this IP from my desktop computer, I am unable to ping the same - it is timing out.

Please note that in the past, I've been able to bring up servers and be able to connect from desktops without any issues - in a similar azure-companynetwork setup.

Am I missing anything here?

答: Ok, so pings do not work, you shouldn't even try that. What you should check is the firewall on you RHEL VM and check you've allowed port 8080 on you NSG, also your VM should have a PublicIP attached</p>


问:
Performance issue with marshalling/unmarshalling in Glassfish/Unix
I've recently deployed my application on a glassfish installation running on Unix and I'm having serious performance issues with a section of the code.
My application has to communicate with another system via XML, and I'm using Jaxb to do the marshalling/unmarshalling of the exchanged messages.
Each communication requires one marshal and one unmarshal operation.
When I run the application on my computer (Windows XP), the total amount of both operations is less than 2 seconds, but when I run the same application, with the same data, in Unix, the total amount is near 20 seconds, almost 10x more.
I've searched thoroughly the server logs, looking for some clue, but couldn't find nothing useful.

Here is the code for both calls:

```<code>    public static <T> String marshal(T transaction) throws JAXBException, IOException {
        JAXBContext jc = JAXBContext.newInstance(transaction.getClass().getPackage().getName());
        Marshaller u = jc.createMarshaller();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        u.setProperty("jaxb.encoding", "ISO-8859-1");
        u.marshal(transaction, baos);

        String xml = new String(baos.toByteArray());

        baos.close();

        return xml;
    }

    public static <T> T unmarshal(Class<T> docClass, String xml) throws JAXBException, IOException {
        String packageName = docClass.getPackage().getName();

        InputStream is = new ByteArrayInputStream(xml.getBytes());

        JAXBContext jc = JAXBContext.newInstance(packageName);
        Unmarshaller u = jc.createUnmarshaller();
        Object o = u.unmarshal(is);

        is.close();

        return (T) o;
    }
</code>```

Can someone help me with this issue?

Kind regards,

Carlos Ferreira

答: The JAXBContext is threadsafe and can be shared.  It does not need to be constantly created.  This will improve performance.</p>

ContentLicense: CC BY-SA 2.5

Body:
I've recently deployed my application on a glassfish installation running on Unix and I'm having serious performance issues with a section of the code.
My application has to communicate with another system via XML, and I'm using Jaxb to do the marshalling/unmarshalling of the exchanged messages.
Each communication requires one marshal and one unmarshal operation.
When I run the application on my computer (Windows XP), the total amount of both operations is less than 2 seconds, but when I run the same application, with the same data, in Unix, the total amount is near 20 seconds, almost 10x more.
I've searched thoroughly the server logs, looking for some clue, but couldn't find nothing useful.

Here is the code for both calls:

    public static <T> String marshal(T transaction) throws JAXBException, IOException {
        JAXBContext jc = JAXBContext.newInstance(transaction.getClass().getPackage().getName());
        Marshaller u = jc.createMarshaller();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        u.setProperty("jaxb.encoding", "ISO-8859-1");
        u.marshal(transaction, baos);

        String xml = new String(baos.toByteArray());

        baos.close();

        return xml;
    }

    public static <T> T unmarshal(Class<T> docClass, String xml) throws JAXBException, IOException {
        String packageName = docClass.getPackage().getName();

        InputStream is = new ByteArrayInputStream(xml.getBytes());

        JAXBContext jc = JAXBContext.newInstance(packageName);
        Unmarshaller u = jc.createUnmarshaller();
        Object o = u.unmarshal(is);

        is.close();

        return (T) o;
    }

Can someone help me with this issue?

Kind regards,

Carlos Ferreira


问:
What is the correct way to set Parsley.js global defaults in version 2.4.x
I searched and couldn't find the answer in the Parsley documentation.

As of version 2.4.x, is this correct way to set parsley global default options?

```<code><script src="Parsley-2.4.3/dist/parsley.min.js" type="text/javascript"></script>
<script>
//set options after parsley.min.js for v2.4.x?
$.extend(window.Parsley.options, {
  excluded: 'input[type=button], input[type=submit], input[type=reset], .search, .ignore',
  triggerAfterFailure: 'input change blur',
  errorsContainer: function (element) {}
});
</script>
</code>```

答: Yes, My example above is correct.</p>

Body: Yes, My example above is correct.


问:
XSLT Transformation not working
I have the following xslt definition

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

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:fo="http://www.w3.org/1999/XSL/Format" >
    <xsl:output method="text" omit-xml-declaration="yes" indent="yes"/>
    <xsl:template match="/">
        <xsl:value-of select="concat(//RedemptionFileName)"/>
            <xsl:for-each select="//ErrorMessageList/ErrorMessage">
                <xsl:value-of select="concat(',',OrderNumber,',',OrderLineItemNumber,',',ErrorCode)"/>
            </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>
</code>```

to tranform Data below

```<code> <?xml version="1.0" encoding="utf-8"?>
<ReceiptDetails xmlns="http://centivesolutions.com/AAA_Receipt.xsd">
    <schemaVersion>10.4</schemaVersion>
    <RedemptionFileName>IncommBIFCFS_Order_20140319110741741.xml</RedemptionFileName>
    <ErrorMessageList>
        <ErrorMessage>
            <OrderNumber>1615296</OrderNumber>
            <OrderLineItemNumber>1910642</OrderLineItemNumber>
            <ErrorCode>SNF</ErrorCode>
            <ErrorDesc>street not found in city (finance number)</ErrorDesc>
        </ErrorMessage>
        <ErrorMessage>
            <OrderNumber>1615297</OrderNumber>
            <OrderLineItemNumber>1910643</OrderLineItemNumber>
            <ErrorCode>SNF</ErrorCode>
            <ErrorDesc>street not found in city (finance number)</ErrorDesc>
        </ErrorMessage>
        <ErrorMessage>
            <OrderNumber>1615298</OrderNumber>
            <OrderLineItemNumber>1910644</OrderLineItemNumber>
            <ErrorCode>BNC</ErrorCode>
            <ErrorDesc>PO Box not found in city (finance number)</ErrorDesc>
        </ErrorMessage>
        <ErrorMessage>
            <OrderNumber>1615299</OrderNumber>
            <OrderLineItemNumber>1910645</OrderLineItemNumber>
            <ErrorCode>ANS</ErrorCode>
            <ErrorDesc>address not on street</ErrorDesc>
        </ErrorMessage>
    </ErrorMessageList>
</ReceiptDetails>
</code>```

The expected output should look like this

```<code>IncommBIFCFS_Order_20140319110741741.xml,1615296,1910642,SNF,1615297,1910643,SNF,1615298,1910644,BNC,1615299,1910645,ANS
</code>```

When I run a sample test using Netbeans IDE i get the desired results but running on mule standalone server 3.7.0 throws an exception

```<code>org.apache.xpath.functions.FuncConcat only allows >1 arguments
</code>```

Also online formatters like this says the xslt is wrong.

答:
I think this:

```<code><xsl:value-of select="concat(//RedemptionFileName)"/>
</code>```

Should be:

```<code><xsl:value-of select="//RedemptionFileName" />
</code>```

You're trying to concat (join) only one thing, the error is saying you need two or more things to join together.

Title: XSLT Transformation not working

Body:
I have the following xslt definition

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

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:fo="http://www.w3.org/1999/XSL/Format" >
    <xsl:output method="text" omit-xml-declaration="yes" indent="yes"/>
    <xsl:template match="/">
        <xsl:value-of select="concat(//RedemptionFileName)"/>
            <xsl:for-each select="//ErrorMessageList/ErrorMessage">
                <xsl:value-of select="concat(',',OrderNumber,',',OrderLineItemNumber,',',ErrorCode)"/>
            </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

to tranform Data below

 <?xml version="1.0" encoding="utf-8"?>
<ReceiptDetails xmlns="http://centivesolutions.com/AAA_Receipt.xsd">
    <schemaVersion>10.4</schemaVersion>
    <RedemptionFileName>IncommBIFCFS_Order_20140319110741741.xml</RedemptionFileName>
    <ErrorMessageList>
        <ErrorMessage>
            <OrderNumber>1615296</OrderNumber>
            <OrderLineItemNumber>1910642</OrderLineItemNumber>
            <ErrorCode>SNF</ErrorCode>
            <ErrorDesc>street not found in city (finance number)</ErrorDesc>
        </ErrorMessage>
        <ErrorMessage>
            <OrderNumber>1615297</OrderNumber>
            <OrderLineItemNumber>1910643</OrderLineItemNumber>
            <ErrorCode>SNF</ErrorCode>
            <ErrorDesc>street not found in city (finance number)</ErrorDesc>
        </ErrorMessage>
        <ErrorMessage>
            <OrderNumber>1615298</OrderNumber>
            <OrderLineItemNumber>1910644</OrderLineItemNumber>
            <ErrorCode>BNC</ErrorCode>
            <ErrorDesc>PO Box not found in city (finance number)</ErrorDesc>
        </ErrorMessage>
        <ErrorMessage>
            <OrderNumber>1615299</OrderNumber>
            <OrderLineItemNumber>1910645</OrderLineItemNumber>
            <ErrorCode>ANS</ErrorCode>
            <ErrorDesc>address not on street</ErrorDesc>
        </ErrorMessage>
    </ErrorMessageList>
</ReceiptDetails>

The expected output should look like this

IncommBIFCFS_Order_20140319110741741.xml,1615296,1910642,SNF,1615297,1910643,SNF,1615298,1910644,BNC,1615299,1910645,ANS

When I run a sample test using Netbeans IDE i get the desired results but running on mule standalone server 3.7.0 throws an exception

org.apache.xpath.functions.FuncConcat only allows >1 arguments

Also online formatters like this says the xslt is wrong.

Body:
I think this:

<xsl:value-of select="concat(//RedemptionFileName)"/>

Should be:

<xsl:value-of select="//RedemptionFileName" />

You're trying to concat (join) only one thing, the error is saying you need two or more things to join together.


问:
Bootstrap 4 - put small element between two long in a row without gaps
I want to make it look similar to this.

```<code>hr  {
  border: none;
  color: black;
  background-color: black;
  height: 5px;
  margin-top: 10px;
}

  <div class="row code-line">
    <div class="col-5">
      <div class="line-left">
        <hr>
      </div>
    </div>
    <div class="col-1">
      <i class="fa fa-code fa-2x" aria-hidden="true"></i>
    </div>
    <div class="col-5">
     <div class="line-right">
        <hr>
      </div>
    </div>
  </div>
</code>```

(fa-code is Font-Awesome icon)

Codepen: https://codepen.io/Oktocorp/pen/yMxpwX?editors=1100

I don't know how to make it symmetric and responsive(long lines should become smaller while resizing). Probably, using flexbox could help?

答:
.hr_line{
  border: 3px solid #eee;
}
.arrow_indicate{
  margin: 10px 0px;
}
.row_right{
  padding-right: 0px!important;
}
.row_left{
  padding-left: 0px!important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-xs-12">
<div class="col-xs-5 row_right">
<hr class="row hr_line"/>
</div>
<div class="col-xs-2">
<div class="row text-center arrow_indicate">
<i class="fa fa-code fa-2x" aria-hidden="true"></i>
</div>
</div>
<div class="col-xs-5 row_left">
<hr class="row hr_line"/>
</div>
</div></code>```

Body:
I want to make it look similar to this.

hr  {
  border: none;
  color: black;
  background-color: black;
  height: 5px;
  margin-top: 10px;
}

(fa-code is Font-Awesome icon)

Codepen: https://codepen.io/Oktocorp/pen/yMxpwX?editors=1100

I don't know how to make it symmetric and responsive(long lines should become smaller while resizing). Probably, using flexbox could help?

Body:
.hr_line{
  border: 3px solid #eee;
}
.arrow_indicate{
  margin: 10px 0px;
}
.row_right{
  padding-right: 0px!important;
}
.row_left{
  padding-left: 0px!important;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-xs-12">
<div class="col-xs-5 row_right">
<hr class="row hr_line"/>
</div>
<div class="col-xs-2">
<div class="row text-center arrow_indicate">
<i class="fa fa-code fa-2x" aria-hidden="true"></i>
</div>
</div>
<div class="col-xs-5 row_left">
<hr class="row hr_line"/>
</div>
</div>


问:
Tkinter escape binding not destroying
I am trying to learn tkinter and the idea that I have requires it to be in fullscreen. Before making it fullscreen, however I wanted to make sure I could close the window using escape. So through other questions similar to this one on Stack Overflow I have been trying to get it to destroy the tkinter window when I hit escape. To me this seems like it should work but I am getting an exception when I hit escape:

```<code>    `Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Jake\AppData\Local\Programs\Python\Python36-
32\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
TypeError: destroy() takes 1 positional argument but 2 were given`
</code>```

This is confusing for me because I don't think I am calling any arguments at all let alone 2. I have added a quit button which calls the close method I made and that works but using escape doesn't seem to. I have supplied my code for clarity. I know this is similar to a lot of questions on here but I have tried everything and nothing seems to be working for me. Thanks in advance!

```<code>import tkinter
from tkinter import *

class Window(Frame):
    def __init__(self, master = None):
        Frame.__init__(self, master)

        master.bind('<Escape>', master.destroy)

        self.init_window()
    def init_window(self):
        self.pack(fill=BOTH, expand=1)
        quitButton = Button(self, text="quit", command=self.close)
        quitButton.place(x=0, y=0)

    def close(self):
        self.master.destroy()

def main():
    root = Tk()
    root.geometry('500x500')
    app = Window(root)
    root.mainloop()

main()
</code>```

答:
When  you bind a function to an event, tkinter will always pass an event object to that function. The destroy function takes no arguments, which means you can't bind directly to it. You need to bind to a function that will accept the event object as an argument.

Since you already have a function, you can give it an optional named argument so that you can continue to call your function without the argument, but it can also be used in a binding:

```<code>class Window(Frame):
    def __init__(self, master = None):
        ...
        master.bind('<Escape>', self.close)

    def close(self, event=None):
        self.master.destroy()
</code>```

You could also use an anonymous function:

```<code>master.bind('<Escape>', lambda event: master.destroy())
</code>```

Title: Tkinter escape binding not destroying

Body:
I am trying to learn tkinter and the idea that I have requires it to be in fullscreen. Before making it fullscreen, however I wanted to make sure I could close the window using escape. So through other questions similar to this one on Stack Overflow I have been trying to get it to destroy the tkinter window when I hit escape. To me this seems like it should work but I am getting an exception when I hit escape:

    `Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Jake\AppData\Local\Programs\Python\Python36-
32\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
TypeError: destroy() takes 1 positional argument but 2 were given`

This is confusing for me because I don't think I am calling any arguments at all let alone 2. I have added a quit button which calls the close method I made and that works but using escape doesn't seem to. I have supplied my code for clarity. I know this is similar to a lot of questions on here but I have tried everything and nothing seems to be working for me. Thanks in advance!

import tkinter
from tkinter import *

class Window(Frame):
    def __init__(self, master = None):
        Frame.__init__(self, master)

        master.bind('<Escape>', master.destroy)

        self.init_window()
    def init_window(self):
        self.pack(fill=BOTH, expand=1)
        quitButton = Button(self, text="quit", command=self.close)
        quitButton.place(x=0, y=0)

    def close(self):
        self.master.destroy()

def main():
    root = Tk()
    root.geometry('500x500')
    app = Window(root)
    root.mainloop()

main()

Body:
When  you bind a function to an event, tkinter will always pass an event object to that function. The destroy function takes no arguments, which means you can't bind directly to it. You need to bind to a function that will accept the event object as an argument.

Since you already have a function, you can give it an optional named argument so that you can continue to call your function without the argument, but it can also be used in a binding:

class Window(Frame):
    def __init__(self, master = None):
        ...
        master.bind('<Escape>', self.close)

    def close(self, event=None):
        self.master.destroy()

You could also use an anonymous function:

master.bind('<Escape>', lambda event: master.destroy())


问:
How to calculate a percentile ranking of a column of data relative to another column using python
I have two columns of data representing the same quantity; one column is from my training data, the other is from my validation data.

I know how to calculate the percentile rankings of the training data efficiently using:

```<code>pandas.DataFrame(training_data).rank(pct = True).values
</code>```

My question is, how can I efficiently get a similar set of percentile rankings of the validation data column relative to the training data column? That is, for each value in the validation data column, how can I find what its percentile ranking would be relative to all the values in the training data column?

I've tried doing this:

```<code>def percentrank(input_data,comparison_data):
    rescaled_data = np.zeros(input_data.size)
    for idx,datum in enumerate(input_data):
        rescaled_data[idx] =scipy.stats.percentileofscore(comparison_data,datum)
    return rescaled_data/100
</code>```

But I'm not sure if this is even correct, and on top of that it's incredibly slow because it is doing a lot of redundant calculations for each value in the for loop.

Any help would be greatly appreciated!

答:
Here's a solution.
Sort the training data. Then use searchsorted on the validation data.

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

# Generate Dummy Data
df_train = pd.DataFrame({'Values': 1000*np.random.rand(15712)})

#Sort Data
df_train = df_train.sort_values('Values')

# Calculating Rank and Rank_Pct for demo purposes
#but note that it is not needed for the solution
# The ranking of the validation data below does not depend on this
df_train['Rank'] = df_train.rank()
df_train['Rank_Pct']= df_train.Values.rank(pct=True)

# Demonstrate how Rank Percentile is calculated
# This gives the same value as .rank(pct=True)
pct_increment = 1./len(df_train)
df_train['Rank_Pct_Manual'] = df_train.Rank*pct_increment

df_train.head()

       Values  Rank  Rank_Pct  Rank_Pct_Manual
2724  0.006174   1.0  0.000064         0.000064
3582  0.016264   2.0  0.000127         0.000127
5534  0.095691   3.0  0.000191         0.000191
944   0.141442   4.0  0.000255         0.000255
7566  0.161766   5.0  0.000318         0.000318
</code>```

Now use searchsorted to get Rank_Pct of validation data

```<code># Generate Dummy Validation Data
df_validation = pd.DataFrame({'Values': 1000*np.random.rand(1000)})

# Note searchsorted returns array index.
# In sorted list rank is the same as the array index +1
df_validation['Rank_Pct'] = (1 + df_train.Values.searchsorted(df_validation.Values))*pct_increment
</code>```

Here is first few lines of final df_validation dataframe:

```<code>print df_validation.head()
      Values  Rank_Pct
0  307.378334  0.304290
1  744.247034  0.744208
2  669.223821  0.670825
3  149.797030  0.145621
4  317.742713  0.314218
</code>```

Body:
I have two columns of data representing the same quantity; one column is from my training data, the other is from my validation data.

I know how to calculate the percentile rankings of the training data efficiently using:

pandas.DataFrame(training_data).rank(pct = True).values

My question is, how can I efficiently get a similar set of percentile rankings of the validation data column relative to the training data column? That is, for each value in the validation data column, how can I find what its percentile ranking would be relative to all the values in the training data column?

I've tried doing this:

def percentrank(input_data,comparison_data):
    rescaled_data = np.zeros(input_data.size)
    for idx,datum in enumerate(input_data):
        rescaled_data[idx] =scipy.stats.percentileofscore(comparison_data,datum)
    return rescaled_data/100

But I'm not sure if this is even correct, and on top of that it's incredibly slow because it is doing a lot of redundant calculations for each value in the for loop.

Any help would be greatly appreciated!

Body:
Here's a solution.
Sort the training data. Then use searchsorted on the validation data.

import pandas as pd
import numpy as np

# Generate Dummy Data
df_train = pd.DataFrame({'Values': 1000*np.random.rand(15712)})

#Sort Data
df_train = df_train.sort_values('Values')

# Calculating Rank and Rank_Pct for demo purposes
#but note that it is not needed for the solution
# The ranking of the validation data below does not depend on this
df_train['Rank'] = df_train.rank()
df_train['Rank_Pct']= df_train.Values.rank(pct=True)

# Demonstrate how Rank Percentile is calculated
# This gives the same value as .rank(pct=True)
pct_increment = 1./len(df_train)
df_train['Rank_Pct_Manual'] = df_train.Rank*pct_increment

df_train.head()

       Values  Rank  Rank_Pct  Rank_Pct_Manual
2724  0.006174   1.0  0.000064         0.000064
3582  0.016264   2.0  0.000127         0.000127
5534  0.095691   3.0  0.000191         0.000191
944   0.141442   4.0  0.000255         0.000255
7566  0.161766   5.0  0.000318         0.000318

Now use searchsorted to get Rank_Pct of validation data

# Generate Dummy Validation Data
df_validation = pd.DataFrame({'Values': 1000*np.random.rand(1000)})

# Note searchsorted returns array index.
# In sorted list rank is the same as the array index +1
df_validation['Rank_Pct'] = (1 + df_train.Values.searchsorted(df_validation.Values))*pct_increment

Here is first few lines of final df_validation dataframe:

print df_validation.head()
      Values  Rank_Pct
0  307.378334  0.304290
1  744.247034  0.744208
2  669.223821  0.670825
3  149.797030  0.145621
4  317.742713  0.314218


问:
display mysql-table - wrong order displayed
php snippet:

```<code>mysqli_select_db($con,"dbtest");
$sql="SELECT * FROM w3school";
$result = mysqli_query($con,$sql);

echo "<ul id='myUL'>";
while($w3school = mysqli_fetch_array($result)) {
    echo "<li id='".$w3school['id']."'>" . $w3school['LastName'] . "</li>";
}
echo "<ul>";
</code>```

SCREEN OUTPUT looks like this:

```<code>id = 5;
id = 4;
id = 3;
id = 1;
id = 2;
</code>```

I don't see why its not 1,2,3,4 ...

Any suggestions? (any spec info just let me know)

答:
You need to use order by where filed need to order as like you want to order by id -> 1,2,3,4...

```<code>SELECT * FROM w3school order by id asc;
</code>```

or simple

```<code> SELECT * FROM w3school order by id; // no need to add asc, default asc
</code>```

And if you want 6,5,4,3,2,1 then use order by desc like

```<code>SELECT * FROM w3school order by id desc;
</code>```

you can use multiple order by like this

```<code>SELECT * FROM t1 ORDER BY key_part1 DESC, key_part2 ASC;
</code>```

more information

https://dev.mysql.com/doc/refman/5.7/en/order-by-optimization.html

Body:
php snippet:

mysqli_select_db($con,"dbtest");
$sql="SELECT * FROM w3school";
$result = mysqli_query($con,$sql);

echo "
";
while($w3school = mysqli_fetch_array($result)) {
    echo "
" . $w3school['LastName'] . "
";
}
echo "
";

SCREEN OUTPUT looks like this:

id = 5;
id = 4;
id = 3;
id = 1;
id = 2;

I don't see why its not 1,2,3,4 ...

Any suggestions? (any spec info just let me know)

Body:
You need to use order by where filed need to order as like you want to order by id -> 1,2,3,4...

SELECT * FROM w3school order by id asc;

or simple

 SELECT * FROM w3school order by id; // no need to add asc, default asc

And if you want 6,5,4,3,2,1 then use order by desc like

SELECT * FROM w3school order by id desc;

you can use multiple order by like this

SELECT * FROM t1 ORDER BY key_part1 DESC, key_part2 ASC;

more information

https://dev.mysql.com/doc/refman/5.7/en/order-by-optimization.html


问:
Embedding PDF in Spreadsheet
Goal is to run this subroutine in an Access application, which embeds a PDF document in a new Excel workbook.  The sub works properly with a text file, but will give error "Run-time error '1004': Document not saved." with a PDF file.  The code breaks on the SaveAs method.  Why does one file-type embed, and the PDF file-type not work?  Any help will be appreciated.</p>

```<code>Sub SavePDFInWorkBook()
    Dim xlObj As New Excel.Application  ' Excel application
    Dim wbkObj As Excel.workbook        ' workbook object
    Dim wstObj As Excel.Worksheet       ' worksheet object
    Dim oleObj As Excel.OLEObject       ' embeded object
    Dim EmbedFile, MyWbk As String

    MyWbk = "M:\SS\DD\Projects\cash_dep2000\TEST.xlsx"
    EmbedFile = "M:\SS\DD\Projects\cash_dep2000\DaytonFreight.pdf"

    Set wbkObj = xlObj.Workbooks.Add    ' workbook is added in open condition in memory
    Set wstObj = wbkObj.Worksheets(1)   ' workbook is created with one worksheet
    Set oleObj = wstObj.OLEObjects.Add(, EmbedFile, False, True)

    wbkObj.SaveAs (MyWbk)               ' saves workbook to folder
    wbkObj.Close                        ' closes workbook in folder
    Set oleObj = Nothing
    Set wstObj = Nothing
    Set wbkObj = Nothing
    Set xlObj = Nothing

    MsgBox ("Test Complete")
End Sub
</code>```

答:
This works to embed pdf icon/link but it also opens the pdf. Aggravating.

ActiveSheet.OLEObjects.Add(Filename:="C:\Users\June\MyStuff\DMV.pdf", Link:=False, _
        DisplayAsIcon:=True, IconFileName:= _
        "C:\WINDOWS\Installer\{AC76BA86-7AD7-1033-7B44-AB0000000001}\PDFFile_8.ico", _
        IconIndex:=0, IconLabel:="whatever you want").Activate

I can manually save the file but SaveAs code for macro-enabled workbook errors. More aggravating. Maybe modifying to your object manipulation code will work.

Title: Embedding PDF in Spreadsheet

Body:
Goal is to run this subroutine in an Access application, which embeds a PDF document in a new Excel workbook.  The sub works properly with a text file, but will give error "Run-time error '1004': Document not saved." with a PDF file.  The code breaks on the SaveAs method.  Why does one file-type embed, and the PDF file-type not work?  Any help will be appreciated.

Sub SavePDFInWorkBook()
    Dim xlObj As New Excel.Application  ' Excel application
    Dim wbkObj As Excel.workbook        ' workbook object
    Dim wstObj As Excel.Worksheet       ' worksheet object
    Dim oleObj As Excel.OLEObject       ' embeded object
    Dim EmbedFile, MyWbk As String

    MyWbk = "M:\SS\DD\Projects\cash_dep2000\TEST.xlsx"
    EmbedFile = "M:\SS\DD\Projects\cash_dep2000\DaytonFreight.pdf"

    Set wbkObj = xlObj.Workbooks.Add    ' workbook is added in open condition in memory
    Set wstObj = wbkObj.Worksheets(1)   ' workbook is created with one worksheet
    Set oleObj = wstObj.OLEObjects.Add(, EmbedFile, False, True)

    wbkObj.SaveAs (MyWbk)               ' saves workbook to folder
    wbkObj.Close                        ' closes workbook in folder
    Set oleObj = Nothing
    Set wstObj = Nothing
    Set wbkObj = Nothing
    Set xlObj = Nothing

    MsgBox ("Test Complete")
End Sub


问:
HTML inside XML CDATA being converted with < and > brackets
I have some sample XML:

```<code><sample><![CDATA[Line 1<br />Line 2<br />Line 3<br />]]></sample>
</code>```

I'm using ASP to output this XML using a stylesheet like so:

```<code>Set xmlHttp = Server.CreateObject("Microsoft.XMLHTTP")
xmlHttp.open "GET", URLxml, false
xmlHttp.send()

Set xslHttp = Server.CreateObject("Microsoft.XMLHTTP")
xslHttp.open "GET", xXsl, false
xslHttp.send()

Set xmlDoc = Server.CreateObject("MICROSOFT.XMLDOM")
Set xslDoc = Server.CreateObject("MICROSOFT.XMLDOM")
xmlDoc.async = false
xslDoc.async = false
xmlDoc.Load xmlHttp.responseXML
xslDoc.Load xslHttp.responseXML

Response.Write xmlDoc.transformNode(xslDoc)
</code>```

However, once this is getting written, the HTML output is showing up as:

```<code>Line 1<br />Line 2<br />Line 3
</code>```

I can see that ASP is converting the brackets in the code, but I'm not sure why.  Any thoughts?

答:
In addition to @Alejandro's explanation, here is the best possible solution:

Never put markup in a text (CDATA) node.

Instead of:

```<code><sample><![CDATA[Line 1<br />Line 2<br />Line 3<br />]]></sample>
</code>```

always create:

```<code><sample>Line 1<br />Line 2<br />Line 3<br /></sample>
</code>```

Remember: Putting markup inside of CDATA is losing it.

Body:
I have some sample XML:

<sample><![CDATA[Line 1
Line 2
Line 3
]]></sample>

I'm using ASP to output this XML using a stylesheet like so:

Set xmlHttp = Server.CreateObject("Microsoft.XMLHTTP")
xmlHttp.open "GET", URLxml, false
xmlHttp.send()

Set xslHttp = Server.CreateObject("Microsoft.XMLHTTP")
xslHttp.open "GET", xXsl, false
xslHttp.send()

Set xmlDoc = Server.CreateObject("MICROSOFT.XMLDOM")
Set xslDoc = Server.CreateObject("MICROSOFT.XMLDOM")
xmlDoc.async = false
xslDoc.async = false
xmlDoc.Load xmlHttp.responseXML
xslDoc.Load xslHttp.responseXML

Response.Write xmlDoc.transformNode(xslDoc)

However, once this is getting written, the HTML output is showing up as:

Line 1
Line 2
Line 3

I can see that ASP is converting the brackets in the code, but I'm not sure why.  Any thoughts?

Body:
In addition to @Alejandro's explanation, here is the best possible solution:

Never put markup in a text (CDATA) node.

Instead of:

<sample><![CDATA[Line 1<br />Line 2<br />Line 3<br />]]></sample>

always create:

<sample>Line 1<br />Line 2<br />Line 3<br /></sample>

Remember: Putting markup inside of CDATA is losing it.


问:
How to issue a warning when package is required at runtime
How can I have emacs issue a warning when a package is required at runtime? I want to do something like cl does with its warning,

Warning: cl package required at runtime

I don't see the responsible piece of code in the cl library.

答: Looks like it comes from byte-compile-file-form-require in bytecomp.el.  There's a line (put 'require 'byte-hunk-handler 'byte-compile-file-form-require) which seems to make it hook into require.  You can redefine byte-compile-file-form-require to make it warn on other libraries.


问:
Log4j is already not configured via logback.groovy file in Grails 3.2.8
As we know by default logging in Grails 3.0 is handled by the Logback logging framework and can be configured with the grails-app/conf/logback.groovy file. The good part of this was that the configuration inside this file was applicable for the Logback and Log4j implementations (tested successfully in Grails 3.1.2). After we migrated to use Grails 3.2.8 from Grails 3.1.2 (as I said before), it seems that the configuration inside the logback.groovy file is not used by the Log4j and it should be configured in other way - at runtime.

I made a deep research in this to ensure that this is really the way it is configured now and it seems that if I am using the default Log4j logging:

```<code>org.apache.log4j.Logger.getLogger("name").info("TEST");
</code>```

is not working at all. To make the information populated into the output log file, I should use the default SLF4J API:

```<code>org.slf4j.LoggerFactory.getLogger("name").info("TEST");
</code>```

The problem here is because that we have a lot of places in the code where the logging is implemented using Log4j approach and now - nothing is written in the log file.

So I have two questions here. The first one - is this the exact way how Grails implemented this behavior (as nothing is mentioned in the official documentation - Grails 3.2.8 Documentation). The second one - is the XML or RUNTIME configurations are the best way to configure the Log4j, so use it as before. If yes - the bad thing here is that we should maintain two same configurations at a time. Is there any other way to configure the Log4j to use the same configuration as the Grails Logger.

P.S. There is no need to publish any code, as all are just default configurations.

Thanks a lot!

答:
```<code>appender('STDOUT', ConsoleAppender) {
    encoder(PatternLayoutEncoder) {
        charset = Charset.forName('UTF-8')
    }
}

root(ERROR, ['STDOUT'])
logger("<package_name>", DEBUG)

List artifacts = ["conf", "controllers", "domain", "init"]
artifacts.each { artifact ->
    logger("grails.app.${artifact}.<package_name>", DEBUG)
}
</code>```

After writing this, you can add logger for debugging in any artifacts mentioned above like:

```<code>log.debug "Any Message"
</code>```

For more setting you can read here: https://logback.qos.ch/manual/groovy.html

Body:
As we know by default logging in Grails 3.0 is handled by the Logback logging framework and can be configured with the grails-app/conf/logback.groovy file. The good part of this was that the configuration inside this file was applicable for the Logback and Log4j implementations (tested successfully in Grails 3.1.2). After we migrated to use Grails 3.2.8 from Grails 3.1.2 (as I said before), it seems that the configuration inside the logback.groovy file is not used by the Log4j and it should be configured in other way - at runtime.

I made a deep research in this to ensure that this is really the way it is configured now and it seems that if I am using the default Log4j logging:

org.apache.log4j.Logger.getLogger("name").info("TEST");

is not working at all. To make the information populated into the output log file, I should use the default SLF4J API:

org.slf4j.LoggerFactory.getLogger("name").info("TEST");

The problem here is because that we have a lot of places in the code where the logging is implemented using Log4j approach and now - nothing is written in the log file.

So I have two questions here. The first one - is this the exact way how Grails implemented this behavior (as nothing is mentioned in the official documentation - Grails 3.2.8 Documentation). The second one - is the XML or RUNTIME configurations are the best way to configure the Log4j, so use it as before. If yes - the bad thing here is that we should maintain two same configurations at a time. Is there any other way to configure the Log4j to use the same configuration as the Grails Logger.

P.S. There is no need to publish any code, as all are just default configurations.

Thanks a lot!

Body:
appender('STDOUT', ConsoleAppender) {
    encoder(PatternLayoutEncoder) {
        charset = Charset.forName('UTF-8')
    }
}

root(ERROR, ['STDOUT'])
logger("<package_name>", DEBUG)

List artifacts = ["conf", "controllers", "domain", "init"]
artifacts.each { artifact ->
    logger("grails.app.${artifact}.<package_name>", DEBUG)
}

After writing this, you can add logger for debugging in any artifacts mentioned above like:

log.debug "Any Message"

For more setting you can read here: https://logback.qos.ch/manual/groovy.html


问:
Cairo: Draw an array of pixels
I'm just starting to explore Cairo, but right now I really want to use it for something very simple.

I have a very low-tech bitmap, i.e., a 3*X*Y array of numbers.  I'd like to use Cairo to make this into a bitmap and write to a file.  I'm looking through tutorials and I'm not seeing a way to use it for comparatively low-level functions like this.

I don't think I need guidance on how to use the tool once I know what the tool is.

答:
I didn't actually test this, but the following should give you lots of useful hints:</p>

```<code>#include <cairo.h>
#include <stdint.h>

#define WIDTH 42
#define HEIGHT 42
uint8_t data[WIDTH][HEIGHT][3];

cairo_surface_t* convert()
{
    cairo_surface_t *result;
    unsigned char *current_row;
    int stride;

    result = cairo_image_surface_create(CAIRO_FORMAT_RGB24, WIDTH, HEIGHT);
    if (cairo_surface_status(result) != CAIRO_STATUS_SUCCESS)
        return result;

    cairo_surface_flush(result);
    current_row = cairo_image_surface_get_data(result);
    stride = cairo_image_surface_get_stride(result);
    for (int y = 0; y < HEIGHT; y++) {
        uint32_t *row = (void *) current_row;
        for (int x = 0; x < WIDTH; x++) {
            uint32_t r = data[x][y][0];
            uint32_t g = data[x][y][1];
            uint32_t b = data[x][y][2];
            row[x] = (r << 16) | (g << 8) | b;
        }

        current_row += stride;
    }
    cairo_surface_mark_dirty(result);
    return result;
}
</code>```

Title: Cairo: Draw an array of pixels

Body:
I didn't actually test this, but the following should give you lots of useful hints:

#include <cairo.h>
#include <stdint.h>

#define WIDTH 42
#define HEIGHT 42
uint8_t data[WIDTH][HEIGHT][3];

cairo_surface_t* convert()
{
    cairo_surface_t *result;
    unsigned char *current_row;
    int stride;

    result = cairo_image_surface_create(CAIRO_FORMAT_RGB24, WIDTH, HEIGHT);
    if (cairo_surface_status(result) != CAIRO_STATUS_SUCCESS)
        return result;

    cairo_surface_flush(result);
    current_row = cairo_image_surface_get_data(result);
    stride = cairo_image_surface_get_stride(result);
    for (int y = 0; y < HEIGHT; y++) {
        uint32_t *row = (void *) current_row;
        for (int x = 0; x < WIDTH; x++) {
            uint32_t r = data[x][y][0];
            uint32_t g = data[x][y][1];
            uint32_t b = data[x][y][2];
            row[x] = (r << 16) | (g << 8) | b;
        }

        current_row += stride;
    }
    cairo_surface_mark_dirty(result);
    return result;
}