问:
What are the benefits of using A B C as table alias in a SQL query just based on the order the tables are added in the FROM clause?
We sent some of our new starters off for some basic SQL training and they came back renaming tables as A for the first table and B for the second and so on. One of them said they were told:
 - It was quicker to type
 - If you use the starting letter then you run into issues when you have tables starting with the same name

In my opinion this seriously sacrifices the readability of the query and I'm probably going to be the one reviewing the code they write. I just want to make sure I'm not missing something before I tell them to either use the first letter and number if there are multiple tables or just an abbreviated version of the table name. In most cases the table names are only 5-8 letters long so I'd prefer they use the full name than an alias that doesn't describe the table in any way.

Are there any other benefits?

答:
well, I would like to point two facts with examples

1.-   select * from pupils pup inner join pupils pup2 on pup.id=pup2.otherId. In this example, I know exactly what I am linking because I am using the same table twice, really useful for queries where the same table is linked twice at least.

```<code>2.- readability is not a problem if you chose well the alias:

 select * from pupils pup inner join parents  payees on
  parents.id=pupils.parentid
  inner join parents tutors on pupils.tutorid=tutors.id
</code>```

In this case, readability is not an issue and I still know and distinguish which are the parents who pay and the tutors or legal guardians.

Body:
well, I would like to point two facts with examples

1.-   select * from pupils pup inner join pupils pup2 on pup.id=pup2.otherId. In this example, I know exactly what I am linking because I am using the same table twice, really useful for queries where the same table is linked twice at least.

2.- readability is not a problem if you chose well the alias:

 select * from pupils pup inner join parents  payees on
  parents.id=pupils.parentid
  inner join parents tutors on pupils.tutorid=tutors.id

In this case, readability is not an issue and I still know and distinguish which are the parents who pay and the tutors or legal guardians.


来源: stackexchange

问:
Difference in initializing char-array and char with integer literals
On my system (4.13.11-1-ARCH, gcc 7.2.0) char is signed. When initializing an array of char with an integer literal like this:

```<code>const char mydata[] = {
    0x80
};
</code>```

I get the following error:

```<code>error: narrowing conversion of ‘128’ from ‘int’ to ‘char’ inside { } [-Wnarrowing]
</code>```

However, when I instead do const char data = 0x80 the compiler is not worried of any narrowing, although it happens of course. The output is 7F, the highest positive signed char value.

Question

Why is the compiler not equally worried about truncation in both cases?

答:
An initializer of the form const char c = 0x80 is a much older construct than
initializer lists, which have been introduced later. So it was possible to define stricter rules for initializer lists, while these rules where not applied to "older" initializers (probably because of not to break "older" code more than necessary).

Hence, initializer lists as defined in this online c++ standard draft forbid such narrowing:

8.5.1 Aggregates

(2) When an aggregate is initialized by an initializer list, as
  specified in [dcl.init.list], the elements of the initializer list are
  taken as initializers for the members of the aggregate, in increasing
  subscript or member order. Each member is copy-initialized from the
  corresponding initializer-clause. If the initializer-clause is an
  expression and a narrowing conversion ([dcl.init.list]) is required to
  convert the expression, the program is ill-formed. ...

BTW: If you use a brace initializer like const char data { 0x80 }, you will get an error, too. So the stricter rules are due to brace-initializers / initializer lists, and not due to whether you initialize an array or a scalar value.

ContentLicense: CC BY-SA 3.0

Body:
On my system (4.13.11-1-ARCH, gcc 7.2.0) char is signed. When initializing an array of char with an integer literal like this:

const char mydata[] = {
    0x80
};

I get the following error:

error: narrowing conversion of ‘128’ from ‘int’ to ‘char’ inside { } [-Wnarrowing]

However, when I instead do const char data = 0x80 the compiler is not worried of any narrowing, although it happens of course. The output is 7F, the highest positive signed char value.

Question

Why is the compiler not equally worried about truncation in both cases?


问:
Laravel parsing json output correctly
i am using this code in laravel .

```<code> $user_detail = \App\Userpacakage::with('user.pacakage')->where('pacakage_id', '=', 1)->get(); //->lists('nombre', 'id')
        return response()->json($user_detail);
</code>```

this is my json output ->

```<code>[{"id":1,"user_id":1,"pacakage_id":1,"transaction_id":"jfjkgjgjkhkjkg55rtf","created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00","user":{"id":1,"name":"omsun","email":"omsun123@gmail.com","contact":2147483647,"regkey":"","created_at":"2015-11-21 01:18:33","updated_at":"2015-11-21 01:18:33","pacakage":[{"id":1,"title":"dsagdjas","description":"<p>\r\n\tsamndbmasndmas,<\/p>\r\n","tab_id":0,"from":"11\/27\/2015","to":"12\/03\/2015","days":22,"unlimited":0,"criteria":1,"category_id":1,"subcategory_id":0,"subject_id":0,"price":2432,"created_at":"2015-11-21 19:07:10","updated_at":"2015-11-21 19:07:10","pivot":{"user_id":1,"pacakage_id":1}}]}}]
</code>```

using jquery i am using this code to fetch user details

```<code>$.get('api/classallocation?pacakage_id=' + pacakage_id, function (data) {

                    console.log(data);
                     $.each(data, function (i, user) {

                         console.log(user.name));
                     });
</code>```

i want to know how to fetch the pacakage details in jquery ..like pacakage title ,price.

答:
```<code>$.get('api/classallocation?pacakage_id=' + pacakage_id, function (data) {
   console.log(data);
   $.each(data, function (i, user) {
   console.log(user.pacakage[0].title));
});
</code>```

Title: Laravel parsing json output correctly

Body:
i am using this code in laravel .

 $user_detail = \App\Userpacakage::with('user.pacakage')->where('pacakage_id', '=', 1)->get(); //->lists('nombre', 'id')
        return response()->json($user_detail);

this is my json output ->

[{"id":1,"user_id":1,"pacakage_id":1,"transaction_id":"jfjkgjgjkhkjkg55rtf","created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00","user":{"id":1,"name":"omsun","email":"omsun123@gmail.com","contact":2147483647,"regkey":"","created_at":"2015-11-21 01:18:33","updated_at":"2015-11-21 01:18:33","pacakage":[{"id":1,"title":"dsagdjas","description":"
\r\n\tsamndbmasndmas,<\/p>\r\n","tab_id":0,"from":"11\/27\/2015","to":"12\/03\/2015","days":22,"unlimited":0,"criteria":1,"category_id":1,"subcategory_id":0,"subject_id":0,"price":2432,"created_at":"2015-11-21 19:07:10","updated_at":"2015-11-21 19:07:10","pivot":{"user_id":1,"pacakage_id":1}}]}}]

using jquery i am using this code to fetch user details

$.get('api/classallocation?pacakage_id=' + pacakage_id, function (data) {

                    console.log(data);
                     $.each(data, function (i, user) {

                         console.log(user.name));
                     });

i want to know how to fetch the pacakage details in jquery ..like pacakage title ,price.


问:
Get differences between 2 linq entities and associated children entities
I would like to compare two LINQ entities of the same type and return a list differences between the two.  I have code that compares properties and returns the differences.

(from: https://stackoverflow.com/a/5812100/2343826)

```<code>    public static void WriteChanges<T>(T obj1, T obj2, string objName, int objId, int userId)
    {
        PropertyInfo[] properties = typeof(T).GetProperties();
        StringBuilder sb = new StringBuilder();

        foreach (PropertyInfo pi in properties)
        {
            object value1 = typeof(T).GetProperty(pi.Name).GetValue(obj1, null);
            object value2 = typeof(T).GetProperty(pi.Name).GetValue(obj2, null);

            if (value1 != value2 && (value1 == null || !value1.Equals(value2)))
            {
                sb.Append(string.Format("Property {0} changed from {1} to {2}" + Environment.NewLine, pi.Name, value1, value2));
            }
        }
        Write(objName, objId, sb.ToString(), userId);
    }
</code>```

Results IN:

Property oItem changed from NS.oItem to NS.oItem

Property dvPC changed from pcName1 to pcName2

Can this code be modified to determine if the property is also a LINQ entity and if so recursively check the child entity for differences?

For instance, in the example results above, NS.oItem is a child entity associated to obj1.  I would like the method to iterate through the child object to compare the differences in it between obj1 and obj2

Thanks for your help

答: You can do that, but mixing templates and reflection makes it unnecessarily complex - I'd re-write this as a non-template function, it can just take two variables of type object and fail up-front if they're not of the same type. I'm not sure why you need to check whether a property "is" a LINQ entity (which doesn't really make sense - do you mean, is mapped to an Entity Framework entity?  But do you need to prevent infinite recursion where an object of type A has a property of type B, which also has a property of type A. (this is not uncommon with EF entities in order to capture foreign-key relationships - and not recursing for any property with a ForeignKey annotation is probably what you want).</p>

Body:
I would like to compare two LINQ entities of the same type and return a list differences between the two.  I have code that compares properties and returns the differences.

(from: https://stackoverflow.com/a/5812100/2343826)

    public static void WriteChanges<T>(T obj1, T obj2, string objName, int objId, int userId)
    {
        PropertyInfo[] properties = typeof(T).GetProperties();
        StringBuilder sb = new StringBuilder();

        foreach (PropertyInfo pi in properties)
        {
            object value1 = typeof(T).GetProperty(pi.Name).GetValue(obj1, null);
            object value2 = typeof(T).GetProperty(pi.Name).GetValue(obj2, null);

            if (value1 != value2 && (value1 == null || !value1.Equals(value2)))
            {
                sb.Append(string.Format("Property {0} changed from {1} to {2}" + Environment.NewLine, pi.Name, value1, value2));
            }
        }
        Write(objName, objId, sb.ToString(), userId);
    }

Results IN:

Property oItem changed from NS.oItem to NS.oItem

Property dvPC changed from pcName1 to pcName2

Can this code be modified to determine if the property is also a LINQ entity and if so recursively check the child entity for differences?

For instance, in the example results above, NS.oItem is a child entity associated to obj1.  I would like the method to iterate through the child object to compare the differences in it between obj1 and obj2

Thanks for your help


问:
Is Java Point class getX() or getY() is casted automatically?
I'm trying to simulate cinematic equations for a physical object, so I want to change velocity every ten milli seconds according to acceleration.here's the part of code which doesn't work for me :(int delay = 10)

```<code>public static void main(String[] args) {
    Point velocity = new Point();
    Point acceleration = new Point(20.0, 0);
    velocity.setLocation(10, 19);

    while (true) {
        velocity.setLocation(velocity.getX() +
            acceleration.getX() * 10 / 1000.0, 19);
        System.out.println(velocity.getX());
    }
}
</code>```

It's unusual that this line doesn't change the velocity's x or y.(and acceleration's x is 20 and it's y is 40.0 ; in case their range makes a difference that I doubt it does)
When I print acceleration.getX() * delay / 1000.0 it prints 0.0 and when I try printing it after replacing acceleration.getX() with its amount it prints the real amount.

Does anyone know what's wrong with this code?

Is getX() casted or something automatically?

答:
As you can see in

Point Documentation

The values that define the point are stored as ints so if the double you want to store is between 0.0 and 1.0 (as is the case on your example) it gets cast to a 0.

Body:
I'm trying to simulate cinematic equations for a physical object, so I want to change velocity every ten milli seconds according to acceleration.here's the part of code which doesn't work for me :(int delay = 10)

public static void main(String[] args) {
    Point velocity = new Point();
    Point acceleration = new Point(20.0, 0);
    velocity.setLocation(10, 19);

    while (true) {
        velocity.setLocation(velocity.getX() +
            acceleration.getX() * 10 / 1000.0, 19);
        System.out.println(velocity.getX());
    }
}

It's unusual that this line doesn't change the velocity's x or y.(and acceleration's x is 20 and it's y is 40.0 ; in case their range makes a difference that I doubt it does)
When I print acceleration.getX() * delay / 1000.0 it prints 0.0 and when I try printing it after replacing acceleration.getX() with its amount it prints the real amount.

Does anyone know what's wrong with this code?

Is getX() casted or something automatically?


问:
Jenkins "unable to find valid certification path to requested target" error while importing Git repository
I'm trying to build a Git repo from Jenkins using the Jenkins Git Plugin on my laptop. The Git repo resides on company trusted server which has self-signed certificates. While specifying the URL I'm always getting an error:

```<code>Failed to connect to repository : sun.security.validator.ValidatorException:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target
</code>```

I understand this error surfaces due to self-signed certificates but the server belongs to my company and is signed by authority.

I also tried to import the same repo from another laptop using self-signed and keep getting the same error.

Any help will be appreciated

答:
That error is a common error message reported by the Java Virtual Machine. This is caused when the Java environment does not have information about the HTTPS server to verify that it is a valid website. Sometimes the certificate is provided by an internal Root CA or is a Self-Signed Certificate. This sometimes can confuse the JVM as it is not one of the ones on the Java “trusted” list who can provide these certificates.

Because we know that the certificate is “valid” we can import this certificate directly into the JVM. In doing so, we tell the JVM that this is is a “trusted” certificate and to “ignore” any issues with it.

You will need to add the certificate to your Java Certificate Authority file. For an Debian/Ubuntu Linux machine, that's usually located here:

```<code>$JAVA_HOME/jre/lib/security/cacerts
</code>```

However, you don't want to add it to the JRE cacert keystore because it will be overwritten/rewritten by the JRE, so it's best to duplicate this file for Jenkins.

$JAVA_HOME - This should be the location of where your current java home is. If you only have the Java Runtime Environment (JRE) installed, then you can replace $JAVA_HOME/jre with the $JRE_HOME.

$ALIAS - This can be any value. It is a value to distinguish this certificate from others. Example would be “git-repo”, or “artifact server”.

$JENKINS_HOME - This is the path to your Jenkins home. Often /var/lib/jenkins.

You can import the certificate into your JVM cacerts file using the following commands. -- In your Jenkins master. Obtain the certificate, copy the JVM keystore for Jenkins, import the certificate into the keystore, add the trusted keystore to the Jenkins startup parameters and restart Jenkins.

```<code># Import certificate
openssl s_client -showcerts -connect https://your-target-server\
< /dev/null 2> /dev/null | openssl x509 -outform PEM > ~/root_ca.pem

# Duplicate Java Keystore file and move into Jenkins...
mkdir $JENKINS_HOME/keystore/
cp $JAVA_HOME/jre/lib/security/cacerts $JENKINS_HOME/keystore/

# Add Certificate to Keystore
keytool -import -alias $ALIAS -keystore $JENKINS_HOME/keystore/cacerts -file ~/root_ca.pem

# Add -Djavax.net.ssl.trustStore=$JENKINS_HOME/keystore/cacerts to the
# Jenkins startup parameters. For Debian/Ubuntu, this is /etc/default/jenkins
echo 'JAVA_ARGS="$JAVA_ARGS -Djavax.net.ssl.trustStore=$JENKINS_HOME/keystore/cacerts"'\
>> /etc/default/jenkins

sudo service jenkins restart
</code>```

Reference Help:

PKIX path building failed error message

How to install a new SSL Certificate in Jenkins

How to add Java arguments to Jenkins

Body:
I'm trying to build a Git repo from Jenkins using the Jenkins Git Plugin on my laptop. The Git repo resides on company trusted server which has self-signed certificates. While specifying the URL I'm always getting an error:

Failed to connect to repository : sun.security.validator.ValidatorException:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target

I understand this error surfaces due to self-signed certificates but the server belongs to my company and is signed by authority.

I also tried to import the same repo from another laptop using self-signed and keep getting the same error.

Any help will be appreciated

Body:
That error is a common error message reported by the Java Virtual Machine. This is caused when the Java environment does not have information about the HTTPS server to verify that it is a valid website. Sometimes the certificate is provided by an internal Root CA or is a Self-Signed Certificate. This sometimes can confuse the JVM as it is not one of the ones on the Java “trusted” list who can provide these certificates.

Because we know that the certificate is “valid” we can import this certificate directly into the JVM. In doing so, we tell the JVM that this is is a “trusted” certificate and to “ignore” any issues with it.

You will need to add the certificate to your Java Certificate Authority file. For an Debian/Ubuntu Linux machine, that's usually located here:

$JAVA_HOME/jre/lib/security/cacerts

However, you don't want to add it to the JRE cacert keystore because it will be overwritten/rewritten by the JRE, so it's best to duplicate this file for Jenkins.

$JAVA_HOME - This should be the location of where your current java home is. If you only have the Java Runtime Environment (JRE) installed, then you can replace $JAVA_HOME/jre with the $JRE_HOME.

$ALIAS - This can be any value. It is a value to distinguish this certificate from others. Example would be “git-repo”, or “artifact server”.

$JENKINS_HOME - This is the path to your Jenkins home. Often /var/lib/jenkins.

You can import the certificate into your JVM cacerts file using the following commands. -- In your Jenkins master. Obtain the certificate, copy the JVM keystore for Jenkins, import the certificate into the keystore, add the trusted keystore to the Jenkins startup parameters and restart Jenkins.

# Import certificate
openssl s_client -showcerts -connect https://your-target-server\
< /dev/null 2> /dev/null | openssl x509 -outform PEM > ~/root_ca.pem

# Duplicate Java Keystore file and move into Jenkins...
mkdir $JENKINS_HOME/keystore/
cp $JAVA_HOME/jre/lib/security/cacerts $JENKINS_HOME/keystore/

# Add Certificate to Keystore
keytool -import -alias $ALIAS -keystore $JENKINS_HOME/keystore/cacerts -file ~/root_ca.pem

# Add -Djavax.net.ssl.trustStore=$JENKINS_HOME/keystore/cacerts to the
# Jenkins startup parameters. For Debian/Ubuntu, this is /etc/default/jenkins
echo 'JAVA_ARGS="$JAVA_ARGS -Djavax.net.ssl.trustStore=$JENKINS_HOME/keystore/cacerts"'\
>> /etc/default/jenkins

sudo service jenkins restart

Reference Help:

PKIX path building failed error message

How to install a new SSL Certificate in Jenkins

How to add Java arguments to Jenkins

ContentLicense: CC BY-SA 4.0


问:
reassign a new "character" to a key, so that it gets printed instead of the default letter for the key
I'm in the process of developing a text editor that has a "macro system," where the user can reassign values to the keys on their keyboard -- so that when they press the letter a, it might print the letter "z" instead. (Really, it'll be used for math symbols, not other letters).

Can anyone get me started on the Java code to reassign a value to a key within a JTextPane?

If you need more details, let me know.

Thank you!

So far, this is what I have:

```<code>public void keyPressed(KeyEvent evt) {
//Called when a key is pressed.

//Intercept the key before the default value is printed.
//1. Suppress the original character. Do this in the KeyEvent object
//by setting the doit property to false in your listener if the key
//matches a macro.

    jTextPane1.addKeyListener(new KeyAdapter() {
public void keyPressed(keyEvent event) {
if (event.getKeyCode() == KeyEvent.VK_A) {
//Perform an action when A is pressed and there is a macro.
if(macroA == true)
{
    keyPressed.doit() = false;
}
}
}
else if (event.getKeyCode() == KeyEvent.VK_B) {
//Perform an action when B is pressed if there is a macro.
if(macroB == true)
{
    keyPressed.doit() = false;
}
}
}
});
</code>```

I'm working on how to implement it with "creating" the macro, checking to see if a macro exists.

If you have any more advice, I would appreciate it.

Thank you.

答:
If you want to change the character displayed in the text pane then you have two options (that I can think of)

a) rewrite the code that displays the text in the text pane
b) insert a different character into the Document so that character will get painted

Option two is the easier approach.

For simple one to one key mappings you can just use a DocumentFilter.

For more complex key mappings, like using Ctrl+1, to enter a special character you would then use KeyBindings.

The Swing tutorial has section on both of these approaches. See "Text Component Features" and "Using Key Bindings".

Body:
I'm in the process of developing a text editor that has a "macro system," where the user can reassign values to the keys on their keyboard -- so that when they press the letter a, it might print the letter "z" instead. (Really, it'll be used for math symbols, not other letters).

Can anyone get me started on the Java code to reassign a value to a key within a JTextPane?

If you need more details, let me know.

Thank you!

So far, this is what I have:

public void keyPressed(KeyEvent evt) {
//Called when a key is pressed.

//Intercept the key before the default value is printed.
//1. Suppress the original character. Do this in the KeyEvent object
//by setting the doit property to false in your listener if the key
//matches a macro.

    jTextPane1.addKeyListener(new KeyAdapter() {
public void keyPressed(keyEvent event) {
if (event.getKeyCode() == KeyEvent.VK_A) {
//Perform an action when A is pressed and there is a macro.
if(macroA == true)
{
    keyPressed.doit() = false;
}
}
}
else if (event.getKeyCode() == KeyEvent.VK_B) {
//Perform an action when B is pressed if there is a macro.
if(macroB == true)
{
    keyPressed.doit() = false;
}
}
}
});

I'm working on how to implement it with "creating" the macro, checking to see if a macro exists.

If you have any more advice, I would appreciate it.

Thank you.

ContentLicense: CC BY-SA 2.5


问:
detect if only one attribute is updated in Rails 4 on update_attributes
I am making a blogging app. I need to have two different methods based on how many attributes have been changed. Essentially, if ONLY the publication_date changes I do one thing...even the publication_date and ANYTHING ELSE changes, I do another thing.

posts_controller.rb

```<code>def special_update
  if #detect change of @post.publication_date only
    #do something
  elsif # @post changes besides publication_date
  elsif #no changes
  end
end
</code>```

答:
Or simply compare parameter with existing value</p>

```<code>if params[:my_model][:publication_date] != @my_model.publication_date
  params[:my_model][:publication_date] =  Time.now
end
</code>```

Body:
I am making a blogging app. I need to have two different methods based on how many attributes have been changed. Essentially, if ONLY the publication_date changes I do one thing...even the publication_date and ANYTHING ELSE changes, I do another thing.

posts_controller.rb

def special_update
  if #detect change of @post.publication_date only
    #do something
  elsif # @post changes besides publication_date
  elsif #no changes
  end
end

Body:
Or simply compare parameter with existing value

if params[:my_model][:publication_date] != @my_model.publication_date
  params[:my_model][:publication_date] =  Time.now
end


问:
Create solid polygon in boost geometry
I'm newbie at boost geometry, I have created polygon with boost::geometry::assign_points(). But I only create outer and inner of that polygon is empty. So I try test boost::geometry::overlaps() with two polygons A, B and A is inside B, result is not overlaps.

So, What can I do to create solid polygon (only know outer point of polygon and inside of polygon is valid) ?

答:
Polygons are by definition solid until you subtract inner rings. From §6.1.11.1 from the standard¹:

A Polygon is a planar Surface defined by 1 exterior boundary and 0 or more interior boundaries. Each interior
  boundary defines a hole in the Polygon. A Triangle is a polygon with 3 distinct, non-collinear vertices and no
  interior boundary. ¹

Overlapping doesn't mean what you think it means.

From §6.1.15.3 (Named spatial relationship predicates based on the DE-9IM)

Crosses

Within

Overlaps

It is defined as

```<code>a.Overlaps(b) ⇔ ( dim(I(a)) = dim(I(b)) = dim(I(a) ∩ I(b)))
                 ∧ (a ∩ b ≠ a) ∧ (a ∩ b ≠ b)
</code>```

Contains

```<code>a.Contains(b) ⇔ b.Within(a)
</code>```

Intersects

```<code>a.Intersects(b) ⇔ ! a.Disjoint(b)
</code>```

In your case you might be looking for !disjoint, within, contains or intersection:

Live On Coliru

```<code>#include <boost/geometry.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <iostream>

namespace bg = boost::geometry;

template <typename Geo> void debug(std::string name, Geo const& g) {
    std::string reason;
    std::cout << name << ": " << bg::dsv(g) << " " << bg::is_valid(g, reason) << ", '" << reason << "'\n";
}

template <typename Geo, typename F>
void both_ways(std::string name, Geo const& a, Geo const& b, F f) {
    std::cout << name << "(a, b) -> " << f(a,b) << "\n";
    std::cout << name << "(b, a) -> " << f(b,a) << "\n";
}

int main() {
    std::cout << std::boolalpha;

    using Pt = bg::model::d2::point_xy<int>;
    using Poly = bg::model::polygon<Pt>;
    using Multi = bg::model::multi_polygon<Poly>;

    Poly const a {{ { 0,0 }, { 0,3 }, { 3,3 }, { 3,0 }, { 0,0 }} };
    Poly const b {{ { 1,1 }, { 1,2 }, { 2,2 }, { 2,1 }, { 1,1 }} };

    debug("a", a);
    debug("b", b);

#define TEST(algo) both_ways(#algo, a, b, [](auto& a, auto& b) { return bg::algo(a, b); })
    TEST(overlaps);
    TEST(intersects);
    TEST(within);
    //TEST(contains); // contains(a,b) ⇔ within(b,a)
    //TEST(crosses); // not implemented for polygons
    TEST(disjoint);

    both_ways("intersection", a, b, [](auto& a, auto& b) {
        Multi c;
        bg::intersection(a, b, c);
        return boost::lexical_cast<std::string>(bg::dsv(c));
    });
}
</code>```

Which prints

```<code>a: (((0, 0), (0, 3), (3, 3), (3, 0), (0, 0))) true, 'Geometry is valid'
b: (((1, 1), (1, 2), (2, 2), (2, 1), (1, 1))) true, 'Geometry is valid'
overlaps(a, b) -> false
overlaps(b, a) -> false
intersects(a, b) -> true
intersects(b, a) -> true
within(a, b) -> false
within(b, a) -> true
disjoint(a, b) -> false
disjoint(b, a) -> false
intersection(a, b) -> ((((1, 1), (1, 2), (2, 2), (2, 1), (1, 1))))
intersection(b, a) -> ((((1, 1), (1, 2), (2, 2), (2, 1), (1, 1))))
</code>```

¹ The OGC Simple Feature / Common architecture

Title: Create solid polygon in boost geometry

Body:
Polygons are by definition solid until you subtract inner rings. From §6.1.11.1 from the standard¹:

A Polygon is a planar Surface defined by 1 exterior boundary and 0 or more interior boundaries. Each interior
  boundary defines a hole in the Polygon. A Triangle is a polygon with 3 distinct, non-collinear vertices and no
  interior boundary. ¹

Overlapping doesn't mean what you think it means.

From §6.1.15.3 (Named spatial relationship predicates based on the DE-9IM)

Crosses

Within

Overlaps

It is defined as

a.Overlaps(b) ⇔ ( dim(I(a)) = dim(I(b)) = dim(I(a) ∩ I(b)))
                 ∧ (a ∩ b ≠ a) ∧ (a ∩ b ≠ b)

Contains

a.Contains(b) ⇔ b.Within(a)

Intersects

a.Intersects(b) ⇔ ! a.Disjoint(b)

In your case you might be looking for !disjoint, within, contains or intersection:

Live On Coliru

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <iostream>

namespace bg = boost::geometry;

template <typename Geo> void debug(std::string name, Geo const& g) {
    std::string reason;
    std::cout << name << ": " << bg::dsv(g) << " " << bg::is_valid(g, reason) << ", '" << reason << "'\n";
}

template <typename Geo, typename F>
void both_ways(std::string name, Geo const& a, Geo const& b, F f) {
    std::cout << name << "(a, b) -> " << f(a,b) << "\n";
    std::cout << name << "(b, a) -> " << f(b,a) << "\n";
}

int main() {
    std::cout << std::boolalpha;

    using Pt = bg::model::d2::point_xy<int>;
    using Poly = bg::model::polygon<Pt>;
    using Multi = bg::model::multi_polygon<Poly>;

    Poly const a {{ { 0,0 }, { 0,3 }, { 3,3 }, { 3,0 }, { 0,0 }} };
    Poly const b {{ { 1,1 }, { 1,2 }, { 2,2 }, { 2,1 }, { 1,1 }} };

    debug("a", a);
    debug("b", b);

#define TEST(algo) both_ways(#algo, a, b, [](auto& a, auto& b) { return bg::algo(a, b); })
    TEST(overlaps);
    TEST(intersects);
    TEST(within);
    //TEST(contains); // contains(a,b) ⇔ within(b,a)
    //TEST(crosses); // not implemented for polygons
    TEST(disjoint);

    both_ways("intersection", a, b, [](auto& a, auto& b) {
        Multi c;
        bg::intersection(a, b, c);
        return boost::lexical_cast<std::string>(bg::dsv(c));
    });
}

Which prints

a: (((0, 0), (0, 3), (3, 3), (3, 0), (0, 0))) true, 'Geometry is valid'
b: (((1, 1), (1, 2), (2, 2), (2, 1), (1, 1))) true, 'Geometry is valid'
overlaps(a, b) -> false
overlaps(b, a) -> false
intersects(a, b) -> true
intersects(b, a) -> true
within(a, b) -> false
within(b, a) -> true
disjoint(a, b) -> false
disjoint(b, a) -> false
intersection(a, b) -> ((((1, 1), (1, 2), (2, 2), (2, 1), (1, 1))))
intersection(b, a) -> ((((1, 1), (1, 2), (2, 2), (2, 1), (1, 1))))

¹ The OGC Simple Feature / Common architecture


问:
Replace multiple words in strings from a list of words in Python
I have a text file in the following format:

```<code>this is some text __label__a
this is another line __label__a __label__b
this is third line __label__x
this is fourth line __label__a __label__x __label__z
</code>```

and another list of labels

```<code>list_labels = ['__label__x','__label__y','__label__z']
</code>```

Each line could contain multiple labels from the list.
what is the best way to replace labels from the list in each line with "__label__no"

example:

```<code>this is third line __label__no
this is fourth line __label__a __label__no
</code>```

There are a lot more lines in the text file and labels and I was wondering what is the fastest way to achieve this.

答:
This probably isn't a "fastest way" to do it, but depending on the length of your text file, this may work:

```<code>list_labels = ['__label__x','__label__y','__label__z']

with open('text.txt', 'r') as f:
    fcontents = f.readlines()

fcontents = [l.strip() for l in fcontents]

def remove_duplicates(l):
    temp = []
    [temp.append(x) for x in l if x not in temp]
    return temp

for line in fcontents:
    for ll in list_labels:
        if ll in line:
            l = line.replace(ll, '__label__no')
            line = ' '.join(remove_duplicates(l.split()))

    print line
</code>```

output:

```<code>this is some text __label__a
this is another line __label__a __label__b
this is third line __label__no
this is fourth line __label__a __label__no
</code>```

Borrowing the unique_list function from this question How can I remove duplicate words in a string with Python?

Body:
I have a text file in the following format:

this is some text __label__a
this is another line __label__a __label__b
this is third line __label__x
this is fourth line __label__a __label__x __label__z

and another list of labels

list_labels = ['__label__x','__label__y','__label__z']

Each line could contain multiple labels from the list.
what is the best way to replace labels from the list in each line with "__label__no"

example:

this is third line __label__no
this is fourth line __label__a __label__no

There are a lot more lines in the text file and labels and I was wondering what is the fastest way to achieve this.

Body:
This probably isn't a "fastest way" to do it, but depending on the length of your text file, this may work:

list_labels = ['__label__x','__label__y','__label__z']

with open('text.txt', 'r') as f:
    fcontents = f.readlines()

fcontents = [l.strip() for l in fcontents]

def remove_duplicates(l):
    temp = []
    [temp.append(x) for x in l if x not in temp]
    return temp

for line in fcontents:
    for ll in list_labels:
        if ll in line:
            l = line.replace(ll, '__label__no')
            line = ' '.join(remove_duplicates(l.split()))

    print line

output:

this is some text __label__a
this is another line __label__a __label__b
this is third line __label__no
this is fourth line __label__a __label__no

Borrowing the unique_list function from this question How can I remove duplicate words in a string with Python?


问:
How can I access the raw documents from the Brown corpus?
For all other NLTK corpora, calling corpus.raw() yields the original text from the files.
For example:

```<code>>>> from nltk.corpus import webtext
>>> webtext.raw()[:10]
'Cookie Man'
</code>```

However, when calling brown.raw() you get tagged text.

```<code>>>> from nltk.corpus import brown
>>> brown.raw()[:10]
'\n\n\tThe/at '
</code>```

I've read all the documentation I can find but can't seem to find an obvious explanation or way to get the un-tagged version. Is there a reason this corpus is tagged and the others aren't?

答:
The tagged text is the raw document, the actual content of the Brown corpus files. The raw() method shows you exactly what is stored in the files; it only returs clean text for "plain text" corpora, not for "all other corpora" as you assume. Try nltk.corpus.treebank.raw('wsj_0001.mrg') or nltk.corpus.conll2000.raw("train.txt"), for example, and you'll see trees and "IOB format" text respectively.

Now if your goal is to reconstitute readable text, joining on spaces is usually good enough for me:

```<code>for sent in brown.sents():
    print(" ".join(sent))
</code>```

You'll get output like this:

`` Only a relative handful of such reports was received '' , the jury said , `` considering
the widespread interest in the election , the number of voters and the size of this
city '' .
```

If you don't like the way this looks, see the answer by alvas for a more ambitious reconstruction.

Body:
For all other NLTK corpora, calling corpus.raw() yields the original text from the files.
For example:

>>> from nltk.corpus import webtext
>>> webtext.raw()[:10]
'Cookie Man'

However, when calling brown.raw() you get tagged text.

>>> from nltk.corpus import brown
>>> brown.raw()[:10]
'\n\n\tThe/at '

I've read all the documentation I can find but can't seem to find an obvious explanation or way to get the un-tagged version. Is there a reason this corpus is tagged and the others aren't?

Body:
The tagged text is the raw document, the actual content of the Brown corpus files. The raw() method shows you exactly what is stored in the files; it only returs clean text for "plain text" corpora, not for "all other corpora" as you assume. Try nltk.corpus.treebank.raw('wsj_0001.mrg') or nltk.corpus.conll2000.raw("train.txt"), for example, and you'll see trees and "IOB format" text respectively.

Now if your goal is to reconstitute readable text, joining on spaces is usually good enough for me:

for sent in brown.sents():
    print(" ".join(sent))

You'll get output like this:

`` Only a relative handful of such reports was received '' , the jury said , `` considering
the widespread interest in the election , the number of voters and the size of this
city '' .

If you don't like the way this looks, see the answer by alvas for a more ambitious reconstruction.


问:
Sequelize can not import a model
In expressJs project, I try to use sequelize to interact with database.

This is my model/user.js :

module.exports = (sequelize, DataTypes) => {
    sequelize.define('user', {
        email: {
            type: DataTypes.STRING,
            unique: true
        },
        password: DataTypes.STRING
    })
}```
</div>
</div>
</p>

<p>And this is models/index.js :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const fs = require('fs')
const path = require('path')
const Sequelize = require('sequelize')
const config = require('../config/config')
const db = {}

const sequelize = new Sequelize(
  config.db.database,
  config.db.user,
  config.db.password,
  config.db.options
)

fs
  .readdirSync(__dirname)
  .filter((file) =>
      file !== 'index.js'
  )
  .forEach((file) => {
    var a = path.join(__dirname, file);
    const model = sequelize.import(path.join(__dirname, file));
    db[model.name] = model;
  })

db.sequelize = sequelize
db.Sequelize = Sequelize

module.exports = db</code>```

The problem is in this line

```<code>const model = sequelize.import(path.join(__dirname, file));
</code>```

Which returns undefine to model variable.

What did I miss here? I appreciate any hint?

Whole code on Github : here

答:
Problem could be because of a missing return

```<code>module.exports = (sequelize, DataTypes) => {
    const User = sequelize.define('User', { // Missing return
        email: {
            type: DataTypes.STRING,
            unique: true
        },
        password: DataTypes.STRING
    })
}
</code>```

Change to

```<code>module.exports = (sequelize, DataTypes) => {
    const User = sequelize.define('User', {
        email: {
            type: DataTypes.STRING,
            unique: true
        },
        password: DataTypes.STRING
    });
    return User;
}
</code>```

Title: Sequelize can not import a model

Body:
In expressJs project, I try to use sequelize to interact with database.

This is my model/user.js :

module.exports = (sequelize, DataTypes) => {
    sequelize.define('user', {
        email: {
            type: DataTypes.STRING,
            unique: true
        },
        password: DataTypes.STRING
    })
}

And this is models/index.js :

const fs = require('fs')
const path = require('path')
const Sequelize = require('sequelize')
const config = require('../config/config')
const db = {}

const sequelize = new Sequelize(
  config.db.database,
  config.db.user,
  config.db.password,
  config.db.options
)

fs
  .readdirSync(__dirname)
  .filter((file) =>
      file !== 'index.js'
  )
  .forEach((file) => {
    var a = path.join(__dirname, file);
    const model = sequelize.import(path.join(__dirname, file));
    db[model.name] = model;
  })

db.sequelize = sequelize
db.Sequelize = Sequelize

module.exports = db

The problem is in this line

const model = sequelize.import(path.join(__dirname, file));

Which returns undefine to model variable.

What did I miss here? I appreciate any hint?

Whole code on Github : here

Body:
Problem could be because of a missing return

module.exports = (sequelize, DataTypes) => {
    const User = sequelize.define('User', { // Missing return
        email: {
            type: DataTypes.STRING,
            unique: true
        },
        password: DataTypes.STRING
    })
}

Change to

module.exports = (sequelize, DataTypes) => {
    const User = sequelize.define('User', {
        email: {
            type: DataTypes.STRING,
            unique: true
        },
        password: DataTypes.STRING
    });
    return User;
}


问:
d3plus: how to flip order of drawn boxplots?
I am using this code for a d3 viz (Box Plot and Whiskers):

```<code>var ODGCostsChart = d3plus.viz()
    .container("#my_viz")
    .data(dataNoMinMax)
    .type("box")
    .id("measure")
    .x("provider")
    .y("deviation")
    .draw();
</code>```

where each row of my data is either:

```<code>{deviation: round(d.value,2), provider: 'This', measure: d.metric}
</code>```

or:

```<code>{deviation: round(d.value_others,2), provider: 'All', measure: d.metric}
</code>```

I would like the resulting visualization to have two boxplots side-by-side, one for "This" provider, and another for "All" providers right next to it. No matter how I try, though, I keep getting the boxplots with "All" preceding "This":

For the life of me I don't know how to flip the order of the boxplots in the drawing. I have gone through the documentation but I am not sure whether it's even possible.

答:
Eventually what did the trick was:

.order({"value": "provider"})

even though I don't see how "This" got ordered before "All"

Body:
I am using this code for a d3 viz (Box Plot and Whiskers):

var ODGCostsChart = d3plus.viz()
    .container("#my_viz")
    .data(dataNoMinMax)
    .type("box")
    .id("measure")
    .x("provider")
    .y("deviation")
    .draw();

where each row of my data is either:

{deviation: round(d.value,2), provider: 'This', measure: d.metric}

or:

{deviation: round(d.value_others,2), provider: 'All', measure: d.metric}

I would like the resulting visualization to have two boxplots side-by-side, one for "This" provider, and another for "All" providers right next to it. No matter how I try, though, I keep getting the boxplots with "All" preceding "This":

For the life of me I don't know how to flip the order of the boxplots in the drawing. I have gone through the documentation but I am not sure whether it's even possible.


问:
Responsive aspect ratios with pure css: how to fill container's height?
I have a div (the one with class container) with fixed height (which is supposed to be dynamic and not known in advance) which contains another div (the one with class fixed-aspect-ratio).

I would like the inner div to fill the container's height while keeping a fixed aspect ratio of 1:1.

The commonly used trick to achieve fixed aspect ratios is to exploit padding: in fact when declaring percentages instead of fixed values for padding, the percentage is calculated based on the WIDTH of the element in question, even if we are declaring a vertical value such as padding-top or padding-bottom.

This makes padding a great trick to exploit if you want to fill the container's WIDTH, but not if you want to fill the container's HEIGHT.

Is it possibile to achieve it using CSS only? No javascript thanks.

Ideally I would love to have CSS units complementary to the viewport ones, but relative to the container. Something like:

cw (container width)

ch (container height)

cmin (container min)

cmax (container max)

Would be freaking awesome.

<!DOCTYPE html>

Some text

```

https://www.w3schools.com/code/tryit.asp?filename=FLJBS4J2MTWS

答:
There is no similar CSS solution for height, as the padding-bottom for width.

Besides script, here is a this trick I have used, where I place an img, with a data url SVG (could be a Base64 png as well) to avoid an extra roundtrip to the server, having a square size.

By setting its height to 100%, it will keep its parent, being inline block, a square, and with visibility: hidden hide it.

Stack snippet

.container {
  background-color: green;
  height: 50vh;
}

.fixed-aspect-ratio {
  display: inline-block;
  background-color: red;
  height: 100%;
  position: relative;
}

.fixed-aspect-ratio img {
  display: block;
  height: 100%;
  visibility: hidden;
}

.text {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="fixed-aspect-ratio">
    <img src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><rect width='10' height='10'/></svg>">
    <div class="text">Some text</div>
    <!-- If you want text inside the container -->
  </div>
</div></code>```

Body:
I have a div (the one with class container) with fixed height (which is supposed to be dynamic and not known in advance) which contains another div (the one with class fixed-aspect-ratio).

I would like the inner div to fill the container's height while keeping a fixed aspect ratio of 1:1.

The commonly used trick to achieve fixed aspect ratios is to exploit padding: in fact when declaring percentages instead of fixed values for padding, the percentage is calculated based on the WIDTH of the element in question, even if we are declaring a vertical value such as padding-top or padding-bottom.

This makes padding a great trick to exploit if you want to fill the container's WIDTH, but not if you want to fill the container's HEIGHT.

Is it possibile to achieve it using CSS only? No javascript thanks.

Ideally I would love to have CSS units complementary to the viewport ones, but relative to the container. Something like:

cw (container width)

ch (container height)

cmin (container min)

cmax (container max)

Would be freaking awesome.

<!DOCTYPE html>

Some text

https://www.w3schools.com/code/tryit.asp?filename=FLJBS4J2MTWS

Body:
There is no similar CSS solution for height, as the padding-bottom for width.

Besides script, here is a this trick I have used, where I place an img, with a data url SVG (could be a Base64 png as well) to avoid an extra roundtrip to the server, having a square size.

By setting its height to 100%, it will keep its parent, being inline block, a square, and with visibility: hidden hide it.

Stack snippet

.container {
  background-color: green;
  height: 50vh;
}

.fixed-aspect-ratio {
  display: inline-block;
  background-color: red;
  height: 100%;
  position: relative;
}

.fixed-aspect-ratio img {
  display: block;
  height: 100%;
  visibility: hidden;
}

.text {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}

<div class="container">
  <div class="fixed-aspect-ratio">
    <img src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><rect width='10' height='10'/></svg>">
    <div class="text">Some text</div>
    <!-- If you want text inside the container -->
  </div>
</div>


问:
How to update Xcode from command line
I am trying to update Xcode from the command line.  Initially I tried running:

```<code> xcode-select --install
</code>```

which resulted in this message:

```<code>xcode-select: error: command line tools are already installed, use "Software Update" to install updates
</code>```

So the question remains, is there a way to update Xcode from the command line?

答:
I got this error after deleting Xcode. I fixed it by resetting the command line tools path with sudo xcode-select -r.

Before:

```<code>navin@Radiant ~$ /usr/bin/clang
xcrun: error: active developer path ("/Applications/Xcode.app/Contents/Developer") does not exist
Use `sudo xcode-select --switch path/to/Xcode.app` to specify the Xcode that you wish to use for command line developer tools, or use `xcode-select --install` to install the standalone command line developer tools.
See `man xcode-select` for more details.

navin@Radiant ~$ xcode-select --install
xcode-select: error: command line tools are already installed, use "Software Update" to install updates
</code>```

After:

```<code>navin@Radiant ~$ /usr/bin/clang
clang: error: no input files
</code>```

Title: How to update Xcode from command line

Body:
I am trying to update Xcode from the command line.  Initially I tried running:

 xcode-select --install

which resulted in this message:

xcode-select: error: command line tools are already installed, use "Software Update" to install updates

So the question remains, is there a way to update Xcode from the command line?

Body:
I got this error after deleting Xcode. I fixed it by resetting the command line tools path with sudo xcode-select -r.

Before:

navin@Radiant ~$ /usr/bin/clang
xcrun: error: active developer path ("/Applications/Xcode.app/Contents/Developer") does not exist
Use `sudo xcode-select --switch path/to/Xcode.app` to specify the Xcode that you wish to use for command line developer tools, or use `xcode-select --install` to install the standalone command line developer tools.
See `man xcode-select` for more details.

navin@Radiant ~$ xcode-select --install
xcode-select: error: command line tools are already installed, use "Software Update" to install updates

After:

navin@Radiant ~$ /usr/bin/clang
clang: error: no input files


问:
Removing first 3 characters of file names in linux
I need a sh script to do remove the first 3 characters of file names, for example:

```<code>"AB file 1.pdf"
"BC file 2.pdf"
"DB file 3.pdf"
"AD file 4.pdf"
...
</code>```

to:

```<code>"file 1.pdf"
"file 2.pdf"
"file 3.pdf"
"file 4.pdf"
...
</code>```

I think the script will be like:

```<code>#!/bin/sh
for i in *.pdf; do
   newName= ????
   mv $i $newName
done
</code>```

答:
Use the cut command:

```<code>newName=$(echo "$i" | cut -c4-)
</code>```

In bash you can use a Parameter Expansion extension:

```<code>newName=${i:3}
</code>```

Also, don't forget to quote your variables:

```<code>mv "$i" "$newName"
</code>```

Otherwise it will think you're trying to move the files named AB, file, and 1.pdf to a directory named 1.pdf.

You could also install the rename command if you don't already have it:

```<code>rename 's/^...//' *.pdf
</code>```

Body:
I need a sh script to do remove the first 3 characters of file names, for example:

"AB file 1.pdf"
"BC file 2.pdf"
"DB file 3.pdf"
"AD file 4.pdf"
...

to:

"file 1.pdf"
"file 2.pdf"
"file 3.pdf"
"file 4.pdf"
...

I think the script will be like:

#!/bin/sh
for i in *.pdf; do
   newName= ????
   mv $i $newName
done

Body:
Use the cut command:

newName=$(echo "$i" | cut -c4-)

In bash you can use a Parameter Expansion extension:

newName=${i:3}

Also, don't forget to quote your variables:

mv "$i" "$newName"

Otherwise it will think you're trying to move the files named AB, file, and 1.pdf to a directory named 1.pdf.

You could also install the rename command if you don't already have it:

rename 's/^...//' *.pdf


问:
How to pass a command which contains special characters through SSH?
I would like to run the following command from Jenkins:

```<code>ssh -i ~/.ssh/company.pem -o StrictHostKeyChecking=no user@$hostname "supervisorctl start company-$app ;  awk -v app=$app '$0 ~ "program:company-"app  {p=NR} p && NR==p+6 && /^autostart/ {$0="autostart=true" ; p=0} 1' /etc/supervisord.conf > $$.tmp && sudo mv $$.tmp /etc/supervisord.conf”
</code>```

This is one of the last steps of a job which creates a CloudFormation stack.

Running the command from the target server's terminal works properly.

In this step, I'd like to ssh to each one of the servers (members of ASG's within the new stack) and search and replace a specific line as shown above in the /etc/supervisord.conf, basically setting one specific service to autostart.

When I run the command I get the following error:

```<code>Usage: awk [POSIX or GNU style options] -f progfile [--] file ...
Usage: awk [POSIX or GNU style options] [--] 'program' file ...
</code>```

I've tried escaping the double quotes but got the same error, any idea what I'm doing wrong?

答:
You are running in to this issue due to the way the shell handles nested quotes. This is a use case for a HERE DOCUMENT or heredoc - A HERE DOCUMENT allows you to write multi-line commands passed through bash without worrying about quotes. The structure is as follows:

```<code>$ ssh -t user@server.com <<'END'
command |\
command2 |\
END
</code>```

<--- Oh yeah, the -t is important to the ssh command as it lets the shell know to behave as if being used interactively, and will avoid warnings and unexpected results.

In your specific case, you should try something like:

```<code>$ ssh -t -i ~/.ssh/company.pem -o StrictHostKeyChecking=no user@$hostname <<'END'
supervisorctl start company-$app |\
awk -v app=$app '$0 ~ \"program:company-\"app  {p=NR} p && NR==p+6 \
&& /^autostart/ {$0="autostart=true" ; p=0} 1' \
/etc/supervisord.conf > $$.tmp && sudo mv $$.tmp /etc/supervisord.conf
END
</code>```

Just a note, since I can't be sure about your desired output of the command you are running, be advised to keep track of your own " and ' marks, and to escape them accordingly in your awk command as you would at an interactive terminal. I notice the "'s around program:company and I am confused a bit by them If they are a part of the pattern in the string being searched they will need to be escaped accordingly.  P.S.

Body:
I would like to run the following command from Jenkins:

ssh -i ~/.ssh/company.pem -o StrictHostKeyChecking=no user@$hostname "supervisorctl start company-$app ;  awk -v app=$app '$0 ~ "program:company-"app  {p=NR} p && NR==p+6 && /^autostart/ {$0="autostart=true" ; p=0} 1' /etc/supervisord.conf > $$.tmp && sudo mv $$.tmp /etc/supervisord.conf”

This is one of the last steps of a job which creates a CloudFormation stack.

Running the command from the target server's terminal works properly.

In this step, I'd like to ssh to each one of the servers (members of ASG's within the new stack) and search and replace a specific line as shown above in the /etc/supervisord.conf, basically setting one specific service to autostart.

When I run the command I get the following error:

Usage: awk [POSIX or GNU style options] -f progfile [--] file ...
Usage: awk [POSIX or GNU style options] [--] 'program' file ...

I've tried escaping the double quotes but got the same error, any idea what I'm doing wrong?

Body:
You are running in to this issue due to the way the shell handles nested quotes. This is a use case for a HERE DOCUMENT or heredoc - A HERE DOCUMENT allows you to write multi-line commands passed through bash without worrying about quotes. The structure is as follows:

$ ssh -t user@server.com <<'END'
command |\
command2 |\
END

<--- Oh yeah, the -t is important to the ssh command as it lets the shell know to behave as if being used interactively, and will avoid warnings and unexpected results.

In your specific case, you should try something like:

$ ssh -t -i ~/.ssh/company.pem -o StrictHostKeyChecking=no user@$hostname <<'END'
supervisorctl start company-$app |\
awk -v app=$app '$0 ~ \"program:company-\"app  {p=NR} p && NR==p+6 \
&& /^autostart/ {$0="autostart=true" ; p=0} 1' \
/etc/supervisord.conf > $$.tmp && sudo mv $$.tmp /etc/supervisord.conf
END

Just a note, since I can't be sure about your desired output of the command you are running, be advised to keep track of your own " and ' marks, and to escape them accordingly in your awk command as you would at an interactive terminal. I notice the "'s around program:company and I am confused a bit by them If they are a part of the pattern in the string being searched they will need to be escaped accordingly.  P.S.


问:
How to call a function a certain time after a web service has been called?
How to call a function a certain time after a web service has been called?

I need to check if a request has been accepted 30s after the request has been created, something like that:

```<code>public function create_request(Request $request)
{
    $user_id = $request->id;

    $validator = Validator::make(
        $request->all(),
        array(
            'request_id' => 'required|numeric|exists:requests,id,user_id,' . $user_id,
        ));

    // Create Request
    $requests = new Requests;
    $requests->user_id = $user_id;

    if ($request->service_type)
        $requests->request_type = $request->service_type;

    $requests->status = REQUEST_NEW;
    $requests->confirmed_provider = $request->provider_id;
    $requests->request_start_time = date("Y-m-d H:i:s");
    $requests->s_address = $request->s_address ? $request->s_address : "";

    if ($request->s_latitude) {
        $requests->s_latitude = $request->s_latitude;
    }
    if ($request->s_longitude) {
        $requests->s_longitude = $request->s_longitude;
    }

    $requests->save();

    sleep(30);

    $request = Requests::where('id', '=', $request->request_id)->first();

    if ($request['provider_status'] == 0) {
        Requests::where('id', '=', $request['id'])->delete();
        $response_array = array('success' => true , 'message' => Helper::get_message(121));
    } else {
        $response_array = array('success' => false, 'error' => Helper::get_error_message(161), 'error_code' => 132);
    }

    return response()->json($response_array, 200);

}
</code>```

The problem with this approach is that the sleep function (sleep(30);) is causing the web service response (return response()->json($response_array, 200);) to be delayed too.

I was expecting something similar to setTimeout(function(){ alert("Hello"); }, 30000); in Javascript

答:
Set a session variable at start with value "set" or something.

from start of function down to sleep(30) have a if(variable == "set")

Then at the point you have sleep(30), replace with else that way it will not check if it's set.

Then use meta header to reload the page after 30 seconds, if the session variable is "set" change it to "check".

This way first time it will set, then next time it will check.

Body:
How to call a function a certain time after a web service has been called?

I need to check if a request has been accepted 30s after the request has been created, something like that:

public function create_request(Request $request)
{
    $user_id = $request->id;

    $validator = Validator::make(
        $request->all(),
        array(
            'request_id' => 'required|numeric|exists:requests,id,user_id,' . $user_id,
        ));

    // Create Request
    $requests = new Requests;
    $requests->user_id = $user_id;

    if ($request->service_type)
        $requests->request_type = $request->service_type;

    $requests->status = REQUEST_NEW;
    $requests->confirmed_provider = $request->provider_id;
    $requests->request_start_time = date("Y-m-d H:i:s");
    $requests->s_address = $request->s_address ? $request->s_address : "";

    if ($request->s_latitude) {
        $requests->s_latitude = $request->s_latitude;
    }
    if ($request->s_longitude) {
        $requests->s_longitude = $request->s_longitude;
    }

    $requests->save();

    sleep(30);

    $request = Requests::where('id', '=', $request->request_id)->first();

    if ($request['provider_status'] == 0) {
        Requests::where('id', '=', $request['id'])->delete();
        $response_array = array('success' => true , 'message' => Helper::get_message(121));
    } else {
        $response_array = array('success' => false, 'error' => Helper::get_error_message(161), 'error_code' => 132);
    }

    return response()->json($response_array, 200);

}

The problem with this approach is that the sleep function (sleep(30);) is causing the web service response (return response()->json($response_array, 200);) to be delayed too.

I was expecting something similar to setTimeout(function(){ alert("Hello"); }, 30000); in Javascript


问:
Python 2.7 equivalent of importlib.machinery.EXTENSION_SUFFIXES
I want to use importlib.machinery.EXTENSION_SUFFIXES from Python 3 but am unfortunately using Python 2.7.

EXTENSION_SUFFIXES evaluates to ['.cpython-34m-x86_64-linux-gnu.so', '.cpython-34m.so', '.abi3.so', '.so'], but this is specific to my machine and possibly python version, so I cannot simply hardcode the list.

Here's where EXTENSION_SUFFIXES is built in Python 3's source: https://github.com/python/cpython/blob/3.6/Lib/importlib/_bootstrap_external.py#L1431.  However it seems to go down into the C implementation (link), so it's unclear to me how I can get this info.

How can I obtain this list in Python 2.7?

答:
Use imp.get_suffixes() instead:

Return a list of 3-element tuples, each describing a particular type of module. Each triple has the form (suffix, mode, type), where suffix is a string to be appended to the module name to form the filename to search for, mode is the mode string to pass to the built-in open() function to open the file (this can be 'r' for text files or 'rb' for binary files), and type is the file type, which has one of the values PY_SOURCE, PY_COMPILED, or C_EXTENSION, described below.

Thus, to filter this into a list of suffixes for C extension modules:

```<code>import imp
extension_suffixes = [suffix for (suffix, mode, type) in imp.get_suffixes()
                             if type == imp.C_EXTENSION]
</code>```

This also works in Python 3, although imp is deprecated in Python 3.

Body:
Use imp.get_suffixes() instead:

Return a list of 3-element tuples, each describing a particular type of module. Each triple has the form (suffix, mode, type), where suffix is a string to be appended to the module name to form the filename to search for, mode is the mode string to pass to the built-in open() function to open the file (this can be 'r' for text files or 'rb' for binary files), and type is the file type, which has one of the values PY_SOURCE, PY_COMPILED, or C_EXTENSION, described below.

Thus, to filter this into a list of suffixes for C extension modules:

import imp
extension_suffixes = [suffix for (suffix, mode, type) in imp.get_suffixes()
                             if type == imp.C_EXTENSION]

This also works in Python 3, although imp is deprecated in Python 3.


问:
How to return a JSON to ajax in yii2
I want to do a web project using Yii2, and I want to return a JSON to AJAX. I have used json_encode() and Yii::$app->response->format = Response::FORMAT_JSON;, but it still doesn't work.

Here is my action:

```<code>public function actionAbout(){
  Yii::$app->response->format = Response::FORMAT_JSON;
  return json_encode(["test"=> 1]);
}
</code>```

Here is my AJAX:

```<code>$.ajax({
  type: "POST",
  // dataType: 'json',
  data: {
    'user': 'A'
  },
  url: "?site/about",
  contentType: "application/json",
  success: function(data) {
    console.log(typeof(data));
    console.log(data)
  },
  error: function (data) {
    console.log(data);
  },
});
</code>```

But it returns this:

```<code><!DOCTYPE html>....
</code>```

still a html. How to solve it?

答:
Instead of using

return json_encode(["test"=> 1]);

shouldn't you be echoing it like this

echo json_encode(["test"=> 1]);

plus if you ARE setting the Yii::$app->response->format to FORMAT_JSON then you do not need to encode the array to JSON just return the array.

```<code>return ['test'=>1];
</code>```

Title: How to return a JSON to ajax in yii2

Body:
I want to do a web project using Yii2, and I want to return a JSON to AJAX. I have used json_encode() and Yii::$app->response->format = Response::FORMAT_JSON;, but it still doesn't work.

Here is my action:

public function actionAbout(){
  Yii::$app->response->format = Response::FORMAT_JSON;
  return json_encode(["test"=> 1]);
}

Here is my AJAX:

$.ajax({
  type: "POST",
  // dataType: 'json',
  data: {
    'user': 'A'
  },
  url: "?site/about",
  contentType: "application/json",
  success: function(data) {
    console.log(typeof(data));
    console.log(data)
  },
  error: function (data) {
    console.log(data);
  },
});

But it returns this:

<!DOCTYPE html>....

still a html. How to solve it?

Body:
Instead of using

return json_encode(["test"=> 1]);

shouldn't you be echoing it like this

echo json_encode(["test"=> 1]);

plus if you ARE setting the Yii::$app->response->format to FORMAT_JSON then you do not need to encode the array to JSON just return the array.

return ['test'=>1];


问:
Variable assignment using dynamic object restructuring
I have a local state object that looks will look like this:

```<code>state:{
   pickup:{
      blah: stuff
    }
}
</code>```

OR

```<code>state:{
   dropoff:{
      blah: stuff
    }
}
</code>```

What I am trying to do is grab either the pickup or dropoff object and set it to some other variable.

This is being done in a function that is passing in whichever type we are attempting to pull off.

tl;dr How can I do something like const location = this.state.[locationType] where locationType is passed into my function.

答:
Following @Nick Tower's comment,

const location = this.state[locationType]

produced the desired result.

Body:
I have a local state object that looks will look like this:

state:{
   pickup:{
      blah: stuff
    }
}

OR

state:{
   dropoff:{
      blah: stuff
    }
}

What I am trying to do is grab either the pickup or dropoff object and set it to some other variable.

This is being done in a function that is passing in whichever type we are attempting to pull off.

tl;dr How can I do something like const location = this.state.[locationType] where locationType is passed into my function.


问:
Passing a char array to int array via a method using Integer.parseInt, and
Thank you in advanced for your help. I am still a beginner java student and I realize there are similar questions, but none specifically answer the question at my level. Essentially a user inputs a long number that requires I treat it like a string, and then turn it into an array. The assignment specifically states, "The .parseInt() method and the Integer class can be your friend in this assignment" I've read and searched through my textbook, scoured the internet, and have not been able to find anything helpful. How can I create an integer array from the string described above? When I call the method later I receive an error.
Below is what I have so far. If you could direct me to a question I have not seen that's fine, but it would really help if someone could answer my question and correct my logic.
Thanks again!

**I did turn the string into a char array, but it's not necessary. If I need to change it I can.

```<code>public int [] ctCd(char [] cardArray){
    int [] creditCard = new int [cardArray.length];
    for (int i=0; i <= 15; i++){
        int newNum = Integer.parseInt(cardArray[i]);
        creditCard [i] = newNum;
    }
    return creditCard;
}
</code>```

答:
The problem you are running into is that .parseInt() takes in a String argument, not a char argument. In your code, you are trying to pass in a char, which is why you are getting an error. You simply have to convert the char object to a String object, which would look like this:</p>

```<code>int newNum = Integer.parseInt(String.valueOf(cardArray[i]));
</code>```

Body:
Thank you in advanced for your help. I am still a beginner java student and I realize there are similar questions, but none specifically answer the question at my level. Essentially a user inputs a long number that requires I treat it like a string, and then turn it into an array. The assignment specifically states, "The .parseInt() method and the Integer class can be your friend in this assignment" I've read and searched through my textbook, scoured the internet, and have not been able to find anything helpful. How can I create an integer array from the string described above? When I call the method later I receive an error.
Below is what I have so far. If you could direct me to a question I have not seen that's fine, but it would really help if someone could answer my question and correct my logic.
Thanks again!

**I did turn the string into a char array, but it's not necessary. If I need to change it I can.

public int [] ctCd(char [] cardArray){
    int [] creditCard = new int [cardArray.length];
    for (int i=0; i <= 15; i++){
        int newNum = Integer.parseInt(cardArray[i]);
        creditCard [i] = newNum;
    }
    return creditCard;
}

Body:
The problem you are running into is that .parseInt() takes in a String argument, not a char argument. In your code, you are trying to pass in a char, which is why you are getting an error. You simply have to convert the char object to a String object, which would look like this:

int newNum = Integer.parseInt(String.valueOf(cardArray[i]));


问:
Creating CoreData Relationship causes 20+ Errors in code
So I have been working for the past couple of weeks trying to use relationships in order to have an array of object ingredient to an individual class of recipe. I've been watching this video.  Now, By creating two extensions of recipe and ingredient classes, I'm getting a ton of errors all in my code, specifically saying

invalid use of (class structure)

or

ambiguous use of (class structure)

I have a Git Repo on GitHub that you can diagnose my code here if that is preferable.

If not, here are the extensions that I've made

Recipe Class:

```<code>import Foundation
import CoreData

extension Recipe {

@nonobjc public class func fetchRequest() -> NSFetchRequest<Recipe> {
    return NSFetchRequest<Recipe>(entityName: "Recipe")
}

@NSManaged public var ingredients: String?
@NSManaged public var instructions: String?
@NSManaged public var time: String?
@NSManaged public var title: String?
@NSManaged public var ingredient: [Ingredient]?

}

// MARK: Generated accessors for ingredient
extension Recipe {

@objc(addIngredientObject:)
@NSManaged public func addToIngredient(_ value: Ingredient)

@objc(removeIngredientObject:)
@NSManaged public func removeFromIngredient(_ value: Ingredient)

@objc(addIngredient:)
@NSManaged public func addToIngredient(_ values: NSSet)

@objc(removeIngredient:)
@NSManaged public func removeFromIngredient(_ values: NSSet)

}
</code>```

And the ingredient class:

```<code>import Foundation
import CoreData

extension Ingredient {

@nonobjc public class func fetchRequest() -> NSFetchRequest<Ingredient>{
    return NSFetchRequest<Ingredient>(entityName: "Ingredient")
}

@NSManaged public var cost: Double
@NSManaged public var name: String?
@NSManaged public var unit: String?
@NSManaged public var recipe: NSSet?

}

// MARK: Generated accessors for recipe
extension Ingredient {

@objc(addRecipeObject:)
@NSManaged public func addToRecipe(_ value: Recipe)

@objc(removeRecipeObject:)
@NSManaged public func removeFromRecipe(_ value: Recipe)

@objc(addRecipe:)
@NSManaged public func addToRecipe(_ values: NSSet)

@objc(removeRecipe:)
@NSManaged public func removeFromRecipe(_ values: NSSet)

}
</code>```

答:
You have to decide if you want to manage your CoreData class files by yourself or if you want Xcode to manage them for you. Even though you tell Xcode to manage them for you have created Recipe+CoreDataClass.swift and Ingredient+CoreDataClass.swift. That is also why you get this error:

```<code> Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
</code>```

This error tells you that there are several classes with the same name.

So either you delete your Recipe and Ingredient extension and let Xcode manage them for you or you create them by yourself but properly. If you want to do so follow these steps: https://stackoverflow.com/a/40868074/5464989

After I created these files manually your app seemed to work.

Body:
So I have been working for the past couple of weeks trying to use relationships in order to have an array of object ingredient to an individual class of recipe. I've been watching this video.  Now, By creating two extensions of recipe and ingredient classes, I'm getting a ton of errors all in my code, specifically saying

invalid use of (class structure)

or

ambiguous use of (class structure)

I have a Git Repo on GitHub that you can diagnose my code here if that is preferable.

If not, here are the extensions that I've made

Recipe Class:

import Foundation
import CoreData

extension Recipe {

@nonobjc public class func fetchRequest() -> NSFetchRequest<Recipe> {
    return NSFetchRequest<Recipe>(entityName: "Recipe")
}

@NSManaged public var ingredients: String?
@NSManaged public var instructions: String?
@NSManaged public var time: String?
@NSManaged public var title: String?
@NSManaged public var ingredient: [Ingredient]?

}

// MARK: Generated accessors for ingredient
extension Recipe {

@objc(addIngredientObject:)
@NSManaged public func addToIngredient(_ value: Ingredient)

@objc(removeIngredientObject:)
@NSManaged public func removeFromIngredient(_ value: Ingredient)

@objc(addIngredient:)
@NSManaged public func addToIngredient(_ values: NSSet)

@objc(removeIngredient:)
@NSManaged public func removeFromIngredient(_ values: NSSet)

}

And the ingredient class:

import Foundation
import CoreData

extension Ingredient {

@nonobjc public class func fetchRequest() -> NSFetchRequest<Ingredient>{
    return NSFetchRequest<Ingredient>(entityName: "Ingredient")
}

@NSManaged public var cost: Double
@NSManaged public var name: String?
@NSManaged public var unit: String?
@NSManaged public var recipe: NSSet?

}

// MARK: Generated accessors for recipe
extension Ingredient {

@objc(addRecipeObject:)
@NSManaged public func addToRecipe(_ value: Recipe)

@objc(removeRecipeObject:)
@NSManaged public func removeFromRecipe(_ value: Recipe)

@objc(addRecipe:)
@NSManaged public func addToRecipe(_ values: NSSet)

@objc(removeRecipe:)
@NSManaged public func removeFromRecipe(_ values: NSSet)

}

Body:
You have to decide if you want to manage your CoreData class files by yourself or if you want Xcode to manage them for you. Even though you tell Xcode to manage them for you have created Recipe+CoreDataClass.swift and Ingredient+CoreDataClass.swift. That is also why you get this error:

 Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1

This error tells you that there are several classes with the same name.

So either you delete your Recipe and Ingredient extension and let Xcode manage them for you or you create them by yourself but properly. If you want to do so follow these steps: https://stackoverflow.com/a/40868074/5464989

After I created these files manually your app seemed to work.


问:
Wrong syntax highlighting for PHP file in PHPStorm
I don't know what happened but syntax highlighting for one php file stopped to working and also icon next to the file has changed. It shows it's text file instead of PHP .

How can I fix that ?

答:
This question is old but I answer for someone that couldn't solve this:

You may have removed one of the PHP start(<?php) or end (?>) tags and is therefore displayed in plain text


问:
Get focus on a tab of jquery UI tabs
I would like to give focus on the tab with the href tabs_11 :

```<code><div id="tabs">

            <!-- PB :: MENU_PRINCIPAL_________________________________________________-->
            <ul>
                <!--<li><a href="#tabs_2-1">Mes données personnelles</a></li>-->
                <li><a href="#tabs_2-4">Mes stagiaires</a></li>
                <li><a href="#tabs_2-2">Formulaire d'évaluation</a></li>

                <!--<li><a href="#tabs_2-3">Mon calendrier</a></li>-->
                <li><a href="#tabs-1">Personnel</a></li>

                <li><a href="#tabs-6">Documentation</a></li>
                <!--<li><a href="#tabs-7">Equipement IT</a></li>-->
                <li><a href="#tabs-8">Motivation</a></li>
                <li><a href="#tabs_9">Mon calendrier</a></li>
                <li><a href="#tabs_10">Documents utiles & FAQ</a></li>
                <li><a href="#tabs_11">Renouveler mon agrément</a></li>

            </ul>

            <?php
        if(isset($_SESSION['en_attente']) && isset($_SESSION['soumis']))
        {
                ?>
                  <script>

                        alert("Message");

                        $('#tabs_11').tabs(
                        {
                                active: index
                        });

                 </script>

        <?php
        }
?>
</code>```

This code does not allow me to select the tab with the href #tabs_11

I tried everything, no success...

答:
```<code>   $('#tabs_11').tabs(
</code>```

In jQuery # means element ID, it's not the same as a # in a URL string. Give your li/a element an ID, or access it based on a different property, like href for example:

```<code>$( "a[href='#tabs_11']" ).closest("li"); // if you need to target the li element
$( "a[href='#tabs_11']" ) // if you dont
</code>```

Title: Get focus on a tab of jquery UI tabs

Body:
I would like to give focus on the tab with the href tabs_11 :

Mes stagiaires

Formulaire d'évaluation

Personnel

Documentation

Motivation

Mon calendrier

Documents utiles & FAQ

Renouveler mon agrément

            <?php
        if(isset($_SESSION['en_attente']) && isset($_SESSION['soumis']))
        {
                ?>

        <?php
        }
?>

This code does not allow me to select the tab with the href #tabs_11

I tried everything, no success...

Body:
   $('#tabs_11').tabs(

In jQuery # means element ID, it's not the same as a # in a URL string. Give your li/a element an ID, or access it based on a different property, like href for example:

$( "a[href='#tabs_11']" ).closest("li"); // if you need to target the li element
$( "a[href='#tabs_11']" ) // if you dont


问:
IONIC2/Angular2 ngOnChange doesn't work
I'm new to Angular2 and I've been struggling for a while with this problem and have found no solution to it online.

[on ionic2!]

I want to use ngOnChanges() so i can detect changes to zonaid:

estados.html:

```<code><ion-item>
       <ion-label color="branco">Zonas</ion-label>

              <ion-select *ngIf="isTrue2" [(ngModel)]=zonaid>
                 <ion-option value={{bicho.zonas}} *ngFor="let bicho of idespecie">
                    {{bicho.zonas}}
                 </ion-option>
             </ion-select>

              <ion-select *ngIf="!isTrue2" [(ngModel)]="zonaid">
                 <ion-option value={{item.id}} *ngFor="let item of itemsZon" >
                    {{item.codigo}}
                 </ion-option>

              </ion-select>
     </ion-item>
</code>```

idespecie and itemsZon are parts of .json files

estados.ts

```<code>import { Component, Input, SimpleChanges, OnChanges } from '@angular/core';
import { NavController } from 'ionic-angular';
import { IpmaBivService} from '../../app/services/ipmabiv.service'
import { Http } from '@angular/http';

@Component({
  selector: 'page-estados',
  templateUrl: 'estados.html'
})
export class EstadosPage {
   itemsZon: any;
   itemsEsp: any;
   zonaEscolhida: any;

   @Input()
   zonaid: string;

   idzona: '';
   idespecie: any[];

   isTrue1:boolean = false;
   isTrue2:boolean = false;
   constructor(public navCtrl: NavController, private ipmaBivService:IpmaBivService) {
  }
  ngOnChanges(changes: SimpleChanges){
     console.log('ngOnChanges ran');
     if(this.zonaid != ''){
        this.isTrue1 = true;
        this.getJsonZonas(this.zonaid);
     }
     if(this.especie != ''){
        this.isTrue2 = true;
        this.getJsonEspecies(this.especie);
     }
 }

}
  ngOnInit(){
     this.getDataZonas('zonas')
     this.getDataEspecies('especies')
   //   this.getData('especies')
 }
 }
</code>```

app.module.ts

```<code>    import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { HttpModule, JsonpModule } from '@angular/http';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';
import { EstadosPage } from '../pages/estados/estados';
import { OutrosPage } from '../pages/estados/outros';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    ListPage,
    EstadosPage,
    OutrosPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    HttpModule,
    JsonpModule
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    ListPage,
    OutrosPage,
    EstadosPage

  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}
</code>```

Everything is happening in the same component (ionic page).

My goal is just to be able to run a method whenever zonaid changes. If you think there is a better way than goin through ngOnChanges, pls let me know

Thanks!

答:
First, remember to always add qoutes, change [(ngModel)]=zonaid to [(ngModel)]="zonaid"

Anyway, as an answer try this:

Change <ion-select *ngIf="isTrue2" [(ngModel)]=zonaid>

to

<ion-select *ngIf="isTrue2" [ngModel]="zonaid"
 (ngModelChange)="runYourFunction($event)">

Remember to create a public runYourFunction(event) {} in your code.

With this you'll be data binding from the component to the view, and whenever the view changes, you'll run the function runYourFunction.

Hope that helps

Title: IONIC2/Angular2 ngOnChange doesn't work

Body:
I'm new to Angular2 and I've been struggling for a while with this problem and have found no solution to it online.

[on ionic2!]

I want to use ngOnChanges() so i can detect changes to zonaid:

estados.html:

<ion-item>
       <ion-label color="branco">Zonas</ion-label>

              <ion-select *ngIf="isTrue2" [(ngModel)]=zonaid>
                 <ion-option value={{bicho.zonas}} *ngFor="let bicho of idespecie">
                    {{bicho.zonas}}
                 </ion-option>
             </ion-select>

              <ion-select *ngIf="!isTrue2" [(ngModel)]="zonaid">
                 <ion-option value={{item.id}} *ngFor="let item of itemsZon" >
                    {{item.codigo}}
                 </ion-option>

              </ion-select>
     </ion-item>

idespecie and itemsZon are parts of .json files

estados.ts

import { Component, Input, SimpleChanges, OnChanges } from '@angular/core';
import { NavController } from 'ionic-angular';
import { IpmaBivService} from '../../app/services/ipmabiv.service'
import { Http } from '@angular/http';

@Component({
  selector: 'page-estados',
  templateUrl: 'estados.html'
})
export class EstadosPage {
   itemsZon: any;
   itemsEsp: any;
   zonaEscolhida: any;

   @Input()
   zonaid: string;

   idzona: '';
   idespecie: any[];

   isTrue1:boolean = false;
   isTrue2:boolean = false;
   constructor(public navCtrl: NavController, private ipmaBivService:IpmaBivService) {
  }
  ngOnChanges(changes: SimpleChanges){
     console.log('ngOnChanges ran');
     if(this.zonaid != ''){
        this.isTrue1 = true;
        this.getJsonZonas(this.zonaid);
     }
     if(this.especie != ''){
        this.isTrue2 = true;
        this.getJsonEspecies(this.especie);
     }
 }

}
  ngOnInit(){
     this.getDataZonas('zonas')
     this.getDataEspecies('especies')
   //   this.getData('especies')
 }
 }

app.module.ts

    import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { HttpModule, JsonpModule } from '@angular/http';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';
import { EstadosPage } from '../pages/estados/estados';
import { OutrosPage } from '../pages/estados/outros';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    ListPage,
    EstadosPage,
    OutrosPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    HttpModule,
    JsonpModule
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    ListPage,
    OutrosPage,
    EstadosPage

  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

Everything is happening in the same component (ionic page).

My goal is just to be able to run a method whenever zonaid changes. If you think there is a better way than goin through ngOnChanges, pls let me know

Thanks!


问:
Scope-resolution operator :: versus member-access operator . in C#
In C#, what's the difference between A::B and A.B? The only difference I've noticed is that only :: can be used with global, but other than that, what's the difference? Why do they both exist?

答:
with :: you can do things like...

```<code> extern alias X;
 extern alias Y;
 class Test
 {
   X::N.A a;
   X::N.B b1;
   Y::N.B b2;
   Y::N.C c;
 }
</code>```

and there are times when . is ambiguous so :: is needed.  here's the example from the C# language spec

```<code>namespace N
{
   public class A {}
   public class B {}
}
namespace N
{
   using A = System.IO;
   class X
   {
      A.Stream s1;         // Error, A is ambiguous
      A::Stream s2;        // Ok
   }
}
</code>```

http://download.microsoft.com/download/0/B/D/0BDA894F-2CCD-4C2C-B5A7-4EB1171962E5/CSharp%20Language%20Specification.htm

Body:
with :: you can do things like...

 extern alias X;
 extern alias Y;
 class Test
 {
   X::N.A a;
   X::N.B b1;
   Y::N.B b2;
   Y::N.C c;
 }

and there are times when . is ambiguous so :: is needed.  here's the example from the C# language spec

namespace N
{
   public class A {}
   public class B {}
}
namespace N
{
   using A = System.IO;
   class X
   {
      A.Stream s1;         // Error, A is ambiguous
      A::Stream s2;        // Ok
   }
}

http://download.microsoft.com/download/0/B/D/0BDA894F-2CCD-4C2C-B5A7-4EB1171962E5/CSharp%20Language%20Specification.htm


问:
Why does my .values() not work as intended
I've been trying to list loans out to the console using .values(), it works with the maps when listing out items or borrowers but for my loans, anyone know why?

```<code>public void listLoans(){
  System.out.println("Loans:");
  for (LoanTransaction t: loans.values()) {
      System.out.println(t);
  }
  System.out.println();
}
</code>```

Accessors

```<code>public Map<Integer, Borrower>  getBorrowers() { return borrowers; }
public Map<Integer, Item>      getItems()     { return items; }
public List<LoanTransaction> getLoans()       { return loans; }
</code>```

Example of Listing Items that works as intended

```<code>public void listItems() {
    System.out.println("Items:");
    for (Item i: items.values()) {
      System.out.println(i);
    }
    System.out.println();
  }
</code>```

答:
values() only works for maps, since maps are made of  pairs. loans is of type List, to get the elements in a list, you only need

```<code>for (LoanTransaction t: loans) {
      System.out.println(t);
  }
</code>```

Body:
I've been trying to list loans out to the console using .values(), it works with the maps when listing out items or borrowers but for my loans, anyone know why?

public void listLoans(){
  System.out.println("Loans:");
  for (LoanTransaction t: loans.values()) {
      System.out.println(t);
  }
  System.out.println();
}

Accessors

public Map<Integer, Borrower>  getBorrowers() { return borrowers; }
public Map<Integer, Item>      getItems()     { return items; }
public List<LoanTransaction> getLoans()       { return loans; }

Example of Listing Items that works as intended

public void listItems() {
    System.out.println("Items:");
    for (Item i: items.values()) {
      System.out.println(i);
    }
    System.out.println();
  }

Body:
values() only works for maps, since maps are made of  pairs. loans is of type List, to get the elements in a list, you only need

for (LoanTransaction t: loans) {
      System.out.println(t);
  }


问:
Getting correct counts from Pandas Groupby
I have a Pandas DataFrame with the following:

```<code>Name   | Attended
Smith  | Y
Smith  | Y
Smith  | N
Adams  | N
Adams  | Y
Morgan | Y
Morgan | Y
</code>```

and I'd like to count the number of Y's and Ns for each Name.
so the output would be:

```<code>Name  | Attended| Count
Smith | Y       | 2
      | N       | 1
Adams | Y       | 1
      | N       | 1
Morgan| Y       | 3
      | N       | 0
</code>```

I tried df.groupby(["Name","Attended"]).count() and variations of it, but for some reason I don't get the right output. I get either the Name and simply the count (Smith 3, Adam 2, Morgan 3) or the same dataframe again. Help! Am I grouping by incorrectly? I looked for awhile over similar questions and my code matches with the answers there.

I'm using Python 3 and jupyter notebook.

答:
Point out a column to count with

```<code>df.groupby(["Name ","Attended"])["Attended"].count().to_frame(name='Count')
Out[842]:
                   Count
Name     Attended
Adams    N             1
         Y             1
Morgan   Y             2
Smith    N             1
         Y             2
</code>```

Body:
I have a Pandas DataFrame with the following:

Name   | Attended
Smith  | Y
Smith  | Y
Smith  | N
Adams  | N
Adams  | Y
Morgan | Y
Morgan | Y

and I'd like to count the number of Y's and Ns for each Name.
so the output would be:

Name  | Attended| Count
Smith | Y       | 2
      | N       | 1
Adams | Y       | 1
      | N       | 1
Morgan| Y       | 3
      | N       | 0

I tried df.groupby(["Name","Attended"]).count() and variations of it, but for some reason I don't get the right output. I get either the Name and simply the count (Smith 3, Adam 2, Morgan 3) or the same dataframe again. Help! Am I grouping by incorrectly? I looked for awhile over similar questions and my code matches with the answers there.

I'm using Python 3 and jupyter notebook.

Body:
Point out a column to count with

df.groupby(["Name ","Attended"])["Attended"].count().to_frame(name='Count')
Out[842]:
                   Count
Name     Attended
Adams    N             1
         Y             1
Morgan   Y             2
Smith    N             1
         Y             2


问:
Creating a arraylist from a class - java
I've created a class called Student which will contain information about students.

```<code>public class Student {
    private int totalPoint;
    private int antalKurser;
    private String program;

// here is constructor and get/set methods
}
</code>```

I'm also trying to create a ArrayList from that class and from what I understand i should write:

```<code>public class createArrayList {
        ArrayList<Student> studentList new ArrayList<>();
}
</code>```

However Netbeans gives me an error and if I hover the line it says ';' expexted but I'm positive I have written that (above snippet is copy-pasted). When I run the code it says "compiled with errors" but still runs.

Found somewhere else I also could write:

```<code>ArrayList<Class> studentList = new ArrayList<>();
</code>```

But then how does the application know which class it should create a list from?

The class Student is in another javafile but is in the same package. What am I missing?

答:
Try</p>

```<code>public class createArrayList {
        ArrayList<Student> studentList = new ArrayList<Student>();
}
</code>```

Body:
I've created a class called Student which will contain information about students.

public class Student {
    private int totalPoint;
    private int antalKurser;
    private String program;

// here is constructor and get/set methods
}

I'm also trying to create a ArrayList from that class and from what I understand i should write:

public class createArrayList {
        ArrayList<Student> studentList new ArrayList<>();
}

However Netbeans gives me an error and if I hover the line it says ';' expexted but I'm positive I have written that (above snippet is copy-pasted). When I run the code it says "compiled with errors" but still runs.

Found somewhere else I also could write:

ArrayList<Class> studentList = new ArrayList<>();

But then how does the application know which class it should create a list from?

The class Student is in another javafile but is in the same package. What am I missing?

Body:
Try

public class createArrayList {
        ArrayList<Student> studentList = new ArrayList<Student>();
}


问:
how to distinguish the domain from a subdomain
i have a problem with script.
At my work i often have to check PTR of domain, MX records and similar data. I did the most of the script, but the problem appears when i do something like
this is subdomain

```<code>e-learning.go4progress.pl
</code>```

this is domain but second level?

```<code>simple.com.pl
</code>```

Now in my script there is something like: if i don't put www, it adds and does

```<code>dig www.e-learning.go4progress.pl
dig e-learning.go4progress.pl
dig go4progress.pl
</code>```

he counts dots and subtracts 1, but problem is when domain looks like

```<code>simple.com.pl
</code>```

because script make dig too for

```<code>com.pl
</code>```

I don't check many domain which contains com.pl, co.uk, gov.pl. I've got an idea to make array and compare this what i put in script with array, when it finds in string component of array he subtracts 2 instead 1 ;)
I paste a part of script to better understand me why he substracks 1.

```<code>    url="`echo $1 | sed 's~http[s]*://~~g' | sed 's./$..' | awk '!/^www/ {$0="www." $0}1'`"
ii=1
dots="`echo $url | grep -o "\." | wc -l`"
while [ $ii -le $dots] ; do
        cut="`echo $url | cut -d "." -f$ii-9`"
        ip="`dig +short $cut`"
        host="`dig -x $ip +short`"
        if [[ -z "$host" ]]; then
                host="No PTR"
        fi
        echo "strona: $cut  Host: $host"
        ii=$[ii + 1]
</code>```

Maybe you have diffrent idea how to help with my problem.

Second question is how to distinguish subdomain from domain.

I need compare mx records of subdomain(when the url contains subdomain) and mx records top level domain.

I waiting for your response ;)

答:
My solution to find the domain as registered with the registrar:

```<code>wget https://raw.githubusercontent.com/gavingmiller/second-level-domains/master/SLDs.csv

DOMAIN="www.e-learning.go4progress.co.uk";
KEEPPARTS=2;
TWOLEVELS=$( /bin/echo "${DOMAIN}" | /usr/bin/rev | /usr/bin/cut -d "." --output-delimiter=".\\" -f 1-2 | /usr/bin/rev );
if  /bin/grep -P ",\.${TWOLEVELS}" SLDs.csv >/dev/null;  then
    KEEPPARTS=3;
fi
DOMAIN=$( /bin/echo "${DOMAIN}" | /usr/bin/rev | /usr/bin/cut -d "." -f "1-${KEEPPARTS}" | /usr/bin/rev );
echo "${DOMAIN}"
</code>```

Thanks to https://github.com/gavingmiller/second-level-domains and https://github.com/medialize/URI.js/issues/17#issuecomment-3976617

Body:
i have a problem with script.
At my work i often have to check PTR of domain, MX records and similar data. I did the most of the script, but the problem appears when i do something like
this is subdomain

e-learning.go4progress.pl

this is domain but second level?

simple.com.pl

Now in my script there is something like: if i don't put www, it adds and does

dig www.e-learning.go4progress.pl
dig e-learning.go4progress.pl
dig go4progress.pl

he counts dots and subtracts 1, but problem is when domain looks like

simple.com.pl

because script make dig too for

com.pl

I don't check many domain which contains com.pl, co.uk, gov.pl. I've got an idea to make array and compare this what i put in script with array, when it finds in string component of array he subtracts 2 instead 1 ;)
I paste a part of script to better understand me why he substracks 1.

    url="`echo $1 | sed 's~http[s]*://~~g' | sed 's./$..' | awk '!/^www/ {$0="www." $0}1'`"
ii=1
dots="`echo $url | grep -o "\." | wc -l`"
while [ $ii -le $dots] ; do
        cut="`echo $url | cut -d "." -f$ii-9`"
        ip="`dig +short $cut`"
        host="`dig -x $ip +short`"
        if [[ -z "$host" ]]; then
                host="No PTR"
        fi
        echo "strona: $cut  Host: $host"
        ii=$[ii + 1]

Maybe you have diffrent idea how to help with my problem.

Second question is how to distinguish subdomain from domain.

I need compare mx records of subdomain(when the url contains subdomain) and mx records top level domain.

I waiting for your response ;)

Body:
My solution to find the domain as registered with the registrar:

wget https://raw.githubusercontent.com/gavingmiller/second-level-domains/master/SLDs.csv

DOMAIN="www.e-learning.go4progress.co.uk";
KEEPPARTS=2;
TWOLEVELS=$( /bin/echo "${DOMAIN}" | /usr/bin/rev | /usr/bin/cut -d "." --output-delimiter=".\\" -f 1-2 | /usr/bin/rev );
if  /bin/grep -P ",\.${TWOLEVELS}" SLDs.csv >/dev/null;  then
    KEEPPARTS=3;
fi
DOMAIN=$( /bin/echo "${DOMAIN}" | /usr/bin/rev | /usr/bin/cut -d "." -f "1-${KEEPPARTS}" | /usr/bin/rev );
echo "${DOMAIN}"

Thanks to https://github.com/gavingmiller/second-level-domains and https://github.com/medialize/URI.js/issues/17#issuecomment-3976617