问:
Run a repeated test reporting as different tests
I'd like to unit test a function with a set of different inputs and expected outputs.

My function is irrelevant thus I'll instead use an example function which counts english words with the following candidate implementation :

```<code>int countEnglishWords( const std::string& text )
{
  return 5;
};
</code>```

The following would be the set of test data. The end of the data is marked by an element with the word "END".

```<code>struct TestData {
  std::string text;
  int englishWords;
};

struct TestData data[] = // Mark end with "END"
{
  { "The car is very fast", 5 },
  { "El coche es muy rapido", 0 },
  { "The rain in Spain stays mainly in the plain", 9},
  { "XXXXX OOOOO TTTT", 0},
  { "Yes Si No No", 3},
  { "I have a cheerful live", 5},
  { "END", 0}
};
</code>```

I could easily write 6 test cases and I would get the result I want. But this is not maintainable, since any further test added to the test cases would not be tested, it would require another test case to be written, which would be just boiler plate. Thus I've written a single test case which loops through all the test data like this :

```<code>#include <cppunit/ui/text/TestRunner.h>
#include <cppunit/extensions/HelperMacros.h>

class cppUnit_test: public CppUnit::TestFixture
{
private:
   CPPUNIT_TEST_SUITE (cppUnit_test);
   CPPUNIT_TEST(myTest);
   CPPUNIT_TEST_SUITE_END();

public:
   void myTest();
};

void cppUnit_test::myTest()
{
  TestData* p = data;
  while ( p->text != "END")
  {
    std::stringstream ss;
    ss << "Text=\"" << p->text << "\" Counted=" <<
       countEnglishWords(p->text) << " Expected=" << p->englishWords;
    CPPUNIT_ASSERT_MESSAGE( ss.str().c_str(),
                countEnglishWords(p->text) == p->englishWords );
    ++p;
  }
}

int main()
{
   CPPUNIT_TEST_SUITE_REGISTRATION (cppUnit_test);
   CppUnit::Test *suite =
         CppUnit::TestFactoryRegistry::getRegistry().makeTest();
   CppUnit::TextUi::TestRunner runner;
   runner.addTest(suite);
   runner.run();
   return 0;
}
</code>```

The problem is that the previous code runs through the 1st test fine and also detects the error in the 2nd test but after that it stops testing. And the report is :

!!!FAILURES!!!

  Test Results:

  Run:  1   Failures: 1   Errors: 0

While the result I'd like to get is :

!!!FAILURES!!!

  Test Results:

  Run:  6   Failures: 4   Errors: 0

答:
As I already mentioned in the comment cppunit 1.14.0 can support your use case.

I you want to reference an external array the quickest way is to use CPPUNIT_TEST_PARAMETERIZED. This macro expects two parameters: first similar to CPPUNIT_TEST a test method and then as a second parameter an iteratable.

Based on your code it would look like:

```<code>CPPUNIT_TEST_PARAMETERIZED(myTest, aData);
</code>```

Now we need to adapt your myTest function a little bit.

```<code>void cppUnit_test::myTest(const TestData& data)
{
    std::stringstream ss;
    ss << "Text=\"" << data.text << "\" Counted=" <<
        countEnglishWords(data.text) << " Expected=" << data.englishWords;

    bool b = countEnglishWords(data.text) == data.englishWords;
    std::string a = ss.str();
    CPPUNIT_ASSERT_MESSAGE( a,
            b);
}
</code>```

Finally as the framework needs a way to report which test failed it expects that it can print the parameter that is passed to the test function. In this case the easiest way is to add a simple operator<< overload.

```<code>std::ostream& operator<<(std::ostream& strm, const TestData& data)
{
    strm << data.text;
    return strm;
}
</code>```

If you combine these pieces you should quickly get a generic solution that will allow you to add as much data to your data array as you want without adapting the test code.

Body:
I'd like to unit test a function with a set of different inputs and expected outputs.

My function is irrelevant thus I'll instead use an example function which counts english words with the following candidate implementation :

int countEnglishWords( const std::string& text )
{
  return 5;
};

The following would be the set of test data. The end of the data is marked by an element with the word "END".

struct TestData {
  std::string text;
  int englishWords;
};

struct TestData data[] = // Mark end with "END"
{
  { "The car is very fast", 5 },
  { "El coche es muy rapido", 0 },
  { "The rain in Spain stays mainly in the plain", 9},
  { "XXXXX OOOOO TTTT", 0},
  { "Yes Si No No", 3},
  { "I have a cheerful live", 5},
  { "END", 0}
};

I could easily write 6 test cases and I would get the result I want. But this is not maintainable, since any further test added to the test cases would not be tested, it would require another test case to be written, which would be just boiler plate. Thus I've written a single test case which loops through all the test data like this :

#include <cppunit/ui/text/TestRunner.h>
#include <cppunit/extensions/HelperMacros.h>

class cppUnit_test: public CppUnit::TestFixture
{
private:
   CPPUNIT_TEST_SUITE (cppUnit_test);
   CPPUNIT_TEST(myTest);
   CPPUNIT_TEST_SUITE_END();

public:
   void myTest();
};

void cppUnit_test::myTest()
{
  TestData* p = data;
  while ( p->text != "END")
  {
    std::stringstream ss;
    ss << "Text=\"" <
text << "\" Counted=" <<
       countEnglishWords(p->text) << " Expected=" <
englishWords;
    CPPUNIT_ASSERT_MESSAGE( ss.str().c_str(),
                countEnglishWords(p->text) == p->englishWords );
    ++p;
  }
}

int main()
{
   CPPUNIT_TEST_SUITE_REGISTRATION (cppUnit_test);
   CppUnit::Test *suite =
         CppUnit::TestFactoryRegistry::getRegistry().makeTest();
   CppUnit::TextUi::TestRunner runner;
   runner.addTest(suite);
   runner.run();
   return 0;
}

The problem is that the previous code runs through the 1st test fine and also detects the error in the 2nd test but after that it stops testing. And the report is :

!!!FAILURES!!!

  Test Results:

  Run:  1   Failures: 1   Errors: 0

While the result I'd like to get is :

!!!FAILURES!!!

  Test Results:

  Run:  6   Failures: 4   Errors: 0

Body:
As I already mentioned in the comment cppunit 1.14.0 can support your use case.

I you want to reference an external array the quickest way is to use CPPUNIT_TEST_PARAMETERIZED. This macro expects two parameters: first similar to CPPUNIT_TEST a test method and then as a second parameter an iteratable.

Based on your code it would look like:

CPPUNIT_TEST_PARAMETERIZED(myTest, aData);

Now we need to adapt your myTest function a little bit.

void cppUnit_test::myTest(const TestData& data)
{
    std::stringstream ss;
    ss << "Text=\"" << data.text << "\" Counted=" <<
        countEnglishWords(data.text) << " Expected=" << data.englishWords;

    bool b = countEnglishWords(data.text) == data.englishWords;
    std::string a = ss.str();
    CPPUNIT_ASSERT_MESSAGE( a,
            b);
}

Finally as the framework needs a way to report which test failed it expects that it can print the parameter that is passed to the test function. In this case the easiest way is to add a simple operator<< overload.

std::ostream& operator<<(std::ostream& strm, const TestData& data)
{
    strm << data.text;
    return strm;
}

If you combine these pieces you should quickly get a generic solution that will allow you to add as much data to your data array as you want without adapting the test code.


来源: stackexchange

问:
Spring-data: Specifications & JPA criterias: how to left join and search/filter in collection properties
i just started to work with Specification's and Criteria* objects and im stuck on doing a simple left join and compare a value with one of the joined entity properties.
As this find/select function im going to build will be sooner or later very dynamic i decided to work with with the Criteria objects instead of building different functions with different parameters.
My real entities has some more properties but i broke it down here to simplify it.

Before i was trying to do my first steps the Specifification i had a Repository function which was annotated with @Query and was working fine:

```<code>@Query( "SELECT DISTINCT c FROM Competition c " +
    "LEFT JOIN c.aliases a " +
    "WHERE " +
    "(lower(a.value) = :name OR lower(c.name) = :lowerCaseName) " +
    "... and so on ")
</code>```

Later then i tried to build a Specification ignoring the lower case and Competition name and im still failing on how to do this join correct for comparing the name parameter with the Alias value property...

First entity:

```<code>@Entity
public class Competition extends AbstractEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @ManyToMany(cascade = CascadeType.MERGE)
    @JoinTable(name="competition_name_alias", joinColumns=@JoinColumn(name="competition_id"), inverseJoinColumns=@JoinColumn(name="alias_id"))
    private Set<Alias> aliases = new HashSet<>();

    ...
}
</code>```

Second entity:

```<code>@Entity
public class Alias extends AbstractEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true)
    private String value;

    ...
}
</code>```

Specification:

```<code>public static Specification<Competition> withLowerCaseName(String name) {
    return new Specification<Competition>() {
        @Override
        public Predicate toPredicate(Root<Competition> product, CriteriaQuery<?> query, CriteriaBuilder builder) {
            final List<Predicate> predicates = new ArrayList<Predicate>();

            Root<Competition> root = query.from(Competition.class);

            Subquery<Alias> subquery = query.subquery(Alias.class);
            SetJoin<Competition, Alias> aliases = root.join(Competition_.aliases);

            Predicate predicate = builder.equal(aliases.get(Alias_.value), name);
            builder.and(predicate);

            Predicate[] predicatesArray = new Predicate[predicates.size()];

            query.distinct(true);

            return builder.and(predicates.toArray(predicatesArray));
        }
    };
}
</code>```

Using this function gets me all competitions and seems to ignore the name parameter.
Switching on the hibernate debug/trace logging shows the reason. The generated sql has as the only where condition
where 1=1.

There is also no name value shown while switching on the logging for the descriptor.sql.BasicBinder parameters...

Does anybody have a hint what im doing wrong?

答:
Found a slighly different example here and changed it for my constellation. Seems to work...</p>

```<code>final Subquery<Alias> aliasSubquery = query.subquery(Alias.class);
final Root<Alias> alias = aliasSubquery.from(Alias.class);
final Expression<Set<Alias>> aliases = product.get(Competition_.aliases);
aliasSubquery.select(alias);
aliasSubquery.where(builder.equal(builder.lower(alias.get(Alias.value)), lowerCaseName), builder.isMember(alias, aliases));

builder.and(builder.exists(aliasSubquery));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i just started to work with Specification's and Criteria* objects and im stuck on doing a simple left join and compare a value with one of the joined entity properties.
As this find/select function im going to build will be sooner or later very dynamic i decided to work with with the Criteria objects instead of building different functions with different parameters.
My real entities has some more properties but i broke it down here to simplify it.

Before i was trying to do my first steps the Specifification i had a Repository function which was annotated with @Query and was working fine:

@Query( "SELECT DISTINCT c FROM Competition c " +
    "LEFT JOIN c.aliases a " +
    "WHERE " +
    "(lower(a.value) = :name OR lower(c.name) = :lowerCaseName) " +
    "... and so on ")

Later then i tried to build a Specification ignoring the lower case and Competition name and im still failing on how to do this join correct for comparing the name parameter with the Alias value property...

First entity:

@Entity
public class Competition extends AbstractEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @ManyToMany(cascade = CascadeType.MERGE)
    @JoinTable(name="competition_name_alias", joinColumns=@JoinColumn(name="competition_id"), inverseJoinColumns=@JoinColumn(name="alias_id"))
    private Set<Alias> aliases = new HashSet<>();

    ...
}

Second entity:

@Entity
public class Alias extends AbstractEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true)
    private String value;

    ...
}

Specification:

public static Specification<Competition> withLowerCaseName(String name) {
    return new Specification<Competition>() {
        @Override
        public Predicate toPredicate(Root<Competition> product, CriteriaQuery<?> query, CriteriaBuilder builder) {
            final List<Predicate> predicates = new ArrayList<Predicate>();

            Root<Competition> root = query.from(Competition.class);

            Subquery<Alias> subquery = query.subquery(Alias.class);
            SetJoin<Competition, Alias> aliases = root.join(Competition_.aliases);

            Predicate predicate = builder.equal(aliases.get(Alias_.value), name);
            builder.and(predicate);

            Predicate[] predicatesArray = new Predicate[predicates.size()];

            query.distinct(true);

            return builder.and(predicates.toArray(predicatesArray));
        }
    };
}

Using this function gets me all competitions and seems to ignore the name parameter.
Switching on the hibernate debug/trace logging shows the reason. The generated sql has as the only where condition
where 1=1.

There is also no name value shown while switching on the logging for the descriptor.sql.BasicBinder parameters...

Does anybody have a hint what im doing wrong?

Body:
Found a slighly different example here and changed it for my constellation. Seems to work...

final Subquery<Alias> aliasSubquery = query.subquery(Alias.class);
final Root<Alias> alias = aliasSubquery.from(Alias.class);
final Expression<Set<Alias>> aliases = product.get(Competition_.aliases);
aliasSubquery.select(alias);
aliasSubquery.where(builder.equal(builder.lower(alias.get(Alias.value)), lowerCaseName), builder.isMember(alias, aliases));

builder.and(builder.exists(aliasSubquery));


答:
We can use the apply function to iterate over the rows of your data.frame. Then, we use rowSums on the logical vectors.

```<code>rowSums(all_logicals <- apply(df, 1, function(r){
    n <- length(r)
    nc2 <- n / 2
    nc2_plus1 <- nc2 + 1
    c('allNA' = all(is.na(r)),
    'allconstant' = (length(unique(r)) == 1 & !all(is.na(r))),
    'firsthalf' = all(is.na(r[1:nc2])) & !all(is.na(r[nc2_plus1:n])),
    'secondhalf' = all(is.na(r[nc2_plus1:n])) & !all(is.na(r[1:nc2])))
}))

  allNA allconstant   firsthalf  secondhalf
      2           2           0           1
</code>```

It may be helpful to see the results from apply which are passed to rowSums:

```<code>all_logicals

             [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]  [,8]  [,9] [,10]
allNA       FALSE FALSE FALSE FALSE  TRUE FALSE  TRUE FALSE FALSE FALSE
allconstant FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE FALSE
firsthalf   FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
secondhalf  FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
</code>```

Edit - using the results to remove rows

We can use all_logicals to find the row indexes which we wish to remove:

```<code>remove_rows <- unique(unlist(apply(all_logicals, 1, which)))
(df_sub <- df[-remove_rows,])

     best2  best3  best4   best5  best6  best7   best8  best9
1   8972.7 2634.4 3079.3  8972.7 2634.4 3079.3  8972.7 2634.4
2   1944.0 1181.3 1512.9  1944.0 1181.3 1512.9  1944.0 1181.3
4  13001.7 2802.4 2804.5 13001.7 2802.4 2804.5 13001.7 2802.4
6   3228.6 1707.6 1597.6  3228.6 1707.6 1597.6  3228.6 1707.6
10  2655.9 1219.0 1558.2  2655.9 1219.0 1558.2  2655.9 1219.0
</code>```

Title: how can I count all NA and delete the row

Body:
I have a data like this

    df<-structure(list(best2 = c(8972.7, 1944, 2022.7, 13001.7, NA, 3228.6,
NA, 186.4, 100, 2655.9), best3 = c(2634.4, 1181.3, 505.2, 2802.4,
NA, 1707.6, NA, 186.4, 100, 1219), best4 = c(3079.3, 1512.9,
NA, 2804.5, NA, 1597.6, NA, 186.4, 100, 1558.2), best5 = c(8972.7,
1944, NA, 13001.7, NA, 3228.6, NA, 186.4, 100, 2655.9), best6 = c(2634.4,
1181.3, NA, 2802.4, NA, 1707.6, NA, 186.4, 100, 1219), best7 = c(3079.3,
1512.9, NA, 2804.5, NA, 1597.6, NA, 186.4, 100, 1558.2), best8 = c(8972.7,
1944, NA, 13001.7, NA, 3228.6, NA, 186.4, 100, 2655.9), best9 = c(2634.4,
1181.3, NA, 2802.4, NA, 1707.6, NA, 186.4, 100, 1219)), .Names = c("best2",
"best3", "best4", "best5", "best6", "best7", "best8", "best9"
), row.names = c(NA, -10L), class = "data.frame")

I want to do all these stuff at once

1-count number of rows that have all cells empty or NA

answer: 2

2-count rows with constant values for all cells

answer: 2

3-count rows with first half empty cells

answer: 0

4-count rows with second half empty cells

answer: 1

Body:
We can use the apply function to iterate over the rows of your data.frame. Then, we use rowSums on the logical vectors.

rowSums(all_logicals <- apply(df, 1, function(r){
    n <- length(r)
    nc2 <- n / 2
    nc2_plus1 <- nc2 + 1
    c('allNA' = all(is.na(r)),
    'allconstant' = (length(unique(r)) == 1 & !all(is.na(r))),
    'firsthalf' = all(is.na(r[1:nc2])) & !all(is.na(r[nc2_plus1:n])),
    'secondhalf' = all(is.na(r[nc2_plus1:n])) & !all(is.na(r[1:nc2])))
}))

  allNA allconstant   firsthalf  secondhalf
      2           2           0           1

It may be helpful to see the results from apply which are passed to rowSums:

all_logicals

             [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]  [,8]  [,9] [,10]
allNA       FALSE FALSE FALSE FALSE  TRUE FALSE  TRUE FALSE FALSE FALSE
allconstant FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE FALSE
firsthalf   FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
secondhalf  FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

Edit - using the results to remove rows

We can use all_logicals to find the row indexes which we wish to remove:

remove_rows <- unique(unlist(apply(all_logicals, 1, which)))
(df_sub <- df[-remove_rows,])

     best2  best3  best4   best5  best6  best7   best8  best9
1   8972.7 2634.4 3079.3  8972.7 2634.4 3079.3  8972.7 2634.4
2   1944.0 1181.3 1512.9  1944.0 1181.3 1512.9  1944.0 1181.3
4  13001.7 2802.4 2804.5 13001.7 2802.4 2804.5 13001.7 2802.4
6   3228.6 1707.6 1597.6  3228.6 1707.6 1597.6  3228.6 1707.6
10  2655.9 1219.0 1558.2  2655.9 1219.0 1558.2  2655.9 1219.0


问:
Using session in ejs
I am a newbie in node and express. I want to use cookies / session to notify my ejs once my registration is successful. I dont know which one is a better option, please suggest. Also help me with their usage.

Below are snippets of my controller ( server-side js ) and register-user ( client side js ).

registerController.js

```<code>app.post('/register',urlencodedParser,function(req,res){
  session=req.session;
  Users(req.body).save(function(err,data){
    if(err) throw err;
    console.log(" back from ajax with data :::; " + data);
    req.session.user='sasdad';
    res.status(200).send('User saved successfully');
  });
});
</code>```

register-user.js

```<code>$.ajax({
  type:'POST',
  url: '/register',
  data: user,
  success: function(data, textStatus, jqXHR){
    var resp = JSON.parse(JSON.stringify(jqXHR));
    console.log(resp);
    if(resp["status"]==200){
      console.log("status == 200");
      window.location.href = '/';
    }
    return data;
  },
  error: function(xhr, status, error) {
    console.log("inside error");
  }
  });

   return false;
});
</code>```

EJS

```<code><form action="/testAction">
  <label for="username"> Username </label>
  <input type="text" for="username" name="username"/>
  <label for="password"> Password </label>
  <input type="password" for="password" name="password" />
  <button type="submit">Log In</button>
</form>
</code>```

答:
It really depends on your use case. Looks like you are doing ajax to post the form and redirecting users to another page if it's successful. In the controller, you are saving the user in the session object, which is done correctly.

If you are going to be redirecting to another page via ajax anyway, maybe you could just do a form post (no need for ajax)? So, your form action goes to register. In your controller, you could do res.redirect('welcome page');
Then, on your welcome page's route, you could check if the user exists in your session. You could then display messages accordingly on the welcome page.

Hope that helps.

Title: Using session in ejs

Body:
I am a newbie in node and express. I want to use cookies / session to notify my ejs once my registration is successful. I dont know which one is a better option, please suggest. Also help me with their usage.

Below are snippets of my controller ( server-side js ) and register-user ( client side js ).

registerController.js

app.post('/register',urlencodedParser,function(req,res){
  session=req.session;
  Users(req.body).save(function(err,data){
    if(err) throw err;
    console.log(" back from ajax with data :::; " + data);
    req.session.user='sasdad';
    res.status(200).send('User saved successfully');
  });
});

register-user.js

$.ajax({
  type:'POST',
  url: '/register',
  data: user,
  success: function(data, textStatus, jqXHR){
    var resp = JSON.parse(JSON.stringify(jqXHR));
    console.log(resp);
    if(resp["status"]==200){
      console.log("status == 200");
      window.location.href = '/';
    }
    return data;
  },
  error: function(xhr, status, error) {
    console.log("inside error");
  }
  });

   return false;
});

EJS

<form action="/testAction">
   Username
  <input type="text" for="username" name="username"/>
   Password
  <input type="password" for="password" name="password" />
  <button type="submit">Log In</button>
</form>


问:
System.IO.StreamWriter has no string constructor in .netcore 1.1
I'm taking my first baby steps in .NET Core V1.1 under VS2017 community edition.

I ported some chunks of code to an ASP.NET Core project that utilizes System.IO.StreamWriter:

```<code>string fileName = "Hello_world.txt";

using (StreamWriter file = new StreamWriter(fileName))
{
    // do stuff...
}
</code>```

With this I get a compiler error:

```<code>error CS1503: Argument 1: cannot convert from 'string' to 'System.IO.Stream'
</code>```

On the other hand the .NET API doc clearly states that a constructor with string is available, see here.

Can anybody tell me why there is no constructor that receives a string and where to find the correct API doc?

答:
A StreamWriter object is actually a wrapper around a Stream object. You should create a FileStream, MemoryStream, or another kind of Stream and pass it to the StreamWriter constructor.

In .NET Framework, the constructor that takes a string, actually creates a FileStream under the hood.

Body:
I'm taking my first baby steps in .NET Core V1.1 under VS2017 community edition.

I ported some chunks of code to an ASP.NET Core project that utilizes System.IO.StreamWriter:

string fileName = "Hello_world.txt";

using (StreamWriter file = new StreamWriter(fileName))
{
    // do stuff...
}

With this I get a compiler error:

error CS1503: Argument 1: cannot convert from 'string' to 'System.IO.Stream'

On the other hand the .NET API doc clearly states that a constructor with string is available, see here.

Can anybody tell me why there is no constructor that receives a string and where to find the correct API doc?


问:
How to print the "instantiated" variable in Python OOP?
I am studying the book "Learn Python the Hard Way" with Python3. The author presented the concept of OOP with this example:

```<code>class Song (object):

    def __init__(self,lyrics):
        self.lyrics = lyrics

    def sing_me_a_song(self):
        for line in self.lyrics:
            print (line)

happy_bday = Song(["Happy birthday to you", "I don't want to get sued","So I'll stop right there"])

bulls_on_parade = Song(["They rally around the family","With pockets full of shells"])

happy_bday.sing_me_a_song()

bulls_on_parade.sing_me_a_song()
</code>```

OOP is kind of funny to me. The author suggest that we should "trash", "break" and "thrash" the code above a little bit.

I was trying to print the variable name in which the object was "instanced" (not sure if "instanced" is the correct word here, maybe the correct word is "instantiated"). In order to try that, I added the following methods on the class Songs():

```<code>class Song (object):

    def __init__(self,lyrics):
        self.lyrics = lyrics

    def sing_me_a_song(self):
        for line in self.lyrics:
            print (line)

    def name_of_var(self):
        print (Song)

    def name_of_var_2(self):
        print (object)

    def name_of_var_3(self):
        print (self)

    def name_of_var_3(self):
        print (self)
</code>```

I used the examples of objects provided by the author:

```<code>happy_bday = Song(["Happy birthday to you", "I don't want to get sued","So I'll stop right there"])

bulls_on_parade = Song(["They rally around the family","With pockets full of shells"])

happy_bday.sing_me_a_song()

bulls_on_parade.sing_me_a_song()
</code>```

Finally, I tried doing:

```<code>print(Song(["They rally around the family","With pockets full of shells"]))

print (happy_bday.name_of_var())

print (happy_bday.name_of_var_2())

print (happy_bday.name_of_var_3())

print (happy_bday.__init__(happy_bday))
</code>```

I wasn't able to achieve my goal. Using the methods above I got:

```<code><__main__.Song object at 0x7f4b784f3da0>
<class '__main__.Song'>
None
<class 'object'>
None
<__main__.Song object at 0x7f4b784f3d30>
None
None
pedr
</code>```

My objective was to create some method in which I would do:

```<code>print (happy_bday.__some__method())
</code>```

And the program would return:

```<code>happy_bday
</code>```

Maybe that's not even possible in Python... If I am not wrong, you can do this type of thing in Lisp/Racket (but I am not 100% sure). Is this possible in Python? How can I do that?

答:
Objects are not associated with names, rather they are associated with references.

If you truly want some means of identifying the object, allow a unique ID to be generated for each object and store it as a parameter. Heck, you can even do self.uid = id(self).

Then, you can store a map of {id : 'your_name_here'}. Later, if you want, you can use the object's uid attribute to get its "name" (the one you gave).

Body:
I am studying the book "Learn Python the Hard Way" with Python3. The author presented the concept of OOP with this example:

class Song (object):

    def __init__(self,lyrics):
        self.lyrics = lyrics

    def sing_me_a_song(self):
        for line in self.lyrics:
            print (line)

happy_bday = Song(["Happy birthday to you", "I don't want to get sued","So I'll stop right there"])

bulls_on_parade = Song(["They rally around the family","With pockets full of shells"])

happy_bday.sing_me_a_song()

bulls_on_parade.sing_me_a_song()

OOP is kind of funny to me. The author suggest that we should "trash", "break" and "thrash" the code above a little bit.

I was trying to print the variable name in which the object was "instanced" (not sure if "instanced" is the correct word here, maybe the correct word is "instantiated"). In order to try that, I added the following methods on the class Songs():

class Song (object):

    def __init__(self,lyrics):
        self.lyrics = lyrics

    def sing_me_a_song(self):
        for line in self.lyrics:
            print (line)

    def name_of_var(self):
        print (Song)

    def name_of_var_2(self):
        print (object)

    def name_of_var_3(self):
        print (self)

    def name_of_var_3(self):
        print (self)

I used the examples of objects provided by the author:

happy_bday = Song(["Happy birthday to you", "I don't want to get sued","So I'll stop right there"])

bulls_on_parade = Song(["They rally around the family","With pockets full of shells"])

happy_bday.sing_me_a_song()

bulls_on_parade.sing_me_a_song()

Finally, I tried doing:

print(Song(["They rally around the family","With pockets full of shells"]))

print (happy_bday.name_of_var())

print (happy_bday.name_of_var_2())

print (happy_bday.name_of_var_3())

print (happy_bday.__init__(happy_bday))

I wasn't able to achieve my goal. Using the methods above I got:

<__main__.Song object at 0x7f4b784f3da0>
<class '__main__.Song'>
None
<class 'object'>
None
<__main__.Song object at 0x7f4b784f3d30>
None
None
pedr

My objective was to create some method in which I would do:

print (happy_bday.__some__method())

And the program would return:

happy_bday

Maybe that's not even possible in Python... If I am not wrong, you can do this type of thing in Lisp/Racket (but I am not 100% sure). Is this possible in Python? How can I do that?


问:
Unable to run Jacoco using bnd gradle plugin
I have configured a simple bndtools project with one bundle project. I am using 'biz.aQute.bnd.workspace' bnd gradle plugin to build the project. The build is working fine.

Now I want to add jacoco gradle plugin to get the coverage report and I always get following error.

```<code>* What went wrong:
Could not resolve all dependencies for configuration
':com.example.api:jacocoAgent'.
> Cannot resolve external dependency org.jacoco:org.jacoco.agent:0.7.8
because no repositories are defined.
Required by:
  project :com.example.api
</code>```

My Settings.gradle file

```<code>buildscript {
 repositories {
maven {
  url 'https://bndtools.ci.cloudbees.com/job/bnd.master/lastSuccessfulBuild/artifact/dist/bundles'
}
mavenCentral()
}
dependencies {
     classpath 'biz.aQute.bnd:biz.aQute.bnd.gradle:+', 'org.jacoco:org.jacoco.agent:0.7.8'

}
}
apply plugin: 'biz.aQute.bnd.workspace'
</code>```

My build.gradle file is as below

```<code>subprojects {

apply plugin: 'jacoco'
}
</code>```

答:
I'm not sure what the problem with your setup is, but this is what is working for me, hope it helps:

In the project folder ("com.example.api" in your case) I added a build.gradle file like this

```<code>apply plugin: "jacoco"

repositories {
    mavenCentral()
}

jacoco {
    toolVersion = "0.7.1.201405082137"
}
</code>```

The fine-tuning is done using a "sonar-project.properties" file next to build.gradle, something like this:

```<code>sonar.projectKey=com.example.api
sonar.projectName=...
sonar.projectVersion=...

# Comma-separated paths to directories with sources (required)
sonar.sources=com.example.api/src

sonar.tests=com.example.api/test

sonar.junit.reportsPath=com.example.api/generated/reports/tests/xml

# Language
sonar.language=java

# Encoding of the source files
sonar.sourceEncoding=UTF-8

sonar.binaries=com.example.api/bin
sonar.java.coveragePlugin=jacoco
sonar.jacoco.reportPath=com.example.api/generated/jacoco/test.exec

#http://docs.sonarqube.org/display/PLUG/Java+Plugin+and+Bytecode
sonar.java.binaries=com.example.api/bin,com.example.api/bin_test
sonar.java.libraries=/somepath/cnf/nonosgi-repo/lombok/lombok-1.16.10.jar
</code>```

Hope that helps!

Body:
I have configured a simple bndtools project with one bundle project. I am using 'biz.aQute.bnd.workspace' bnd gradle plugin to build the project. The build is working fine.

Now I want to add jacoco gradle plugin to get the coverage report and I always get following error.

* What went wrong:
Could not resolve all dependencies for configuration
':com.example.api:jacocoAgent'.
> Cannot resolve external dependency org.jacoco:org.jacoco.agent:0.7.8
because no repositories are defined.
Required by:
  project :com.example.api

My Settings.gradle file

buildscript {
 repositories {
maven {
  url 'https://bndtools.ci.cloudbees.com/job/bnd.master/lastSuccessfulBuild/artifact/dist/bundles'
}
mavenCentral()
}
dependencies {
     classpath 'biz.aQute.bnd:biz.aQute.bnd.gradle:+', 'org.jacoco:org.jacoco.agent:0.7.8'

}
}
apply plugin: 'biz.aQute.bnd.workspace'

My build.gradle file is as below

subprojects {

apply plugin: 'jacoco'
}

Body:
I'm not sure what the problem with your setup is, but this is what is working for me, hope it helps:

In the project folder ("com.example.api" in your case) I added a build.gradle file like this

apply plugin: "jacoco"

repositories {
    mavenCentral()
}

jacoco {
    toolVersion = "0.7.1.201405082137"
}

The fine-tuning is done using a "sonar-project.properties" file next to build.gradle, something like this:

sonar.projectKey=com.example.api
sonar.projectName=...
sonar.projectVersion=...

# Comma-separated paths to directories with sources (required)
sonar.sources=com.example.api/src

sonar.tests=com.example.api/test

sonar.junit.reportsPath=com.example.api/generated/reports/tests/xml

# Language
sonar.language=java

# Encoding of the source files
sonar.sourceEncoding=UTF-8

sonar.binaries=com.example.api/bin
sonar.java.coveragePlugin=jacoco
sonar.jacoco.reportPath=com.example.api/generated/jacoco/test.exec

#http://docs.sonarqube.org/display/PLUG/Java+Plugin+and+Bytecode
sonar.java.binaries=com.example.api/bin,com.example.api/bin_test
sonar.java.libraries=/somepath/cnf/nonosgi-repo/lombok/lombok-1.16.10.jar

Hope that helps!


问:
Setting environment variable in react-native?
I am using react-native to build a cross-platform app, but I do not know how to set the environment variable so that I can have different constants for different environments.

Example:

```<code>development:
  BASE_URL: '',
  API_KEY: '',
staging:
  BASE_URL: '',
  API_KEY: '',
production:
  BASE_URL: '',
  API_KEY: '',
</code>```

答:
I use babel-plugin-transform-inline-environment-variables.

What I did was put a configuration files within S3 with my different environments.

```<code>s3://example-bucket/dev-env.sh
s3://example-bucket/prod-env.sh
s3://example-bucket/stage-env.sh
</code>```

EACH env file:

```<code>FIRSTENV=FIRSTVALUE
SECONDENV=SECONDVALUE
</code>```

Afterwards, I added a new script in my package.json that runs a script for bundling

```<code>if [ "$ENV" == "production" ]
then
  eval $(aws s3 cp s3://example-bucket/prod-env.sh - | sed 's/^/export /')
elif [ "$ENV" == "staging" ]
then
  eval $(aws s3 cp s3://example-bucket/stage-env.sh - | sed 's/^/export /')
else
  eval $(aws s3 cp s3://example-bucket/development-env.sh - | sed 's/^/export /')
fi

react-native start
</code>```

Within your app you will probably have a config file that has:

```<code>const FIRSTENV = process.env['FIRSTENV']
const SECONDENV = process.env['SECONDENV']
</code>```

which will be replaced by babel to:

```<code>const FIRSTENV = 'FIRSTVALUE'
const SECONDENV = 'SECONDVALUE'
</code>```

REMEMBER you have to use process.env['STRING'] NOT process.env.STRING or it won't convert properly.

Body:
I am using react-native to build a cross-platform app, but I do not know how to set the environment variable so that I can have different constants for different environments.

Example:

development:
  BASE_URL: '',
  API_KEY: '',
staging:
  BASE_URL: '',
  API_KEY: '',
production:
  BASE_URL: '',
  API_KEY: '',

Body:
I use babel-plugin-transform-inline-environment-variables.

What I did was put a configuration files within S3 with my different environments.

s3://example-bucket/dev-env.sh
s3://example-bucket/prod-env.sh
s3://example-bucket/stage-env.sh

EACH env file:

FIRSTENV=FIRSTVALUE
SECONDENV=SECONDVALUE

Afterwards, I added a new script in my package.json that runs a script for bundling

if [ "$ENV" == "production" ]
then
  eval $(aws s3 cp s3://example-bucket/prod-env.sh - | sed 's/^/export /')
elif [ "$ENV" == "staging" ]
then
  eval $(aws s3 cp s3://example-bucket/stage-env.sh - | sed 's/^/export /')
else
  eval $(aws s3 cp s3://example-bucket/development-env.sh - | sed 's/^/export /')
fi

react-native start

Within your app you will probably have a config file that has:

const FIRSTENV = process.env['FIRSTENV']
const SECONDENV = process.env['SECONDENV']

which will be replaced by babel to:

const FIRSTENV = 'FIRSTVALUE'
const SECONDENV = 'SECONDVALUE'

REMEMBER you have to use process.env['STRING'] NOT process.env.STRING or it won't convert properly.

ContentLicense: CC BY-SA 4.0


问:
Error on installing php-magicwand on RHEL (conflict between php-common)
I am trying to install ImageMagic (for php7) on RHEL7 hosted on AWS.
After running

```<code>pecl install imagick
</code>```

I end up with the following error

configure: error: not found. Please provide a path to MagickWand-config or Wand-config program.

Thus I searched for magickwand which returned a possible match php-magickwand.x86_64.

Now comes the ultimate issue. When I try to install php-magickwand via yum, I receive the following error (check the 3rd last line).

```<code>Loaded plugins: amazon-id, rhui-lb, search-disabled-repos
Resolving Dependencies
--> Running transaction check
---> Package php-magickwand.x86_64 0:1.0.9-6.el7 will be installed
--> Processing Dependency: php(zend-abi) = 20100525-64 for package: php-magickwand-1.0.9-6.el7.x86_64
--> Processing Dependency: php(api) = 20100412-64 for package: php-magickwand-1.0.9-6.el7.x86_64
--> Running transaction check
---> Package php-common.x86_64 0:5.4.16-42.el7 will be installed
--> Processing Dependency: libzip.so.2()(64bit) for package: php-common-5.4.16-42.el7.x86_64
--> Running transaction check
---> Package libzip.x86_64 0:0.10.1-8.el7 will be installed
--> Processing Conflict: php70w-common-7.0.19-1.w7.x86_64 conflicts php-common < 7.0
--> Finished Dependency Resolution
Error: php70w-common conflicts with php-common-5.4.16-42.el7.x86_64
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest
</code>```

I have searched for php-common-5.4 on my machine but there is nothing like it. All the packages I have is related to php7 (cause I never installed php55 on this machine).

Can someone please shed some light on where can I dig more? I at least Googled for an hour, no one seemed to fall into this trap.

答:
Try this and see if it works:

yum install ImageMagick-devel

Body:
I am trying to install ImageMagic (for php7) on RHEL7 hosted on AWS.
After running

pecl install imagick

I end up with the following error

configure: error: not found. Please provide a path to MagickWand-config or Wand-config program.

Thus I searched for magickwand which returned a possible match php-magickwand.x86_64.

Now comes the ultimate issue. When I try to install php-magickwand via yum, I receive the following error (check the 3rd last line).

Loaded plugins: amazon-id, rhui-lb, search-disabled-repos
Resolving Dependencies
--> Running transaction check
---> Package php-magickwand.x86_64 0:1.0.9-6.el7 will be installed
--> Processing Dependency: php(zend-abi) = 20100525-64 for package: php-magickwand-1.0.9-6.el7.x86_64
--> Processing Dependency: php(api) = 20100412-64 for package: php-magickwand-1.0.9-6.el7.x86_64
--> Running transaction check
---> Package php-common.x86_64 0:5.4.16-42.el7 will be installed
--> Processing Dependency: libzip.so.2()(64bit) for package: php-common-5.4.16-42.el7.x86_64
--> Running transaction check
---> Package libzip.x86_64 0:0.10.1-8.el7 will be installed
--> Processing Conflict: php70w-common-7.0.19-1.w7.x86_64 conflicts php-common < 7.0
--> Finished Dependency Resolution
Error: php70w-common conflicts with php-common-5.4.16-42.el7.x86_64
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest

I have searched for php-common-5.4 on my machine but there is nothing like it. All the packages I have is related to php7 (cause I never installed php55 on this machine).

Can someone please shed some light on where can I dig more? I at least Googled for an hour, no one seemed to fall into this trap.


问:
How to write a dynamic string replacement in git bash?
This is on Windows 10 using the Linuxy environment provided with Git Bash.

I have this line in my target source file:

```<code>'version' => 'v1.1.023',
</code>```

I have this function in my ~/.bash_profile:

```<code>function tag() {
    ....
    tagname="$1"
    cmd="s:v[0-9]\\.[0-9]\\.[0-9]+:$tagname:g;"
    perl -p -i -e "$cmd" config/app.php
    ...
}
</code>```

When I run the command:

```<code>$ tag v.1.1.024
</code>```

The string is not replaced, therefore the version is not updated in my code. I tried a very similar script with sed instead of perl. The file isn't getting changed. I tried the same perl replacement syntax on CentOS and it worked. Note that the double-backslash appears to be required in order for the command to work on the next line when it's run in perl. That is to say, the variable string representation of the command has a double backslash so that it becomes a literal "." in the replacement.

Any ideas?

答:
-i doesn't work on Windows builds of perl.

>perl -i -pe1 foo
Can't do inplace edit without backup.
```

<p>That feature uses anonymous files, which aren't supported by Windows. That said, you're not using a Windows build of <code>perl</code> but a cygwin build or similar. It could be that your unix emulation environment emulates anonymous files, so that might not be the the problem. </p>

<p>But if it is the problem, replacing <code>-i</code> with <code>-i.bak</code> will solve it. (Feel free to follow up with <code>rm config/app.php.bak</code>.)</p>

<hr>

<p>By the way, you are generating Perl code, which is fragile. (Tag names containing <code>:</code>, <code>\</code>, <code>$</code> or <code>@</code> will cause the code to fail.) I recommend one of the following instead:</p>

```TAGNAME="$tagname" perl -i -pe's:v[0-9]\.[0-9]\.[0-9]+:$ENV{TAGNAME}:g' config/app.php
```

<p>or</p>

```perl -i -pe'
   BEGIN { $tagname = shift(@ARGV); }
   s:v[0-9]\.[0-9]\.[0-9]+:$tagname:g;
' "$tagname" config/app.php
```

Body:
This is on Windows 10 using the Linuxy environment provided with Git Bash.

I have this line in my target source file:

'version' => 'v1.1.023',

I have this function in my ~/.bash_profile:

function tag() {
    ....
    tagname="$1"
    cmd="s:v[0-9]\\.[0-9]\\.[0-9]+:$tagname:g;"
    perl -p -i -e "$cmd" config/app.php
    ...
}

When I run the command:

$ tag v.1.1.024

The string is not replaced, therefore the version is not updated in my code. I tried a very similar script with sed instead of perl. The file isn't getting changed. I tried the same perl replacement syntax on CentOS and it worked. Note that the double-backslash appears to be required in order for the command to work on the next line when it's run in perl. That is to say, the variable string representation of the command has a double backslash so that it becomes a literal "." in the replacement.

Any ideas?

Body:
-i doesn't work on Windows builds of perl.

>perl -i -pe1 foo
Can't do inplace edit without backup.

That feature uses anonymous files, which aren't supported by Windows. That said, you're not using a Windows build of perl but a cygwin build or similar. It could be that your unix emulation environment emulates anonymous files, so that might not be the the problem.

But if it is the problem, replacing -i with -i.bak will solve it. (Feel free to follow up with rm config/app.php.bak.)

By the way, you are generating Perl code, which is fragile. (Tag names containing :, \, $ or @ will cause the code to fail.) I recommend one of the following instead:

TAGNAME="$tagname" perl -i -pe's:v[0-9]\.[0-9]\.[0-9]+:$ENV{TAGNAME}:g' config/app.php

or

perl -i -pe'
   BEGIN { $tagname = shift(@ARGV); }
   s:v[0-9]\.[0-9]\.[0-9]+:$tagname:g;
' "$tagname" config/app.php


问:
$_SERVER['PHP_SELF'] intermittently returning two leading forward slashes
Why would $_SERVER['PHP_SELF'] return a filename in one instance as /test/foo.bar and another instance (executed from the same php script) as //test/foo.bar (with double leading forward slashes)?

form.php sends $_GET to login.php. login.php redirects to

```<code>header ('Location: test/foo.bar')
</code>```

foo.bar includes:

```<code>$page = filter_var($_SERVER['SCRIPT_NAME'], FILTER_SANITIZE_STRING);
</code>```

(Additionally, I cannot replicate it on demand. )

答:
I'd guess you're building links in code somewhere (or maybe someone just typed in an extra slash somewhere).  You might have some code along these lines:

```<code>function buildLink($site, $relPath, $text) {
    return "<a href=\"$site/$relPath\">$text</a>";
}
</code>```

If $site is passed in with a trailing slash in some cases, you'd end up with the leading double slash when the server name was removed.  Or if an absolute path was passed in.  An extra slash won't affect which page is displayed, but it would still show up in the parsed url.

ContentLicense: CC BY-SA 2.5

Body:
Why would $_SERVER['PHP_SELF'] return a filename in one instance as /test/foo.bar and another instance (executed from the same php script) as //test/foo.bar (with double leading forward slashes)?

form.php sends $_GET to login.php. login.php redirects to

header ('Location: test/foo.bar')

foo.bar includes:

$page = filter_var($_SERVER['SCRIPT_NAME'], FILTER_SANITIZE_STRING);

(Additionally, I cannot replicate it on demand. )

Body:
I'd guess you're building links in code somewhere (or maybe someone just typed in an extra slash somewhere).  You might have some code along these lines:

function buildLink($site, $relPath, $text) {
    return "<a href=\"$site/$relPath\">$text</a>";
}

If $site is passed in with a trailing slash in some cases, you'd end up with the leading double slash when the server name was removed.  Or if an absolute path was passed in.  An extra slash won't affect which page is displayed, but it would still show up in the parsed url.


答:
You can't do that. The name of your variable isn't part of the instance, and the instance doesn't know about it. As far as it is concerned, it has no name at all, or many, or maybe it is part of a list or so.

Like this:

```<code>>>> print(Song(["Line", "Line"]).some_method())
</code>```

In this case, the instance is made, the method is called, and then the instance is thrown away again. It never had a name. What should it print?

Or this:

```<code>>>> name1 = name2 = Song(["Line", "Line"])
>>> name1.some_method()
</code>```

Now the instance is referred to by two names, both name1 and name2.

```<code>>>> name1  = [Song(["Line"])]
</code>```

Now it doesn't have a name itself, but there exists a list with a name that holds a reference to the song.

And so on. I hope this makes it a bit clearer. Instances exist apart from their names.

Title: How to print the "instantiated" variable in Python OOP?

Body:
You can't do that. The name of your variable isn't part of the instance, and the instance doesn't know about it. As far as it is concerned, it has no name at all, or many, or maybe it is part of a list or so.

Like this:

>>> print(Song(["Line", "Line"]).some_method())

In this case, the instance is made, the method is called, and then the instance is thrown away again. It never had a name. What should it print?

Or this:

>>> name1 = name2 = Song(["Line", "Line"])
>>> name1.some_method()

Now the instance is referred to by two names, both name1 and name2.

>>> name1  = [Song(["Line"])]

Now it doesn't have a name itself, but there exists a list with a name that holds a reference to the song.

And so on. I hope this makes it a bit clearer. Instances exist apart from their names.


答:
What's confusing you is that an object doesn't actually have a name! Let's say we create a Song using the Song constructor, and put it in a variable called happy_bday:

```<code>happy_bday = Song(["Happy birthday to you", "I don't want to get sued","So I'll stop right there"])
</code>```

This creates a Song object, which lives on "the heap," an area of memory in your computer. It also creates a variable called happy_bday, which refers to the Song object you've just created. The Song object itself doesn't know this, though.

In fact, if you run

```<code>happy_bday2 = happy_bday
</code>```

you will create another variable, happy_bday2, that refers to the exact same Song object. In fact, if you were to now run the line

```<code>happy_bday.lyrics[0] = "Happy Birthday To You"
</code>```

to add some capitalization, the lyrics of happy_bday2 would also change. That's because even though you have two separate variables, they are really just two ways of referring to the exact same object in memory.

Hopefully, it's now clear why you can't ask the Song object what variable refers to it; there could be multiple variables that refer to it, or no variables at all (after all, you could just write Song(["some lyrics"]).var_name(), in which case, what should be printed out?).

If you'd like to visualize this, there's a great tool called PythonTutor available here: http://pythontutor.com. You can type in your code, and see the variables and objects that are being created.

Body:
What's confusing you is that an object doesn't actually have a name! Let's say we create a Song using the Song constructor, and put it in a variable called happy_bday:

happy_bday = Song(["Happy birthday to you", "I don't want to get sued","So I'll stop right there"])

This creates a Song object, which lives on "the heap," an area of memory in your computer. It also creates a variable called happy_bday, which refers to the Song object you've just created. The Song object itself doesn't know this, though.

In fact, if you run

happy_bday2 = happy_bday

you will create another variable, happy_bday2, that refers to the exact same Song object. In fact, if you were to now run the line

happy_bday.lyrics[0] = "Happy Birthday To You"

to add some capitalization, the lyrics of happy_bday2 would also change. That's because even though you have two separate variables, they are really just two ways of referring to the exact same object in memory.

Hopefully, it's now clear why you can't ask the Song object what variable refers to it; there could be multiple variables that refer to it, or no variables at all (after all, you could just write Song(["some lyrics"]).var_name(), in which case, what should be printed out?).

If you'd like to visualize this, there's a great tool called PythonTutor available here: http://pythontutor.com. You can type in your code, and see the variables and objects that are being created.


问:
How to subtract rows based on matching column in Pandas?
If I have two dataframes, like these in the example created with:

```<code>df1 = pd.DataFrame({'A': randint(1,11,10), 'B': randint(10,100,10), 'C': randint(100,1000,10)})
df2 = pd.DataFrame({'A': randint(1,11,10), 'B': randint(10,100,10), 'C': randint(100,1000,10)})
df2 = df2.drop_duplicates(subset=['A'])
</code>```

df1

```<code>    A   B   C
0   2   96  826
1   1   64  601
2   1   27  343
3   5   65  600
4   10  68  658
5   6   81  895
6   5   73  440
7   4   54  865
8   1   24  597
9   10  66  928
</code>```

df2

```<code>    A   B   C
0   2   87  669
1   5   99  594
2   6   50  989
3   10  46  767
4   3   56  828
5   4   83  415
6   1   41  332
</code>```

How can I subtract columns B (df['B'] - df2['B']) only if the values from column A are matching? So I can get a new column in df1 like:

```<code>9
23
-14
-34
22
31
-26
-29
-17
20
</code>```

答:
To get the values you want to subtract, take df1['A'] and map the values of df2['B'] to it by indexing df2['B'] with df2['A']:

```<code>df1['new'] = df1['B'] - df1['A'].map(df2.set_index('A')['B'])
</code>```

The resulting output:

```<code>    A   B    C  new
0   2  96  826    9
1   1  64  601   23
2   1  27  343  -14
3   5  65  600  -34
4  10  68  658   22
5   6  81  895   31
6   5  73  440  -26
7   4  54  865  -29
8   1  24  597  -17
9  10  66  928   20
</code>```

Edit

For smaller datasets, it may be slightly faster to supply a dictionary to map.

Timings on the example dataset:

```<code>%timeit df1.B - df1.A.map(df2.set_index('A').B)
%timeit df1.B - df1.A.map(dict(zip(df2.A, df2.B)))
%timeit df1.B - df1.A.map(dict(zip(df2.A.values, df2.B.values)))

1000 loops, best of 3: 718 µs per loop
1000 loops, best of 3: 492 µs per loop
1000 loops, best of 3: 459 µs per loop
</code>```

For larger datasets, using the index method appears to be faster.

Larger dataset setup:

```<code>rows, a_max, b_max, c_max = 10**6, 5*10**4, 10**5, 10**5
df1 = pd.DataFrame({'A': randint(1, a_max, rows), 'B': randint(10, b_max, rows), 'C': randint(100, c_max, rows)})
df2 = pd.DataFrame({'A': randint(1, a_max, rows), 'B': randint(10, b_max, rows), 'C': randint(100, c_max, rows)})
df2 = df2.drop_duplicates(subset=['A'])
</code>```

Timings on the larger dataset:

```<code>%timeit df1.B - df1.A.map(df2.set_index('A').B)
%timeit df1.B - df1.A.map(dict(zip(df2.A, df2.B)))
%timeit df1.B - df1.A.map(dict(zip(df2.A.values, df2.B.values)))

10 loops, best of 3: 114 ms per loop
10 loops, best of 3: 359 ms per loop
10 loops, best of 3: 354 ms per loop
</code>```

Body:
If I have two dataframes, like these in the example created with:

df1 = pd.DataFrame({'A': randint(1,11,10), 'B': randint(10,100,10), 'C': randint(100,1000,10)})
df2 = pd.DataFrame({'A': randint(1,11,10), 'B': randint(10,100,10), 'C': randint(100,1000,10)})
df2 = df2.drop_duplicates(subset=['A'])

df1

    A   B   C
0   2   96  826
1   1   64  601
2   1   27  343
3   5   65  600
4   10  68  658
5   6   81  895
6   5   73  440
7   4   54  865
8   1   24  597
9   10  66  928

df2

    A   B   C
0   2   87  669
1   5   99  594
2   6   50  989
3   10  46  767
4   3   56  828
5   4   83  415
6   1   41  332

How can I subtract columns B (df['B'] - df2['B']) only if the values from column A are matching? So I can get a new column in df1 like:

9
23
-14
-34
22
31
-26
-29
-17
20

Body:
To get the values you want to subtract, take df1['A'] and map the values of df2['B'] to it by indexing df2['B'] with df2['A']:

df1['new'] = df1['B'] - df1['A'].map(df2.set_index('A')['B'])

The resulting output:

    A   B    C  new
0   2  96  826    9
1   1  64  601   23
2   1  27  343  -14
3   5  65  600  -34
4  10  68  658   22
5   6  81  895   31
6   5  73  440  -26
7   4  54  865  -29
8   1  24  597  -17
9  10  66  928   20

Edit

For smaller datasets, it may be slightly faster to supply a dictionary to map.

Timings on the example dataset:

%timeit df1.B - df1.A.map(df2.set_index('A').B)
%timeit df1.B - df1.A.map(dict(zip(df2.A, df2.B)))
%timeit df1.B - df1.A.map(dict(zip(df2.A.values, df2.B.values)))

1000 loops, best of 3: 718 µs per loop
1000 loops, best of 3: 492 µs per loop
1000 loops, best of 3: 459 µs per loop

For larger datasets, using the index method appears to be faster.

Larger dataset setup:

rows, a_max, b_max, c_max = 10**6, 5*10**4, 10**5, 10**5
df1 = pd.DataFrame({'A': randint(1, a_max, rows), 'B': randint(10, b_max, rows), 'C': randint(100, c_max, rows)})
df2 = pd.DataFrame({'A': randint(1, a_max, rows), 'B': randint(10, b_max, rows), 'C': randint(100, c_max, rows)})
df2 = df2.drop_duplicates(subset=['A'])

Timings on the larger dataset:

%timeit df1.B - df1.A.map(df2.set_index('A').B)
%timeit df1.B - df1.A.map(dict(zip(df2.A, df2.B)))
%timeit df1.B - df1.A.map(dict(zip(df2.A.values, df2.B.values)))

10 loops, best of 3: 114 ms per loop
10 loops, best of 3: 359 ms per loop
10 loops, best of 3: 354 ms per loop


问:
In iOS AVPlayer, addPeriodicTimeObserverForInterval seems to be missing
I'm trying to setup AVPlayer.addPeriodicTimeObserverForInterval(). Has anyone used this successfully?

I'm using Xcode 8.1, Swift 3

答:
The accepted answer makes it feel like that you can assign the return value to a local variable and ignore it. But according to the doc, it is actually important the hold on strong reference to the return value and removeTimeObserver(_ :).

You must maintain a strong reference the returned value as long as you want the time observer to be invoked by the player. Each invocation of this method should be paired with a corresponding call to
  removeTimeObserver(:)
  . Releasing the observer object without invoking
  removeTimeObserver(:)
   will result in undefined behaviour.

So I would do:

```<code>if let ob = self.observer {
    player.removeTimeObserver(ob)
}

let interval = CMTimeMake(1, 4) // 0.25 (1/4) seconds
self.observer = player.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main) { [weak self] time in
    ...
}
</code>```

Body:
The accepted answer makes it feel like that you can assign the return value to a local variable and ignore it. But according to the doc, it is actually important the hold on strong reference to the return value and removeTimeObserver(_ :).

You must maintain a strong reference the returned value as long as you want the time observer to be invoked by the player. Each invocation of this method should be paired with a corresponding call to
  removeTimeObserver(:)
  . Releasing the observer object without invoking
  removeTimeObserver(:)
   will result in undefined behaviour.

So I would do:

if let ob = self.observer {
    player.removeTimeObserver(ob)
}

let interval = CMTimeMake(1, 4) // 0.25 (1/4) seconds
self.observer = player.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main) { [weak self] time in
    ...
}


问:
How to resolve a category from a property table in SQL
By way of an example, lets say I have the following (simplified) table (called NumericValue):

```<code>Age   Gender    Occupation      Location        Value
40    M         Accountant      Johannesburg    100
40    F         Accountant      Johannesburg    120
40    M         Engineer        NULL            110
40    F         Engineer        NULL            110
</code>```

Now suppose I have this table called Employees:

```<code>Employee Number  Age   Gender    Occupation      Location
1000123          40    F         Engineer        Cape Town
1000124          40    M         Accountant      Johannesburg
</code>```

Now, what I need is to select the "value" field for these two employees. And let's say that engineers will never ever have a "location" in the NumericValue table, so I can't just do a simple join. In stead, I reformat my "NumericTable" as follows:

```<code>Table: "CategoryValue"
Category   Value
1          100
2          120
3          110
4          110
</code>```

With a "property" table like this:

```<code>Table: "CategoryProperty"
Category   FieldName   FieldValue
1          Age         40
1          Gender      M
1          Occupation  Accountant
1          Location    Johannesburg
.
.
4          Age         40
4          Gender      F
4          Occupation  Engineer
</code>```

(note, no entry for "location" under category 4, which refers to the 40 year old female engineer)

Which makes sense to me, since I only have entries where a specific categorisation field is of importance. But how do I resolve this and extract the Value field for the specific employee?

Thanks

Karl

答:
Why don't you do something like this?

```<code>Select  e.EmployeeNumber,
        e.Age,
        e.Gender,
        e.Occupation,
        e.Location,
        nv.Value
From Employees e
Join NumericValue nv on e.Age = nv.Age
                        And e.Gender = nv.Gender
                        And e.Occupation = nv.Occupation
                        And e.Location = IsNull(nv.Location, e.Location)
</code>```

Just replace the NumericValue Location with the value of the Employee Location when it is NULL

Body:
By way of an example, lets say I have the following (simplified) table (called NumericValue):

Age   Gender    Occupation      Location        Value
40    M         Accountant      Johannesburg    100
40    F         Accountant      Johannesburg    120
40    M         Engineer        NULL            110
40    F         Engineer        NULL            110

Now suppose I have this table called Employees:

Employee Number  Age   Gender    Occupation      Location
1000123          40    F         Engineer        Cape Town
1000124          40    M         Accountant      Johannesburg

Now, what I need is to select the "value" field for these two employees. And let's say that engineers will never ever have a "location" in the NumericValue table, so I can't just do a simple join. In stead, I reformat my "NumericTable" as follows:

Table: "CategoryValue"
Category   Value
1          100
2          120
3          110
4          110

With a "property" table like this:

Table: "CategoryProperty"
Category   FieldName   FieldValue
1          Age         40
1          Gender      M
1          Occupation  Accountant
1          Location    Johannesburg
.
.
4          Age         40
4          Gender      F
4          Occupation  Engineer

(note, no entry for "location" under category 4, which refers to the 40 year old female engineer)

Which makes sense to me, since I only have entries where a specific categorisation field is of importance. But how do I resolve this and extract the Value field for the specific employee?

Thanks

Karl

Body:
Why don't you do something like this?

Select  e.EmployeeNumber,
        e.Age,
        e.Gender,
        e.Occupation,
        e.Location,
        nv.Value
From Employees e
Join NumericValue nv on e.Age = nv.Age
                        And e.Gender = nv.Gender
                        And e.Occupation = nv.Occupation
                        And e.Location = IsNull(nv.Location, e.Location)

Just replace the NumericValue Location with the value of the Employee Location when it is NULL


问:
Play Framework Scala Templates looping through two lists comparing items
I'm trying to compare two lists by using only scala templates from play framework. My goal is to show all items listA in a table and then find out if listA has objects containing the same values as in listB to change the appearence of the duplicated items.

So let's assume a.id has an equivalent b.id, then i want a.id to appear in the list but crossed-out.

Example Input: listA has 5 objects with the attributes name and id. listB has 2 objects with the attributes id and xxx.

Desired Output: I want to display all items from listA (using the first scala @for loop), but if the id already exists in listB, i want the item to be <s>crossed out</s> in my table.

This is what i got so far:

```<code> <tbody>
        @for(a <- aList){
            @for(b <- bList){
                 <thead>
                    <tr>
                       <th>Key</th>
                       <th>Name</th>
                    </tr>
                 </thead>
                 @if(a.id == b.id){
                    <tr>
                        <td><s>@a.id</s></td>
                        <td><s>@a.name</s></td>
                    </tr>
                    } else {
                    <tr>
                        <td>@a.id</td>
                        <td>@a.name</td>
                    </tr>
                    }
                }
             } </tbody>
</code>```

So far the code works, but now every element from listA appears as many times as the second loop goes through, which absolutely makes sense, but how can i prevent that?

答:
```<code>var valueA= document.getElementById(@a.id);

var valueB= document.getElementById(@b.id);
@if(valueA == valueB){

}
</code>```

Or
You can use

```<code>if(valueA.contains(valueB)){

}
</code>```

Body:
I'm trying to compare two lists by using only scala templates from play framework. My goal is to show all items listA in a table and then find out if listA has objects containing the same values as in listB to change the appearence of the duplicated items.

So let's assume a.id has an equivalent b.id, then i want a.id to appear in the list but crossed-out.

Example Input: listA has 5 objects with the attributes name and id. listB has 2 objects with the attributes id and xxx.

Desired Output: I want to display all items from listA (using the first scala @for loop), but if the id already exists in listB, i want the item to be <s>crossed out</s> in my table.

This is what i got so far:

        @for(a <- aList){
            @for(b <- bList){

                       Key
                       Name

                 @if(a.id == b.id){

                        <s>@a.id</s>
                        <s>@a.name</s>

                    } else {

                        @a.id
                        @a.name

                    }
                }
             }

So far the code works, but now every element from listA appears as many times as the second loop goes through, which absolutely makes sense, but how can i prevent that?

Body:
var valueA= document.getElementById(@a.id);

var valueB= document.getElementById(@b.id);
@if(valueA == valueB){

}

Or
You can use

if(valueA.contains(valueB)){

}


问:
Class calling own method within method NodeJS/ES6
Firstly, I apologize if this has already been answered; I've been searching and searching but nothing I have found has given me that Eureka! moment...so I come here.

I am newish to Node and ES6 and am looking to abstract some of my functions/methods from my app.js file. Doing so...I have created a class like the below.

```<code>this.tryLogin(email, password)....
</code>```

Always returns undefined.

I have tried:

in constructor()var self = this and set it to self.tryLogin()... to no avail

Experimented with using function UserHandler() {}.... and using prototypes.

My goal is to create a JS "class" where I have the ability to call it's own methods both INSIDE and OUTSIDE the class.

```<code>    class UserHandler {

    constructor() {
        this.aws_config = require("./aws-config");
    }

    redirectIfLoggedIn(request, response, next) {

        if (request.session.user && request.session.user.id_token) {

            if (request.query.redirect) {
                response.redirect(request.query.redirect);
            }
            else {
                response.redirect("/profile");
            }
        }
        else {
            next();
        }
    }

    handleLogin(request, response, next) {
        let form_data = request.body;
        let email = request.body.email;
        let password = request.body.password;
        let remember_me = request.body.remember_me;

        this.tryLogin(email, password).then(function () {

        }).catch(function(){

        });
    }

    tryLogin(username, password) {
        return new Promise(function(resolve, reject) {

        });
    }
    // Test function
    pingPromise(string) {
        return new Promise(function(resolve , reject) {
            if (string == "ping") {
                resolve("pong");
            }
            else {
                reject(Error("You must send 'ping'!"));
            }
        });
    }
}

module.exports = new UserHandler();
</code>```

EDIT:

Error I am trying to solve TypeError: Cannot read property 'tryLogin' of undefined

I am initially calling the handleLogin function via ExpressJS as a middleware:

```<code>app.post(default_data.login_form_action, UserHandler.handleLogin, function (request, response) {});
</code>```

答:
I think you should return the result of calling this.tryLogin():

```<code>handleLogin(request, response, next) {
    let form_data = request.body;
    let email = request.body.email;
    let password = request.body.password;
    let remember_me = request.body.remember_me;

    return this.tryLogin(email, password).then(function () {

    }).catch(function(){

    });
}
</code>```

Body:
Firstly, I apologize if this has already been answered; I've been searching and searching but nothing I have found has given me that Eureka! moment...so I come here.

I am newish to Node and ES6 and am looking to abstract some of my functions/methods from my app.js file. Doing so...I have created a class like the below.

this.tryLogin(email, password)....

Always returns undefined.

I have tried:

in constructor()var self = this and set it to self.tryLogin()... to no avail

Experimented with using function UserHandler() {}.... and using prototypes.

My goal is to create a JS "class" where I have the ability to call it's own methods both INSIDE and OUTSIDE the class.

    class UserHandler {

    constructor() {
        this.aws_config = require("./aws-config");
    }

    redirectIfLoggedIn(request, response, next) {

        if (request.session.user && request.session.user.id_token) {

            if (request.query.redirect) {
                response.redirect(request.query.redirect);
            }
            else {
                response.redirect("/profile");
            }
        }
        else {
            next();
        }
    }

    handleLogin(request, response, next) {
        let form_data = request.body;
        let email = request.body.email;
        let password = request.body.password;
        let remember_me = request.body.remember_me;

        this.tryLogin(email, password).then(function () {

        }).catch(function(){

        });
    }

    tryLogin(username, password) {
        return new Promise(function(resolve, reject) {

        });
    }
    // Test function
    pingPromise(string) {
        return new Promise(function(resolve , reject) {
            if (string == "ping") {
                resolve("pong");
            }
            else {
                reject(Error("You must send 'ping'!"));
            }
        });
    }
}

module.exports = new UserHandler();

EDIT:

Error I am trying to solve TypeError: Cannot read property 'tryLogin' of undefined

I am initially calling the handleLogin function via ExpressJS as a middleware:

app.post(default_data.login_form_action, UserHandler.handleLogin, function (request, response) {});

Body:
I think you should return the result of calling this.tryLogin():

handleLogin(request, response, next) {
    let form_data = request.body;
    let email = request.body.email;
    let password = request.body.password;
    let remember_me = request.body.remember_me;

    return this.tryLogin(email, password).then(function () {

    }).catch(function(){

    });
}


问:
How to trigger lambda-local command from .js file in a nodejs application
I am using a nodejs application and
w.r.t this link :- http://blog.rowanudell.com/testing-serverless-functions-locally/.

I was able to call the lambda function locally with the command : $ lambda-local  -f index.js on CLI.

Is there a way to trigger the same from inside a .js file of nodejs application?

答:
This should do the job:</p>

```<code>// set the event data you want here
const event = {};
// mock the context if needed here
const context = {};
// retrieve the result of the lambda here
const cb = (err, res) => {
  console.log(err, res);
};

// load the file containing the Lambda handler
const lambda = require("./path/to/index.js");
// call the handler
lambda.handler(event, context, cb);
</code>```

Body:
This should do the job:

// set the event data you want here
const event = {};
// mock the context if needed here
const context = {};
// retrieve the result of the lambda here
const cb = (err, res) => {
  console.log(err, res);
};

// load the file containing the Lambda handler
const lambda = require("./path/to/index.js");
// call the handler
lambda.handler(event, context, cb);


问:
Dart final functions
Is it possible for the _distance variable to be final but still keep the type signatures in the constructor for a Dart object?

```<code>Function _distance;

ExampleConstuctor(num distanceFunction(T a, T b)) {
  _distance = distanceFunction;
}
</code>```

答:
You can use a typedef:</p>

```<code>typedef num DistanceFunction<T>(T a, T b);

class ExampleConstructor<T> {
  final DistanceFunction<T> _distance;

  ExampleConstructor(this._distance);
}
</code>```

Title: Dart final functions

Body:
Is it possible for the _distance variable to be final but still keep the type signatures in the constructor for a Dart object?

Function _distance;

ExampleConstuctor(num distanceFunction(T a, T b)) {
  _distance = distanceFunction;
}

Body:
You can use a typedef:

typedef num DistanceFunction<T>(T a, T b);

class ExampleConstructor<T> {
  final DistanceFunction<T> _distance;

  ExampleConstructor(this._distance);
}


问:
How to avoid rendering directive element
Is it possible to hide my directive html element?
I mean if I have this directive:

app.js

```<code>angular.module("myApp", [])
    .directive("myDirective", function() {
        return {
            restrict: "E",
            template: "<div><p>Some text...</p></div>"
    }
);
</code>```

Only render the content of the template.

```<code><div>
    <p>Some text...</p>
</div>
</code>```

Not the directives element:

```<code><my-directive>
    <div>
        <p>Some text...</p>
    </div>
</my-directive>
</code>```

答:
Note that replace: true is marked as deprecated (I use it myself nonetheless from time to time)

See: Explain replace=true in Angular Directives (Deprecated)

Body:
Is it possible to hide my directive html element?
I mean if I have this directive:

app.js

angular.module("myApp", [])
    .directive("myDirective", function() {
        return {
            restrict: "E",
            template: "

Some text...

"
    }
);

Only render the content of the template.

Some text...

Not the directives element:

<my-directive>

Some text...

</my-directive>


问:
Grow/Shrink flex item to fit image
I have a layout with an image on the left and text content on the right. I want an image to have 100% height and I want to keep image aspect ratio. Text content should fill available width.

I tried with flex-box, but an image flex item will not adjust its width to the image size:

.wrap {
  display: flex;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.image-container {
  background-color: blue;
  flex: 0 0 auto;
}

img {
  height: 100%;
}

.content-container {
  background-color: green;
  flex: 1 1 0;
  overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">
  <div class="image-container">
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/06/Kitten_in_Rizal_Park%2C_Manila.jpg/230px-Kitten_in_Rizal_Park%2C_Manila.jpg" />
  </div>
  <div class="content-container">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam vitae interdum nunc. In nec semper lectus. Nunc et nisi mi. Integer lobortis lobortis fermentum. Pellentesque egestas, turpis eget rhoncus feugiat, massa elit euismod eros, et venenatis libero ex sed ipsum. Cras ut nisi eget erat hendrerit porttitor. Pellentesque mi elit, fringilla vel nulla eget, consequat iaculis ante. Maecenas rhoncus ante nec augue maximus tristique ac ut massa. Suspendisse sit amet mi nunc. Integer commodo nulla non sapien volutpat, non faucibus nunc scelerisque. Nullam nec venenatis ligula. Etiam ac molestie magna, et dictum nibh.
  </div>
</div></code>```

How to grow/shrink image-container flex item to fit image size?

答:
One way to do it is to simply erase the DIV around the image (you won't see the background anyway, if it works the way you want), which makes the image itself a flex-item, and leave that at the default settings:

.wrap {
  display: flex;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

img {
  height: 100%;
  width: auto;
}

.content-container {
  background-color: green;
  overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/06/Kitten_in_Rizal_Park%2C_Manila.jpg/230px-Kitten_in_Rizal_Park%2C_Manila.jpg" />
  <div class="content-container">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam vitae interdum nunc. In nec semper lectus. Nunc et nisi mi. Integer lobortis lobortis fermentum. Pellentesque egestas, turpis eget rhoncus feugiat, massa elit euismod eros, et venenatis libero ex sed ipsum. Cras ut nisi eget erat hendrerit porttitor. Pellentesque mi elit, fringilla vel nulla eget, consequat iaculis ante. Maecenas rhoncus ante nec augue maximus tristique ac ut massa. Suspendisse sit amet mi nunc. Integer commodo nulla non sapien volutpat, non faucibus nunc scelerisque. Nullam nec venenatis ligula. Etiam ac molestie magna, et dictum nibh.
  </div>
</div></code>```

Title: Grow/Shrink flex item to fit image

Body:
I have a layout with an image on the left and text content on the right. I want an image to have 100% height and I want to keep image aspect ratio. Text content should fill available width.

I tried with flex-box, but an image flex item will not adjust its width to the image size:

.wrap {
  display: flex;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.image-container {
  background-color: blue;
  flex: 0 0 auto;
}

img {
  height: 100%;
}

.content-container {
  background-color: green;
  flex: 1 1 0;
  overflow: auto;
}

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam vitae interdum nunc. In nec semper lectus. Nunc et nisi mi. Integer lobortis lobortis fermentum. Pellentesque egestas, turpis eget rhoncus feugiat, massa elit euismod eros, et venenatis libero ex sed ipsum. Cras ut nisi eget erat hendrerit porttitor. Pellentesque mi elit, fringilla vel nulla eget, consequat iaculis ante. Maecenas rhoncus ante nec augue maximus tristique ac ut massa. Suspendisse sit amet mi nunc. Integer commodo nulla non sapien volutpat, non faucibus nunc scelerisque. Nullam nec venenatis ligula. Etiam ac molestie magna, et dictum nibh.

How to grow/shrink image-container flex item to fit image size?

Body:
One way to do it is to simply erase the DIV around the image (you won't see the background anyway, if it works the way you want), which makes the image itself a flex-item, and leave that at the default settings:

.wrap {
  display: flex;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

img {
  height: 100%;
  width: auto;
}

.content-container {
  background-color: green;
  overflow: auto;
}

<div class="wrap">
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/06/Kitten_in_Rizal_Park%2C_Manila.jpg/230px-Kitten_in_Rizal_Park%2C_Manila.jpg" />
  <div class="content-container">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam vitae interdum nunc. In nec semper lectus. Nunc et nisi mi. Integer lobortis lobortis fermentum. Pellentesque egestas, turpis eget rhoncus feugiat, massa elit euismod eros, et venenatis libero ex sed ipsum. Cras ut nisi eget erat hendrerit porttitor. Pellentesque mi elit, fringilla vel nulla eget, consequat iaculis ante. Maecenas rhoncus ante nec augue maximus tristique ac ut massa. Suspendisse sit amet mi nunc. Integer commodo nulla non sapien volutpat, non faucibus nunc scelerisque. Nullam nec venenatis ligula. Etiam ac molestie magna, et dictum nibh.
  </div>
</div>


问:
Can't reset a file to a specific commit using Git
I have a modified file which I want to rever to whatever is in the latest commit but it's "stuck" there always being marked as modified.

```<code>$ git status
# On branch master
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   index.php
#
no changes added to commit (use "git add" and/or "git commit -a")
</code>```

I then try:

```<code>$git checkout -- index.php
</code>```

But the output of git status is still the same. I then try:

```<code>$git reset --hard master
HEAD is now at 02c9613 test commit message
</code>```

And the output of git status is STILL the same.

Any ideas on how I can get rid of the supposed changes on that file?

答:
You have to remove index.php from the "index."  Then can you checkout a different version.

```<code>git rm --cached index.php
</code>```

Should do the trick.  See:

http://www.kernel.org/pub/software/scm/git/docs/git-rm.html

Body:
I have a modified file which I want to rever to whatever is in the latest commit but it's "stuck" there always being marked as modified.

$ git status
# On branch master
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   index.php
#
no changes added to commit (use "git add" and/or "git commit -a")

I then try:

$git checkout -- index.php

But the output of git status is still the same. I then try:

$git reset --hard master
HEAD is now at 02c9613 test commit message

And the output of git status is STILL the same.

Any ideas on how I can get rid of the supposed changes on that file?

Body:
You have to remove index.php from the "index."  Then can you checkout a different version.

git rm --cached index.php

Should do the trick.  See:

http://www.kernel.org/pub/software/scm/git/docs/git-rm.html


问:
Changing the type of a payload
I have created the following type for my Http module:

```<code>export type HttpPromise<TData> = Promise<HttpPromiseSuccess<TData>>
export type HttpPromiseSuccess<TData> = {
    config: object;
    headers: object;
    request: XMLHttpRequest;
    status: number;
    statusText: string;
    data: TData;
}
</code>```

Let's say I have the following two types:

```<code>export type User = {
    id: number;
    name: string;
    ...
}
export type ApiError = {
    error: string;
    statusCode: number;
}
</code>```

I would normally do:

```<code>const promise: HttpPromise<User> = Http.get('/api/users/1');
promise
   .then(response => {
      // response.data is now of type `User`
   });
</code>```

But my API could actually return the error type ApiError so I want the response.data to be of either type User or of type ApiError. I tried

```<code>const promise: HttpPromise<User | ApiError> = Http.get('/api/users/1');
// But now response.data only contains the union of the two type
</code>```

I also tried to do

```<code>const promise: HttpPromise<User> = Http.get('/api/users/1');
promise
   .then(response => {
       if ('error' in response.data) {
           const payload = response.data as ApiError;
       }
   });
</code>```

But this cannot do the casting. What are my options? Unfortunately I do not have control over the API; the API will always return a 200 but if the payload contains error, then it will have a statusCode that contains the code.

答:
You can use a user defined typeguard.

The typeguard itself looks like this:

```<code>const isError = <T>(response: T | ApiError): response is ApiError => {
    return !!(response as ApiError).data.error;
};
</code>```

This will return a boolean - true if response is an Error, or false if it is not.  Your request handler can then be:

```<code>const promise: HttpPromise<User | ApiError> = Http.get('/api/users/1');
promise
    .then(response => {
        if (isError(response)) {
            // response typed as ApiError
        } else {
            // response typed as User
        }
    });
</code>```

Because the typeguard is generic, then this will also work with other response types:

```<code>const promise: HttpPromise<BlogPost | ApiError> = Http.get('/api/users/1');
promise
    .then(response => {
        if (isError(response)) {
            // response typed as ApiError
        } else {
            // response typed as BlogPost
        }
    });
</code>```

Title: Changing the type of a payload

Body:
I have created the following type for my Http module:

export type HttpPromise<TData> = Promise<HttpPromiseSuccess<TData>>
export type HttpPromiseSuccess<TData> = {
    config: object;
    headers: object;
    request: XMLHttpRequest;
    status: number;
    statusText: string;
    data: TData;
}

Let's say I have the following two types:

export type User = {
    id: number;
    name: string;
    ...
}
export type ApiError = {
    error: string;
    statusCode: number;
}

I would normally do:

const promise: HttpPromise<User> = Http.get('/api/users/1');
promise
   .then(response => {
      // response.data is now of type `User`
   });

But my API could actually return the error type ApiError so I want the response.data to be of either type User or of type ApiError. I tried

const promise: HttpPromise<User | ApiError> = Http.get('/api/users/1');
// But now response.data only contains the union of the two type

I also tried to do

const promise: HttpPromise<User> = Http.get('/api/users/1');
promise
   .then(response => {
       if ('error' in response.data) {
           const payload = response.data as ApiError;
       }
   });

But this cannot do the casting. What are my options? Unfortunately I do not have control over the API; the API will always return a 200 but if the payload contains error, then it will have a statusCode that contains the code.

Body:
You can use a user defined typeguard.

The typeguard itself looks like this:

const isError = <T>(response: T | ApiError): response is ApiError => {
    return !!(response as ApiError).data.error;
};

This will return a boolean - true if response is an Error, or false if it is not.  Your request handler can then be:

const promise: HttpPromise<User | ApiError> = Http.get('/api/users/1');
promise
    .then(response => {
        if (isError(response)) {
            // response typed as ApiError
        } else {
            // response typed as User
        }
    });

Because the typeguard is generic, then this will also work with other response types:

const promise: HttpPromise<BlogPost | ApiError> = Http.get('/api/users/1');
promise
    .then(response => {
        if (isError(response)) {
            // response typed as ApiError
        } else {
            // response typed as BlogPost
        }
    });