答:
```<code>static void Main()
{
    var randomCrap = new List<Object>
    {
        1, "two",
        new List<object> { 3, 4 },
        5, 6,
        new List<object> {
            new List<object> { 7, 8, "nine" },
        },
    };

    randomCrap.PrintAll();
}
</code>```

Output:

```<code>1
two
3
4
5
6
7
8
nine
</code>```

Using this:

```<code>public static class Extensions
{
    public static void PrintAll(this Object root)
    {
        foreach (var x in root.SelectAll())
        {
            Console.WriteLine(x);
        }
    }

    public static IEnumerable<Object> SelectAll(this object o)
    {
        //  Thank you, eocron
        if (o is String)
        {
            yield return o;
        }
        else if (o is IEnumerable)
        {
            var e = o as IEnumerable;
            foreach (var child in e)
            {
                foreach (var child2 in child.SelectAll())
                    yield return child2;
            }
        }
        else
        {
            yield return o;
        }
    }
}
</code>```

Title: How do you iterate through a mixed List<t> and print contents to console in C#?

Body:
static void Main()
{
    var randomCrap = new List<Object>
    {
        1, "two",
        new List<object> { 3, 4 },
        5, 6,
        new List<object> {
            new List<object> { 7, 8, "nine" },
        },
    };

    randomCrap.PrintAll();
}

Output:

1
two
3
4
5
6
7
8
nine

Using this:

public static class Extensions
{
    public static void PrintAll(this Object root)
    {
        foreach (var x in root.SelectAll())
        {
            Console.WriteLine(x);
        }
    }

    public static IEnumerable<Object> SelectAll(this object o)
    {
        //  Thank you, eocron
        if (o is String)
        {
            yield return o;
        }
        else if (o is IEnumerable)
        {
            var e = o as IEnumerable;
            foreach (var child in e)
            {
                foreach (var child2 in child.SelectAll())
                    yield return child2;
            }
        }
        else
        {
            yield return o;
        }
    }
}


来源: stackexchange

问:
C++ how to check if among N objects some of them are equal
I have some C++ objects and I would like to check if some of them are equal.

```<code>bool IsEqual(const Board& b)
{
    if( b.From() != from_ )
        return false;

    if (b.To() != to_ )
        return false;

    if( b.Selection() != selection_ )
        return false;

    return true;
}
</code>```

My objects consist of some integers ( from_, to_, selection_) and the class offers the IsEqual method to compare two objects.

calling obj1.IsEqual(obj2) returns true if both objects have the same values.

However how do I compare N objects? Is it possible to push_back objects to an std::vector<Board> and use std::unique?

答:
Is it possible to push_back objects to an std::vector and use std::unique?

Yes it is possible, but that would require you to sort your vector first and then use std::unique using the same criteria as you used for sort. Note std::sort and std::unqiue require strict weak ordering as described in Compare concept. Your IsEqual function does not satisfy that requirement.

ContentLicense: CC BY-SA 3.0

Body:
I have some C++ objects and I would like to check if some of them are equal.

bool IsEqual(const Board& b)
{
    if( b.From() != from_ )
        return false;

    if (b.To() != to_ )
        return false;

    if( b.Selection() != selection_ )
        return false;

    return true;
}

My objects consist of some integers ( from_, to_, selection_) and the class offers the IsEqual method to compare two objects.

calling obj1.IsEqual(obj2) returns true if both objects have the same values.

However how do I compare N objects? Is it possible to push_back objects to an std::vector<Board> and use std::unique?


问:
Password Encryption Android, PHP

UPDATED:

I have my android app working fine with plain text password until now. I am trying to hash the password as next step. Cant find what the error is.

I am very sure that the communication is fine with plain text passwords.
I verified that the hashed value is getting stored in the DB properly(used varchar(80) for this attribute in the DB).

Please help.

Register.php

```<code>    <?php
include("config.php");

session_start();

// username and password sent from form

$firstName = mysqli_real_escape_string($db,$_POST["firstName"]);

$lastName = mysqli_real_escape_string($db,$_POST["lastName"]);

$email = mysqli_real_escape_string($db,$_POST["email"]);

$myusername = mysqli_real_escape_string($db,$_POST["username"]);

$mypassword = mysqli_real_escape_string($db,$_POST["password"]);

$passwordhash = password_hash($mypassword, PASSWORD_DEFAULT);

$sql = "INSERT into user VALUES ('$firstName', '$lastName', '$myusername', '$email', '$passwordhash')";

$result = mysqli_query($db,$sql);

if($result)
{

    echo "success";

}else{

    echo "failed";

}

?>
</code>```

Login.php

```<code>    <?php
include("config.php");

session_start();

// username and password sent from form

$myusername = mysqli_real_escape_string($db,$_POST["username"]);

$mypassword = mysqli_real_escape_string($db,$_POST["password"]);

$sql = "SELECT * FROM user WHERE username = '$myusername'";

$result = mysqli_query($db,$sql);
$count = mysqli_num_rows($result);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$hash = $row['password'];

// If result matched $myusername and $mypassword, table row must be 1 row

if(true === password_verify($mypassword,$hash)) {

    echo "success". "\n";

    echo $row['firstName'] . "\n";

    echo $row['lastName'] . "\n";

    echo $row['username'] . "\n";

    echo $row['email'] . "\n";

}
else{

    echo " Incorrect Login. Please try again ";
}

?>
</code>```

答:
you gotta use another php function called password_verify, it will verify that a particular password was used to create the hash.

http://php.net/manual/en/function.password-verify.php

Title: Password Encryption Android, PHP

Body:
UPDATED:

I have my android app working fine with plain text password until now. I am trying to hash the password as next step. Cant find what the error is.

I am very sure that the communication is fine with plain text passwords.
I verified that the hashed value is getting stored in the DB properly(used varchar(80) for this attribute in the DB).

Please help.

Register.php

    <?php
include("config.php");

session_start();

// username and password sent from form

$firstName = mysqli_real_escape_string($db,$_POST["firstName"]);

$lastName = mysqli_real_escape_string($db,$_POST["lastName"]);

$email = mysqli_real_escape_string($db,$_POST["email"]);

$myusername = mysqli_real_escape_string($db,$_POST["username"]);

$mypassword = mysqli_real_escape_string($db,$_POST["password"]);

$passwordhash = password_hash($mypassword, PASSWORD_DEFAULT);

$sql = "INSERT into user VALUES ('$firstName', '$lastName', '$myusername', '$email', '$passwordhash')";

$result = mysqli_query($db,$sql);

if($result)
{

    echo "success";

}else{

    echo "failed";

}

?>

Login.php

    <?php
include("config.php");

session_start();

// username and password sent from form

$myusername = mysqli_real_escape_string($db,$_POST["username"]);

$mypassword = mysqli_real_escape_string($db,$_POST["password"]);

$sql = "SELECT * FROM user WHERE username = '$myusername'";

$result = mysqli_query($db,$sql);
$count = mysqli_num_rows($result);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$hash = $row['password'];

// If result matched $myusername and $mypassword, table row must be 1 row

if(true === password_verify($mypassword,$hash)) {

    echo "success". "\n";

    echo $row['firstName'] . "\n";

    echo $row['lastName'] . "\n";

    echo $row['username'] . "\n";

    echo $row['email'] . "\n";

}
else{

    echo " Incorrect Login. Please try again ";
}

?>


问:
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>```

答:
In addition to the above answers, I also found this works: </p>

```<code>class ExampleConstructor<T> {
  final Function _distance;

  ExampleConstructor(num this._distance(T a, T b))
}
</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:
In addition to the above answers, I also found this works:

class ExampleConstructor<T> {
  final Function _distance;

  ExampleConstructor(num this._distance(T a, T b))
}


问:
Entity Framework 6.1.1 - How to check if property is ignored from an entity in SaveChanges method
Scenario:

I have following set of entities:

```<code>public interface IAuditable
{
    DateTime? CreatedDate { get; set; }
    string CreatedBy {get;set;}
    string LastModifiedBy {get;set;}
    DateTime? LastModifiedDate {get;set;}
}

public abstract class BaseEntity: IAuditable
{
    public int ID { get; set; }
    public DateTime? CreatedDate { get; set; }
    public string CreatedBy {get;set;}
    public string LastModifiedBy {get;set;}
    public DateTime? LastModifiedDate {get;set;}
}

public class Product: BaseEntity
{
    public string Name { get; set; }
}

public class Order : BaseEntity
{
    public int ProductID { get; set; }
    public int Qty { get; set; }
}
</code>```

and following DbContext:

```<code>public class AuditDbContext : DbContext
    {
        public AuditDbContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
        }

        public DbSet<Product> Products { get; set; }
        public DbSet<Order> Orders { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Products>()
            .Ignore(t => t.CreatedDate);

            modelBuilder.Entity<Order>()
            .Ignore(t => t.LastModifiedBy);
            modelBuilder.Entity<Order>()
            .Ignore(t => t.LastModifiedDate);
        }

        public override int SaveChanges()
        {
            SetAuditableProperties();
            return base.SaveChanges();
        }

        private void SetAuditableProperties()
        {
            foreach (var auditableEntity in ChangeTracker.Entries<IAuditable>())
            {
                if (auditableEntity.State == EntityState.Added ||
                    auditableEntity.State == EntityState.Modified)
                {
                    string userName = "ABC";
                    DateTime dateTimeNow = DateTime.Now;

                    auditableEntity.Entity.LastModifiedDate = dateTimeNow;
                    auditableEntity.Entity.LastModifiedBy = userName;

                    if (auditableEntity.State == EntityState.Added)
                    {
                        auditableEntity.Entity.CreatedDate = dateTimeNow;
                        auditableEntity.Entity.CreatedBy = userName;
                    }
                    else
                    {
                        auditableEntity.Property(p => p.CreatedDate).IsModified = false; //TODO: Set this property if mapped otherwise dont execute this line
                        auditableEntity.Property(p => p.CreatedBy).IsModified = false; //TODO: Set this property if mapped otherwise dont execute this line
                    }
                }
            }
        }
    }
</code>```

Observe I'm Ignoring some properties form entities in OnModelCreating and setting Auditable properties inside SaveChanges method by overriding it. Now, when I try to create new entity it works as expected but when I try to update an existing entity it throws exception.

Problem:

Let's say I try to update Product entity it throws following exceptions:

"Member 'IsModified' cannot be called for property 'CreatedDate' on entity of type 'Products' because the property is not part of the Entity Data Model".

Same is true for 'Order' entity but for 'LastModifiedBy' and 'LastModifiedDate' properties.

How can I check if a property is ignored from entity inside 'SetAuditableProperties' method? So that I can set 'IsModified' accordingly.

P.S. I can find out [NotMapped] properties but when I use the ModelBuilder to ignore a column, I cannot detect these.

答:
The EF6 is over encapsulated and most of the metadata is hidden inside internal classes/members.

I see two relatively easy ways to resolve your issue.

Generally you could use DbEntityEntry<TEntity>.CurrentValues property of type DbPropertyValues, which in turn has PropertyNames property of type IEnumerable<string>, which can be used to check for existence of a property name (the non mapped properties are not included in that list):

```<code>if (auditableEntity.CurrentValues.PropertyNames.Contains(nameof(IAuditable.CreatedDate)))
    auditableEntity.Property(p => p.CreatedDate).IsModified = false;
if (auditableEntity.CurrentValues.PropertyNames.Contains(nameof(IAuditable.CreatedBy)))
    auditableEntity.Property(p => p.CreatedBy).IsModified = false;
</code>```

Another way for this particular case is to utilize the fact that the Property method returns DbPropertyEntry instance with IsModified == false for ignored properties (only the setter throws exception):

```<code>if (auditableEntity.Property(p => p.CreatedDate).IsModified)
    auditableEntity.Property(p => p.CreatedDate).IsModified = false;
if (auditableEntity.Property(p => p.CreatedBy).IsModified)
    auditableEntity.Property(p => p.CreatedBy).IsModified = false;
</code>```

Of course you could encapsulate both logics in a custom (extension) methods.

Body:
Scenario:

I have following set of entities:

public interface IAuditable
{
    DateTime? CreatedDate { get; set; }
    string CreatedBy {get;set;}
    string LastModifiedBy {get;set;}
    DateTime? LastModifiedDate {get;set;}
}

public abstract class BaseEntity: IAuditable
{
    public int ID { get; set; }
    public DateTime? CreatedDate { get; set; }
    public string CreatedBy {get;set;}
    public string LastModifiedBy {get;set;}
    public DateTime? LastModifiedDate {get;set;}
}

public class Product: BaseEntity
{
    public string Name { get; set; }
}

public class Order : BaseEntity
{
    public int ProductID { get; set; }
    public int Qty { get; set; }
}

and following DbContext:

public class AuditDbContext : DbContext
    {
        public AuditDbContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
        }

        public DbSet<Product> Products { get; set; }
        public DbSet<Order> Orders { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Products>()
            .Ignore(t => t.CreatedDate);

            modelBuilder.Entity<Order>()
            .Ignore(t => t.LastModifiedBy);
            modelBuilder.Entity<Order>()
            .Ignore(t => t.LastModifiedDate);
        }

        public override int SaveChanges()
        {
            SetAuditableProperties();
            return base.SaveChanges();
        }

        private void SetAuditableProperties()
        {
            foreach (var auditableEntity in ChangeTracker.Entries<IAuditable>())
            {
                if (auditableEntity.State == EntityState.Added ||
                    auditableEntity.State == EntityState.Modified)
                {
                    string userName = "ABC";
                    DateTime dateTimeNow = DateTime.Now;

                    auditableEntity.Entity.LastModifiedDate = dateTimeNow;
                    auditableEntity.Entity.LastModifiedBy = userName;

                    if (auditableEntity.State == EntityState.Added)
                    {
                        auditableEntity.Entity.CreatedDate = dateTimeNow;
                        auditableEntity.Entity.CreatedBy = userName;
                    }
                    else
                    {
                        auditableEntity.Property(p => p.CreatedDate).IsModified = false; //TODO: Set this property if mapped otherwise dont execute this line
                        auditableEntity.Property(p => p.CreatedBy).IsModified = false; //TODO: Set this property if mapped otherwise dont execute this line
                    }
                }
            }
        }
    }

Observe I'm Ignoring some properties form entities in OnModelCreating and setting Auditable properties inside SaveChanges method by overriding it. Now, when I try to create new entity it works as expected but when I try to update an existing entity it throws exception.

Problem:

Let's say I try to update Product entity it throws following exceptions:

"Member 'IsModified' cannot be called for property 'CreatedDate' on entity of type 'Products' because the property is not part of the Entity Data Model".

Same is true for 'Order' entity but for 'LastModifiedBy' and 'LastModifiedDate' properties.

How can I check if a property is ignored from entity inside 'SetAuditableProperties' method? So that I can set 'IsModified' accordingly.

P.S. I can find out [NotMapped] properties but when I use the ModelBuilder to ignore a column, I cannot detect these.

Body:
The EF6 is over encapsulated and most of the metadata is hidden inside internal classes/members.

I see two relatively easy ways to resolve your issue.

Generally you could use DbEntityEntry<TEntity>.CurrentValues property of type DbPropertyValues, which in turn has PropertyNames property of type IEnumerable<string>, which can be used to check for existence of a property name (the non mapped properties are not included in that list):

if (auditableEntity.CurrentValues.PropertyNames.Contains(nameof(IAuditable.CreatedDate)))
    auditableEntity.Property(p => p.CreatedDate).IsModified = false;
if (auditableEntity.CurrentValues.PropertyNames.Contains(nameof(IAuditable.CreatedBy)))
    auditableEntity.Property(p => p.CreatedBy).IsModified = false;

Another way for this particular case is to utilize the fact that the Property method returns DbPropertyEntry instance with IsModified == false for ignored properties (only the setter throws exception):

if (auditableEntity.Property(p => p.CreatedDate).IsModified)
    auditableEntity.Property(p => p.CreatedDate).IsModified = false;
if (auditableEntity.Property(p => p.CreatedBy).IsModified)
    auditableEntity.Property(p => p.CreatedBy).IsModified = false;

Of course you could encapsulate both logics in a custom (extension) methods.


问:
Center three div containers next to each other
I want three divs to be centered in the mid. In the end it should look like this

now my problem. In my css I used the float keyword but it seems this does not work for sure. The divs still split up.

As you can see in the following code example the containers are getting weird.

Would be awesome if someone could help me out there!

#selectionElementContainer {
  height: 70%;
  width: 100%;
  margin-top: 50px;
}

#selectionElementLeft {
  float: left;
}

#selectionElementCenter {
  margin: 0 auto;
}

#selectionElementRight {
  float: right;
}

.selectionElementImage {
  cursor: default;
  text-align: center;
  margin-top: 10px;
}

.selectionElementHeader {
  cursor: default;
  text-align: center;
  font-size: 30px;
  margin-top: 30px;
  color: #333f4b;
}

.selectionElementText {
  cursor: default;
  text-align: center;
  margin-top: 20px;
  font-size: 18px;
  color: #4c545c;
}

.selectionElementLinkContainer {
  cursor: default;
  margin-top: 10px;
}

.selectionElementBtn {
  text-decoration: none;
  text-align: center;
  cursor: pointer;
  border: none;
  font-size: 18px;
  background-color: white;
  color: #1bbee7;
  transition: 0.5s;
}

.selectionElementBtn:hover {
  color: #a4d662;
  transition: 0.5s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div id="selectionElementContainer">
      <div id="selectionElementLeft">
        <div class="selectionElementImage">
          <img src="bild">
        </div>
        <div class="selectionElementHeader">
          Title
        </div>
        <div class="selectionElementText">
          Text
        </div>
        <div class="selectionElementLink">
          <button class="selectionElementBtn">Link</button>
        </div>
      </div>
      <div id="selectionElementCenter">
        <div class="selectionElementImage">
          <img src="bild">
        </div>
        <div class="selectionElementHeader">
          Title
        </div>
        <div class="selectionElementText">
          Text
        </div>
        <div class="selectionElementLink">
          <button class="selectionElementBtn">Link</button>
        </div>
      </div>
      <div id="selectionElementRight">
        <div class="selectionElementImage">
          <img src="bild">
        </div>
        <div class="selectionElementHeader">
          Title
        </div>
        <div class="selectionElementText">
          Text
        </div>
        <div class="selectionElementLinkContainer">
          <button class="selectionElementBtn">Link</button>
        </div>
      </div>
    </div></code>```

答:
You can keep your existing CSS and just change the order of your divs so that it's left, right, center. This way the left and right divs will be positioned to the left and right sides respectively, and the center div will float up between them.

#selectionElementContainer {
  height: 70%;
  width: 100%;
  margin-top: 50px;
  overflow:auto;
}

#selectionElementLeft {
  float: left;
}

#selectionElementCenter {
  margin: 0 auto;
}

#selectionElementRight {
  float: right;
}

.selectionElementImage {
  cursor: default;
  text-align: center;
  margin-top: 10px;
}

.selectionElementHeader {
  cursor: default;
  text-align: center;
  font-size: 30px;
  margin-top: 30px;
  color: #333f4b;
}

.selectionElementText {
  cursor: default;
  text-align: center;
  margin-top: 20px;
  font-size: 18px;
  color: #4c545c;
}

.selectionElementLinkContainer {
  cursor: default;
  margin-top: 10px;
}

.selectionElementBtn {
  text-decoration: none;
  text-align: center;
  cursor: pointer;
  border: none;
  font-size: 18px;
  background-color: white;
  color: #1bbee7;
  transition: 0.5s;
}

.selectionElementBtn:hover {
  color: #a4d662;
  transition: 0.5s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="selectionElementContainer">
  <div id="selectionElementLeft">
    <div class="selectionElementImage">
      <img src="bild">
    </div>
    <div class="selectionElementHeader">
      Title
    </div>
    <div class="selectionElementText">
      Text
    </div>
    <div class="selectionElementLink">
      <button class="selectionElementBtn">Link</button>
    </div>
  </div>

  <div id="selectionElementRight">
    <div class="selectionElementImage">
      <img src="bild">
    </div>
    <div class="selectionElementHeader">
      Title
    </div>
    <div class="selectionElementText">
      Text
    </div>
    <div class="selectionElementLinkContainer">
      <button class="selectionElementBtn">Link</button>
    </div>
  </div>
  <div id="selectionElementCenter">
    <div class="selectionElementImage">
      <img src="bild">
    </div>
    <div class="selectionElementHeader">
      Title
    </div>
    <div class="selectionElementText">
      Text
    </div>
    <div class="selectionElementLink">
      <button class="selectionElementBtn">Link</button>
    </div>
  </div>
</div></code>```

Note that I also added overflow:auto to your container div so that the container actually contains the floated divs.

Body:
I want three divs to be centered in the mid. In the end it should look like this

now my problem. In my css I used the float keyword but it seems this does not work for sure. The divs still split up.

As you can see in the following code example the containers are getting weird.

Would be awesome if someone could help me out there!

#selectionElementContainer {
  height: 70%;
  width: 100%;
  margin-top: 50px;
}

#selectionElementLeft {
  float: left;
}

#selectionElementCenter {
  margin: 0 auto;
}

#selectionElementRight {
  float: right;
}

.selectionElementImage {
  cursor: default;
  text-align: center;
  margin-top: 10px;
}

.selectionElementHeader {
  cursor: default;
  text-align: center;
  font-size: 30px;
  margin-top: 30px;
  color: #333f4b;
}

.selectionElementText {
  cursor: default;
  text-align: center;
  margin-top: 20px;
  font-size: 18px;
  color: #4c545c;
}

.selectionElementLinkContainer {
  cursor: default;
  margin-top: 10px;
}

.selectionElementBtn {
  text-decoration: none;
  text-align: center;
  cursor: pointer;
  border: none;
  font-size: 18px;
  background-color: white;
  color: #1bbee7;
  transition: 0.5s;
}

.selectionElementBtn:hover {
  color: #a4d662;
  transition: 0.5s;
}

          Title

          Text

          <button class="selectionElementBtn">Link</button>

          Title

          Text

          <button class="selectionElementBtn">Link</button>

          Title

          Text

          <button class="selectionElementBtn">Link</button>

Body:
You can keep your existing CSS and just change the order of your divs so that it's left, right, center. This way the left and right divs will be positioned to the left and right sides respectively, and the center div will float up between them.

#selectionElementContainer {
  height: 70%;
  width: 100%;
  margin-top: 50px;
  overflow:auto;
}

#selectionElementLeft {
  float: left;
}

#selectionElementCenter {
  margin: 0 auto;
}

#selectionElementRight {
  float: right;
}

.selectionElementImage {
  cursor: default;
  text-align: center;
  margin-top: 10px;
}

.selectionElementHeader {
  cursor: default;
  text-align: center;
  font-size: 30px;
  margin-top: 30px;
  color: #333f4b;
}

.selectionElementText {
  cursor: default;
  text-align: center;
  margin-top: 20px;
  font-size: 18px;
  color: #4c545c;
}

.selectionElementLinkContainer {
  cursor: default;
  margin-top: 10px;
}

.selectionElementBtn {
  text-decoration: none;
  text-align: center;
  cursor: pointer;
  border: none;
  font-size: 18px;
  background-color: white;
  color: #1bbee7;
  transition: 0.5s;
}

.selectionElementBtn:hover {
  color: #a4d662;
  transition: 0.5s;
}

<div id="selectionElementContainer">
  <div id="selectionElementLeft">
    <div class="selectionElementImage">
      <img src="bild">
    </div>
    <div class="selectionElementHeader">
      Title
    </div>
    <div class="selectionElementText">
      Text
    </div>
    <div class="selectionElementLink">
      <button class="selectionElementBtn">Link</button>
    </div>
  </div>

  <div id="selectionElementRight">
    <div class="selectionElementImage">
      <img src="bild">
    </div>
    <div class="selectionElementHeader">
      Title
    </div>
    <div class="selectionElementText">
      Text
    </div>
    <div class="selectionElementLinkContainer">
      <button class="selectionElementBtn">Link</button>
    </div>
  </div>
  <div id="selectionElementCenter">
    <div class="selectionElementImage">
      <img src="bild">
    </div>
    <div class="selectionElementHeader">
      Title
    </div>
    <div class="selectionElementText">
      Text
    </div>
    <div class="selectionElementLink">
      <button class="selectionElementBtn">Link</button>
    </div>
  </div>
</div>

Note that I also added overflow:auto to your container div so that the container actually contains the floated divs.


问:
Using npm behind corporate proxy .pac
I need to download several packages through npm but our corporate proxy configuration is a .pac file (i'm on windows)

I have already tried

```<code>npm config set proxy http://mydomain\username:password@1.2.3.4:8181/proxy.pac
npm config set https-proxy http://mydomain\username:password@1.2.3.4:8181/proxy.pac
</code>```

or

```<code>npm config set proxy http://1.2.3.4:8181/proxy.pac
npm config set https-proxy http://1.2.3.4:8181/proxy.pac
</code>```

but it doesn't work...

any suggestion? thanks

答:
You must use "npm config set http-proxy"

use:

```<code>npm config set http-proxy http://1.2.3.4:8181
npm config set https-proxy http://1.2.3.4:8181
</code>```

ContentLicense: CC BY-SA 4.0

Title: Using npm behind corporate proxy .pac

Body:
I need to download several packages through npm but our corporate proxy configuration is a .pac file (i'm on windows)

I have already tried

npm config set proxy http://mydomain\username:password@1.2.3.4:8181/proxy.pac
npm config set https-proxy http://mydomain\username:password@1.2.3.4:8181/proxy.pac

or

npm config set proxy http://1.2.3.4:8181/proxy.pac
npm config set https-proxy http://1.2.3.4:8181/proxy.pac

but it doesn't work...

any suggestion? thanks

Body:
You must use "npm config set http-proxy"

use:

npm config set http-proxy http://1.2.3.4:8181
npm config set https-proxy http://1.2.3.4:8181


答:
You can try a home cooked code as below:

put objects in an array

compare each object to the rest of objects in array in the loop

The loop will look like:

```<code>A[] arr = {a, b, c, d};
int counter = 0;
for (int i=0; i < arr.length -1 ; i++) {
  for (int j=i+1; j < arr.length; j++) {
     if (arr[i].IsEqual(arr[j])) counter++;
  }
}
printf("There is %d objects that are equal", counter);
</code>```

Title: C++ how to check if among N objects some of them are equal

Body:
You can try a home cooked code as below:

put objects in an array

compare each object to the rest of objects in array in the loop

The loop will look like:

A[] arr = {a, b, c, d};
int counter = 0;
for (int i=0; i < arr.length -1 ; i++) {
  for (int j=i+1; j < arr.length; j++) {
     if (arr[i].IsEqual(arr[j])) counter++;
  }
}
printf("There is %d objects that are equal", counter);


问:
Spark Error Running "stats()": could not find implicit value for parameter num: Numeric[Double]
I'm learning spark/scala after just writing some MapReduce jobs.

I wrote some java beans to help me parse a file in HDFS and I want to use that to help speed up my progress in spark.

I've had success loading my file and creating an array of my java bean objects:

```<code>val input = sc.textFile("hdfs://host:port/user/test/path/out")
import my.package.Record
val clust_recs = clv_input.map(line => new my.package.Record(line))
clust_recs.map(rec => rec.getPremium()).stats()
</code>```

But the last line creates this error:

<console>:46: error: could not find implicit value for parameter num: Numeric[Double]

I've tested that the values in this field are all valid, so I am pretty sure I don't have any null values that could be causing this error.

Here is an example of values:

```<code>val dblArray = clust_recs.map(rec => rec.getPremium()).filter(!isNaN(_))
dblArray.take(10)
</code>```

OUTPUT:

```<code>res82: Array[Double] = Array(1250.6, 433.72, 567.07, 219.24, 310.32, 2173.48, 195.0, 697.94, 711.46, 42.718050000000005)
</code>```

I'm at a loss to how to resolve this error and wondering if I should just abandon the concept of using a JavaBean object that I've already created.

答:
You can only expect stats operator available on a RDD[T] by implicit conversions for RDD[Double] or RDD[T] where T can be converted to Numeric[T] (see the code):

```<code>implicit def doubleRDDToDoubleRDDFunctions(rdd: RDD[Double]): DoubleRDDFunctions = {
  new DoubleRDDFunctions(rdd)
}

implicit def numericRDDToDoubleRDDFunctions[T](rdd: RDD[T])(implicit num: Numeric[T])
  : DoubleRDDFunctions = {
  new DoubleRDDFunctions(rdd.map(x => num.toDouble(x)))
}
</code>```

The implicit conversions are also mentioned in the scaladoc of DoubleRDDFunctions:

Extra functions available on RDDs of Doubles through an implicit conversion.

The point is that the following line does not give you RDD[Double], but something else.

```<code>clust_recs.map(rec => rec.getPremium())
</code>```

That's the reason for the following compilation error:

error: could not find implicit value for parameter num: Numeric[Double]

The Scala compiler can't find Numeric[Double] implicit conversion that is called num.

```<code>implicit def numericRDDToDoubleRDDFunctions[T](rdd: RDD[T])(implicit num: Numeric[T])
  : DoubleRDDFunctions = {
  new DoubleRDDFunctions(rdd.map(x => num.toDouble(x)))
}
</code>```

I can only guess that the Double is Java's java.lang.Double not Scala's Double and hence the compilation error.

Body:
I'm learning spark/scala after just writing some MapReduce jobs.

I wrote some java beans to help me parse a file in HDFS and I want to use that to help speed up my progress in spark.

I've had success loading my file and creating an array of my java bean objects:

val input = sc.textFile("hdfs://host:port/user/test/path/out")
import my.package.Record
val clust_recs = clv_input.map(line => new my.package.Record(line))
clust_recs.map(rec => rec.getPremium()).stats()

But the last line creates this error:

<console>:46: error: could not find implicit value for parameter num: Numeric[Double]

I've tested that the values in this field are all valid, so I am pretty sure I don't have any null values that could be causing this error.

Here is an example of values:

val dblArray = clust_recs.map(rec => rec.getPremium()).filter(!isNaN(_))
dblArray.take(10)

OUTPUT:

res82: Array[Double] = Array(1250.6, 433.72, 567.07, 219.24, 310.32, 2173.48, 195.0, 697.94, 711.46, 42.718050000000005)

I'm at a loss to how to resolve this error and wondering if I should just abandon the concept of using a JavaBean object that I've already created.

Body:
You can only expect stats operator available on a RDD[T] by implicit conversions for RDD[Double] or RDD[T] where T can be converted to Numeric[T] (see the code):

implicit def doubleRDDToDoubleRDDFunctions(rdd: RDD[Double]): DoubleRDDFunctions = {
  new DoubleRDDFunctions(rdd)
}

implicit def numericRDDToDoubleRDDFunctions[T](rdd: RDD[T])(implicit num: Numeric[T])
  : DoubleRDDFunctions = {
  new DoubleRDDFunctions(rdd.map(x => num.toDouble(x)))
}

The implicit conversions are also mentioned in the scaladoc of DoubleRDDFunctions:

Extra functions available on RDDs of Doubles through an implicit conversion.

The point is that the following line does not give you RDD[Double], but something else.

clust_recs.map(rec => rec.getPremium())

That's the reason for the following compilation error:

error: could not find implicit value for parameter num: Numeric[Double]

The Scala compiler can't find Numeric[Double] implicit conversion that is called num.

implicit def numericRDDToDoubleRDDFunctions[T](rdd: RDD[T])(implicit num: Numeric[T])
  : DoubleRDDFunctions = {
  new DoubleRDDFunctions(rdd.map(x => num.toDouble(x)))
}

I can only guess that the Double is Java's java.lang.Double not Scala's Double and hence the compilation error.


问:
webpack font can't resolve
I am trying to include font files in my webpack with a bit of difficulty.

font.css

```<code>@font-face {
    font-family: 'LatoBlack';
    src: url('./font/Lato-Black.woff2') format('woff2'), /* Modern Browsers */
         url('./font/Lato-Black.woff') format('woff'), /* Modern Browsers */
         url('./font/Lato-Black.ttf') format('truetype');
    font-style: normal;
    font-weight: normal;
    text-rendering: optimizeLegibility;
}
</code>```

Webpack.base.Config

```<code>module.exports = {
  module: {
    loaders: [
      { test: /\.svg$/, loader: 'url?limit=65000&mimetype=image/svg+xml&name=./font/[name].[ext]' },
      { test: /\.woff$/, loader: 'url?limit=65000&mimetype=application/font-woff&name=./font/[name].[ext]' },
      { test: /\.woff2$/, loader: 'url?limit=65000&mimetype=application/font-woff2&name=./font/[name].[ext]' },
      { test: /\.[ot]tf$/, loader: 'url?limit=65000&mimetype=application/octet-stream&name=./font/[name].[ext]' },
      { test: /\.eot$/, loader: 'url?limit=65000&mimetype=application/vnd.ms-fontobject&name=./font/[name].[ext]' }
    ]
  }
};
</code>```

Structure

webpack.prod.conf

```<code>module.exports = new Config().extend('./webpack.base.config.js').merge({
  entry: [
    './src/index.js'
  ],
  devtool: 'eval',
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production')
      }
    })
  ],
  output: {
    filename: 'main.js',
    path: path.join(__dirname, 'app/www'),
    publicPath: '/app/www'
  },
});
</code>```

Error

```<code>ERROR in ./~/css-loader?{"modules":true,"sourceMap":true,"importLoaders":2,"localIdentName":"[local]_[hash:base64:5]"}!./~/postcss-loader?sourceMap&parser=postcss-scss!./src/components/shared/main.css
Module not found: Error: Can't resolve './font/Lato-ThinItalic.ttf' in '/var/www/kindred/src/components/shared'
 @ ./~/css-loader?{"modules":true,"sourceMap":true,"importLoaders":2,"localIdentName":"[local]_[hash:base64:5]"}!./~/postcss-loader?sourceMap&parser=postcss-scss!./src/components/shared/main.css 6:5744-5781
 @ ./src/components/shared/main.css
 @ ./src/index.js
 @ multi ./src/index.js
</code>```

webpack.base.config

```<code>/* eslint-disable filenames/match-regex, import/no-commonjs, import/unambiguous */

const path = require('path');
const {environment} = require('webpack-config');

module.exports = {
  module: {
    loaders: [
      {
        test: /dashjs\/dist\/.*/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]'
        }
      },
      {
        test: /\.js$/,
        exclude: /node_modules\/.*/,
        use: ['babel-loader']
      },
      {
        test: /\.(jpg|png)$/,
        loader: 'url?limit=25000'
      },
      {
        test: /\.svg$/,
        use: ['babel-loader', 'svg-react-loader']
      },
      {
        test: /\.css$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader?sourceMap',
            query: {
              modules: true,
              sourceMap: true,
              importLoaders: 2,
              localIdentName: environment.get('cssIdent')
            }
          },
          'postcss-loader?sourceMap&parser=postcss-scss'
        ],
      },
      // Font Definitions
      { test: /\.svg$/, loader: 'url?limit=65000&mimetype=image/svg+xml&name=./font/[name].[ext]' },
      { test: /\.woff$/, loader: 'url?limit=65000&mimetype=application/font-woff&name=./font/[name].[ext]' },
      { test: /\.woff2$/, loader: 'url?limit=65000&mimetype=application/font-woff2&name=./font/[name].[ext]' },
      { test: /\.[ot]tf$/, loader: 'url?limit=65000&mimetype=application/octet-stream&name=./font/[name].[ext]' },
      { test: /\.eot$/, loader: 'url?limit=65000&mimetype=application/vnd.ms-fontobject&name=./font/[name].[ext]' }
    ]
  }
};
</code>```

So how can I make it load? :O

答:
Due to having relative webpack is not able to find according to its current location. In the module rules add this and install file-loader

npm install --save-dev file-loader

```<code>{
        test: /\.(svg|eot|ttf|woff|woff2)$/,
        use:'file-loader',
        options: {
            name: 'images/[name].[hash].[ext]'
       }

},
</code>```

Edit:
Usually relative url can be solved in three ways

-use absolute path

-use options and set url to false

```<code>use:[
        {
            loader: 'css-loader',
            options: {url: false}
        }
    ]
</code>```

-use raw loder as it will loder url as string

```<code>use: ['raw-loader', 'css-loader'],
</code>```

Title: webpack font can't resolve

Body:
I am trying to include font files in my webpack with a bit of difficulty.

font.css

@font-face {
    font-family: 'LatoBlack';
    src: url('./font/Lato-Black.woff2') format('woff2'), /* Modern Browsers */
         url('./font/Lato-Black.woff') format('woff'), /* Modern Browsers */
         url('./font/Lato-Black.ttf') format('truetype');
    font-style: normal;
    font-weight: normal;
    text-rendering: optimizeLegibility;
}

Webpack.base.Config

module.exports = {
  module: {
    loaders: [
      { test: /\.svg$/, loader: 'url?limit=65000&mimetype=image/svg+xml&name=./font/[name].[ext]' },
      { test: /\.woff$/, loader: 'url?limit=65000&mimetype=application/font-woff&name=./font/[name].[ext]' },
      { test: /\.woff2$/, loader: 'url?limit=65000&mimetype=application/font-woff2&name=./font/[name].[ext]' },
      { test: /\.[ot]tf$/, loader: 'url?limit=65000&mimetype=application/octet-stream&name=./font/[name].[ext]' },
      { test: /\.eot$/, loader: 'url?limit=65000&mimetype=application/vnd.ms-fontobject&name=./font/[name].[ext]' }
    ]
  }
};

Structure

webpack.prod.conf

module.exports = new Config().extend('./webpack.base.config.js').merge({
  entry: [
    './src/index.js'
  ],
  devtool: 'eval',
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production')
      }
    })
  ],
  output: {
    filename: 'main.js',
    path: path.join(__dirname, 'app/www'),
    publicPath: '/app/www'
  },
});

Error

ERROR in ./~/css-loader?{"modules":true,"sourceMap":true,"importLoaders":2,"localIdentName":"[local]_[hash:base64:5]"}!./~/postcss-loader?sourceMap&parser=postcss-scss!./src/components/shared/main.css
Module not found: Error: Can't resolve './font/Lato-ThinItalic.ttf' in '/var/www/kindred/src/components/shared'
 @ ./~/css-loader?{"modules":true,"sourceMap":true,"importLoaders":2,"localIdentName":"[local]_[hash:base64:5]"}!./~/postcss-loader?sourceMap&parser=postcss-scss!./src/components/shared/main.css 6:5744-5781
 @ ./src/components/shared/main.css
 @ ./src/index.js
 @ multi ./src/index.js

webpack.base.config

/* eslint-disable filenames/match-regex, import/no-commonjs, import/unambiguous */

const path = require('path');
const {environment} = require('webpack-config');

module.exports = {
  module: {
    loaders: [
      {
        test: /dashjs\/dist\/.*/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]'
        }
      },
      {
        test: /\.js$/,
        exclude: /node_modules\/.*/,
        use: ['babel-loader']
      },
      {
        test: /\.(jpg|png)$/,
        loader: 'url?limit=25000'
      },
      {
        test: /\.svg$/,
        use: ['babel-loader', 'svg-react-loader']
      },
      {
        test: /\.css$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader?sourceMap',
            query: {
              modules: true,
              sourceMap: true,
              importLoaders: 2,
              localIdentName: environment.get('cssIdent')
            }
          },
          'postcss-loader?sourceMap&parser=postcss-scss'
        ],
      },
      // Font Definitions
      { test: /\.svg$/, loader: 'url?limit=65000&mimetype=image/svg+xml&name=./font/[name].[ext]' },
      { test: /\.woff$/, loader: 'url?limit=65000&mimetype=application/font-woff&name=./font/[name].[ext]' },
      { test: /\.woff2$/, loader: 'url?limit=65000&mimetype=application/font-woff2&name=./font/[name].[ext]' },
      { test: /\.[ot]tf$/, loader: 'url?limit=65000&mimetype=application/octet-stream&name=./font/[name].[ext]' },
      { test: /\.eot$/, loader: 'url?limit=65000&mimetype=application/vnd.ms-fontobject&name=./font/[name].[ext]' }
    ]
  }
};

So how can I make it load? :O

Body:
Due to having relative webpack is not able to find according to its current location. In the module rules add this and install file-loader

npm install --save-dev file-loader

{
        test: /\.(svg|eot|ttf|woff|woff2)$/,
        use:'file-loader',
        options: {
            name: 'images/[name].[hash].[ext]'
       }

},

Edit:
Usually relative url can be solved in three ways

-use absolute path

-use options and set url to false

use:[
        {
            loader: 'css-loader',
            options: {url: false}
        }
    ]

-use raw loder as it will loder url as string

use: ['raw-loader', 'css-loader'],


问:
Matplotlib and unit tests
I have a GTK application that draws some plots of some live data. The code is split so that one method deals with creating the plots and another one with updating the data and re-drawing said plots.

Clearly running the application allows me to see if the plots are sensible and look how I want them to look. However, this is a mechanical and visual test.

Is there a way to unit test this?

I could set a test method and mock all the calls to matplotlib then check that said calls were made. However, this feels like testing the implementation and not behaviour.

答:
This is coming two years late, but Matplotlib (now?) seems to have a webpage that gives developer's tips for testing.

They also talk about how to write an image comparison test, for example, which might be what you're looking for.

Title: Matplotlib and unit tests


问:
Deleting from array javascript
I am looping through an array and displaying it on the screen. I have a problem, though. I tried to add a function that when you click on the text, it deletes that clicked text. Here is my code:

```<code>var div = document.querySelector('div');
var array = [
"Banana",
"Chocolate",
"Oranges"
];

for(let i = 0; i < array.length; i++){

var p = document.createElement('p');
p.textContent = array[i];
div.appendChild(p);

p.onclick = function(){

    array.splice(array[i], 1);
    console.log(array);
}

}
</code>```

When I click on it, it deletes the item from the array and logs it to the console. But it doesn't show on the screen. Any help?

Thank you,
Scratch Cat

答:
Here you go:

```<code>var div = document.querySelector('div');
var array = [
"Banana",
"Chocolate",
"Oranges"
];

for (let i = 0; i < array.length; i++) {
  let p = document.createElement('p'); //note the block scoping
  p.textContent = array[i];
  div.appendChild(p);

  p.onclick = function() {
    array.splice(array.indexOf(this), 1); //splice wants an index...
    this.remove(); //remove el from document tree
    console.log(array);
  }

}
</code>```

https://jsfiddle.net/wt0fux3f/6/

Title: Deleting from array javascript

Body:
I am looping through an array and displaying it on the screen. I have a problem, though. I tried to add a function that when you click on the text, it deletes that clicked text. Here is my code:

var div = document.querySelector('div');
var array = [
"Banana",
"Chocolate",
"Oranges"
];

for(let i = 0; i < array.length; i++){

var p = document.createElement('p');
p.textContent = array[i];
div.appendChild(p);

p.onclick = function(){

    array.splice(array[i], 1);
    console.log(array);
}

}

When I click on it, it deletes the item from the array and logs it to the console. But it doesn't show on the screen. Any help?

Thank you,
Scratch Cat

Body:
Here you go:

var div = document.querySelector('div');
var array = [
"Banana",
"Chocolate",
"Oranges"
];

for (let i = 0; i < array.length; i++) {
  let p = document.createElement('p'); //note the block scoping
  p.textContent = array[i];
  div.appendChild(p);

  p.onclick = function() {
    array.splice(array.indexOf(this), 1); //splice wants an index...
    this.remove(); //remove el from document tree
    console.log(array);
  }

}

https://jsfiddle.net/wt0fux3f/6/


问:
Unable to access viewmodel properties from inside Listvew.Resources
I'm trying to bind the SelectedItem to a View. But the view is not able to access the viewmodel when it is inside the Resources block.
When the datacontext is re-assigned to the children, the binding works for textblocks but not for UserControl (NoteView)

Am I missing any Binding?

PFB revised(entire) code and inline comments.

```<code><UserControl x:Class="Konduva.View.NoteSearchView"
<!-- other namespaces here -->
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
DataContext="{Binding NoteSearch, Source={StaticResource Locator}}">
    <Grid>
    <ListView ItemsSource="{Binding Notes}"
        SelectedItem="{Binding SelectedNote}">
        <ListView.Resources>
        <DataTemplate DataType="{x:Type vm:NoteViewModel}">
                    <DockPanel>
                        <TextBlock Text="{Binding Title}" />
                        <Popup Placement="Right"
                           PlacementTarget="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListViewItem}}"
                           IsOpen="{Binding (ListViewItem.IsSelected), RelativeSource={RelativeSource FindAncestor, AncestorType=ListViewItem}}"
                           DataContext="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType={x:Type ListView}}}">
                            <StackPanel>
  <!-- This is working -->      <TextBlock Text="{Binding SelectedNote.Title}" />
  <!-- This is not working -->  <v:NoteView DataContext="{Binding SelectedNote}" />
                            </StackPanel>
                        </Popup>
                    </DockPanel>
                </DataTemplate>
            </ListView.Resources>
        </ListView>
    </Grid>
</UserControl>
</code>```

NoteView:

```<code><Grid>
    <TextBlock Text="{Binding Title}" /> // This Text is not displayed
</Grid>
</code>```

答:
Update 3
Since you're using MvvmLight: in NoteView, try changing

```<code>DataContext="{Binding Note, Source={StaticResource Locator}}"
</code>```

to

```<code><UserControl.Style>
    <Style TargetType="UserControl">
        <Setter Property="DataContext" Value="{Binding Note, Source={StaticResource Locator}}"/>
    </Style>
</UserControl.Style>
</code>```

Update 2

Encountered a similar problem a few minutes ago which I didn't fully understand so I'll throw in the same solution here to see if it helps. What happends if you change it to this?

```<code><v:NoteView DataContext="{Binding RelativeSource={RelativeSource AncestorType={x:Type Popup}},
                                  Path=DataContext.SelectedNote}"/>
</code>```

Update

I'm unable to reproduce this. Try adding this in your NoteView constructor. Do you reach DataContextChangedHandler when you change the selection in the ListView?

```<code>public NoteView()
{
    InitializeComponent();
    DependencyPropertyDescriptor dpd =
        DependencyPropertyDescriptor.FromProperty(UserControl.DataContextProperty,
                                                  typeof(UserControl));
    if (dpd != null)
    {
        dpd.AddValueChanged(this, new EventHandler(DataContextChangedHandler));
    }
}
void DataContextChangedHandler(object sender, EventArgs e)
{
    MessageBox.Show("DataContext Changed: " + DataContext);
}
</code>```

First answer

Your DockPanel will get the NoteViewModel as a DataContext and not the ListView and since this DataContext is inherited by all Childs every child will end up with a NoteViewModel as DataContext. To use the ListView as a DataContext for the Popup you can do this. I'm not sure what the DataContext Binding for the StackPanel does though, so I might be missing something here..

```<code><DataTemplate DataType="{x:Type vm:NoteViewModel}">
    <DockPanel>
        <TextBlock Text="{Binding Title}" />
        <Popup Placement="Right"
               PlacementTarget="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListViewItem}}"
               IsOpen="{Binding (ListViewItem.IsSelected), RelativeSource={RelativeSource FindAncestor, AncestorType=ListViewItem}}"
               DataContext="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType={x:Type ListView}}}">
            <StackPanel>
                <TextBlock Text="{Binding SelectedNote.Title}" />
                <StackPanel>
                    <v:NoteView DataContext="{Binding SelectedNote}"/>
                </StackPanel>
            </StackPanel>
        </Popup>
    </DockPanel>
</DataTemplate>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to bind the SelectedItem to a View. But the view is not able to access the viewmodel when it is inside the Resources block.
When the datacontext is re-assigned to the children, the binding works for textblocks but not for UserControl (NoteView)

Am I missing any Binding?

PFB revised(entire) code and inline comments.

<UserControl x:Class="Konduva.View.NoteSearchView"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
DataContext="{Binding NoteSearch, Source={StaticResource Locator}}">
    <Grid>
    <ListView ItemsSource="{Binding Notes}"
        SelectedItem="{Binding SelectedNote}">
        <ListView.Resources>
        <DataTemplate DataType="{x:Type vm:NoteViewModel}">
                    <DockPanel>
                        <TextBlock Text="{Binding Title}" />
                        <Popup Placement="Right"
                           PlacementTarget="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListViewItem}}"
                           IsOpen="{Binding (ListViewItem.IsSelected), RelativeSource={RelativeSource FindAncestor, AncestorType=ListViewItem}}"
                           DataContext="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType={x:Type ListView}}}">
                            <StackPanel>
        <TextBlock Text="{Binding SelectedNote.Title}" />
    <v:NoteView DataContext="{Binding SelectedNote}" />
                            </StackPanel>
                        </Popup>
                    </DockPanel>
                </DataTemplate>
            </ListView.Resources>
        </ListView>
    </Grid>
</UserControl>

NoteView:

<Grid>
    <TextBlock Text="{Binding Title}" /> // This Text is not displayed
</Grid>

Body:
Update 3
Since you're using MvvmLight: in NoteView, try changing

DataContext="{Binding Note, Source={StaticResource Locator}}"

to

<UserControl.Style>
    <Style TargetType="UserControl">
        <Setter Property="DataContext" Value="{Binding Note, Source={StaticResource Locator}}"/>
    </Style>
</UserControl.Style>

Update 2

Encountered a similar problem a few minutes ago which I didn't fully understand so I'll throw in the same solution here to see if it helps. What happends if you change it to this?

<v:NoteView DataContext="{Binding RelativeSource={RelativeSource AncestorType={x:Type Popup}},
                                  Path=DataContext.SelectedNote}"/>

Update

I'm unable to reproduce this. Try adding this in your NoteView constructor. Do you reach DataContextChangedHandler when you change the selection in the ListView?

public NoteView()
{
    InitializeComponent();
    DependencyPropertyDescriptor dpd =
        DependencyPropertyDescriptor.FromProperty(UserControl.DataContextProperty,
                                                  typeof(UserControl));
    if (dpd != null)
    {
        dpd.AddValueChanged(this, new EventHandler(DataContextChangedHandler));
    }
}
void DataContextChangedHandler(object sender, EventArgs e)
{
    MessageBox.Show("DataContext Changed: " + DataContext);
}

First answer

Your DockPanel will get the NoteViewModel as a DataContext and not the ListView and since this DataContext is inherited by all Childs every child will end up with a NoteViewModel as DataContext. To use the ListView as a DataContext for the Popup you can do this. I'm not sure what the DataContext Binding for the StackPanel does though, so I might be missing something here..

<DataTemplate DataType="{x:Type vm:NoteViewModel}">
    <DockPanel>
        <TextBlock Text="{Binding Title}" />
        <Popup Placement="Right"
               PlacementTarget="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListViewItem}}"
               IsOpen="{Binding (ListViewItem.IsSelected), RelativeSource={RelativeSource FindAncestor, AncestorType=ListViewItem}}"
               DataContext="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType={x:Type ListView}}}">
            <StackPanel>
                <TextBlock Text="{Binding SelectedNote.Title}" />
                <StackPanel>
                    <v:NoteView DataContext="{Binding SelectedNote}"/>
                </StackPanel>
            </StackPanel>
        </Popup>
    </DockPanel>
</DataTemplate>


问:
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?

答:
You should probably do this in Scala code, rather than inside the template.

What you want is listA with a Boolean for each element telling you if it's in listB. Here's a simple way to do this:

```<code>val listAWithBool = listA.map(a => (a,  listB.map(_.id).contains(a.id)))
</code>```

Then, in your for loop, you can do

```<code>@for((a,inB) <- listAWithBool){
  @if(inB){
    ...
  } else {
    ...
  }
}
</code>```

EDIT

Since you're using Play Java, most of what I wrote previously will be hard to put in code, since it's functional programming. A possible solution is to put all that in your template, which allows scala code; just put this at the top of your template (under the list of parameters):

```<code>@listAWithBool = @{
  listA.map(a => (a,  listB.map(_.id).contains(a.id)))
}
</code>```

Now to explain the weird for((a, inB) <- listAWithBool) syntax: just as for(a <- listA) means "extract all values from my list and do the following with each of them, giving it the name a", this now means "extract all pairs of values from my list and do the following with each of them, giving name a and inB to its two elements.

Remember that we have built listAWithBool to be a list of pairs (as return type of the lambda) of type List[A, Boolean], so the compiler will be able to understand that a is of type A and inB is of type Boolean.

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:
You should probably do this in Scala code, rather than inside the template.

What you want is listA with a Boolean for each element telling you if it's in listB. Here's a simple way to do this:

val listAWithBool = listA.map(a => (a,  listB.map(_.id).contains(a.id)))

Then, in your for loop, you can do

@for((a,inB) <- listAWithBool){
  @if(inB){
    ...
  } else {
    ...
  }
}

EDIT

Since you're using Play Java, most of what I wrote previously will be hard to put in code, since it's functional programming. A possible solution is to put all that in your template, which allows scala code; just put this at the top of your template (under the list of parameters):

@listAWithBool = @{
  listA.map(a => (a,  listB.map(_.id).contains(a.id)))
}

Now to explain the weird for((a, inB) <- listAWithBool) syntax: just as for(a <- listA) means "extract all values from my list and do the following with each of them, giving it the name a", this now means "extract all pairs of values from my list and do the following with each of them, giving name a and inB to its two elements.

Remember that we have built listAWithBool to be a list of pairs (as return type of the lambda) of type List[A, Boolean], so the compiler will be able to understand that a is of type A and inB is of type Boolean.


问:
Converting NetCDF to GRIB2
I know there is software like wgrib2 that will convert files in grib and grib2 format to NetCDF files, but I need to go the other way: from NetCDF to grib2, because the local weather offices here can only consume gridded data in grib2 format.

It appears that one solution could be in Python, using the NetCDF4-Python library (or other) to read the NetCDF files and using pygrib to write grib2.

Is there a better way?

答:
I know CDO is mentioned above, but I thought it would be useful to give the full command</p>

```<code>cdo -f grb2 copy in.nc out.grb
</code>```

Title: Converting NetCDF to GRIB2

Body:
I know CDO is mentioned above, but I thought it would be useful to give the full command

cdo -f grb2 copy in.nc out.grb


问:
JQuery Passing Each Sibling to a Function
I'm having trouble with the .siblings().each() in JQuery.  I have a nested list of checkboxes.  One functionality is that you check a checkbox and it also checks all of the corresponding checkboxes having the same value.  That works.  Then, if you check a parent checkbox then all of the children (siblings) will be selected.  That also works.

What I'm having trouble with is checking a parent checkbox and then calling a function on each child (sibling) to check other checkboxes of the same value.  Basically passing each sibling to the  checkAllSameUser function.

Here's the HTML:

```<code><ul>
<li><input type='checkbox' class="build-checkbox" value="1"  /> 1</li>
<li><input type='checkbox' class="build-checkbox" value="2"  /> 2
  <ul>
    <li><input type='checkbox' class="build-checkbox" value="3"  /> 3</li>
  </ul>
</li>
<li><input type='checkbox' class="build-checkbox" value="4"  /> 4
  <ul>
    <li><input type='checkbox' class="build-checkbox" value="3"  /> 3</li>
     <li><input type='checkbox' class="build-checkbox" value="5"  /> 5</li>
  </ul>
</li>
<li><input type='checkbox' class="build-checkbox" value="6"  /> 6
  <ul>
    <li><input type='checkbox' class="build-checkbox" value="5"  /> 5</li>
     <li><input type='checkbox' class="build-checkbox" value="7"  /> 7</li>
  </ul>
</li>
</code>```

JQuery:

```<code>    $(".build-checkbox").change(function () {
    checkAllSameUser($(this));
});

function checkAllSameUser(user) {
    var val = user.val();
    if ($(user).is(":checked")) {

        $(":checkbox[value='" + val + "']").prop("checked", true);
    }
    else {
        $(":checkbox[value='" + val + "']").prop("checked", false);
    }
};

$(function () {
    $("input[type='checkbox']").change(function () {
        $(this).siblings('ul')
             .find("input[type='checkbox']")
             .prop('checked', this.checked);
        $(this).siblings('ul').each(function () {
            checkAllSameUser($(this).find('input[type=checkbox]'));
        });
    });
});
</code>```

JSFiddle: http://jsfiddle.net/mU3FV/376/

Basically, if you hit check the '4' checkbox, then all of the '3' and '5' checkboxes on the page will also be checked (following the same logic of hitting the '3' or '5' individually). "I'm going to check each child and each matching value of each child on the page" essentially.

I'm fairly certain I'm not understanding the .each function or passing each sibling objects properly. I'd appreciate any input... JQuery and Javascript are not my strong points.

答:
Are you looking for a logic as this?

$(".build-checkbox").change(function() {
  checkAllSameUser($(this));
});

function checkAllSameUser(user) {
  var val = user.val();
  if ($(user).is(":checked")) {
    $(":checkbox[value='" + val + "']").prop("checked", true);
  } else {
    $(":checkbox[value='" + val + "']").prop("checked", false);
  }
};

$(function() {
  $("input[type='checkbox']").change(function() {
    var val = $(this).val();
    $(this).siblings('ul').find("input[type='checkbox']").prop('checked', this.checked);
    $(this).siblings('ul').find("input[type='checkbox']").each(function() {
      checkAllSameUser($(this));
    });
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li ul {
  padding-left: 25px;
  border: none;
  display: block;
}

ul {
  border: 2px solid blue;
  padding: 5px;
  margin: 5px;
  display: inline-block;
  list-style-type: none;
}</code>```

    <input type='checkbox' class="build-checkbox" value="1" /> 1

    <input type='checkbox' class="build-checkbox" value="2" /> 2

        <input type='checkbox' class="build-checkbox" value="3" /> 3

    <input type='checkbox' class="build-checkbox" value="4" /> 4

        <input type='checkbox' class="build-checkbox" value="3" /> 3

        <input type='checkbox' class="build-checkbox" value="5" /> 5

    <input type='checkbox' class="build-checkbox" value="6" /> 6

        <input type='checkbox' class="build-checkbox" value="5" /> 5

        <input type='checkbox' class="build-checkbox" value="7" /> 7

```
</div>
</div>
</p>

<p>Note the </p>

```$(this).siblings('ul').find("input[type='checkbox']").each(function() {
  checkAllSameUser($(this));
});
```

<p>instead of </p>

```$(this).siblings('ul').each(function () {
    checkAllSameUser($(this));
});
```

Body:
I'm having trouble with the .siblings().each() in JQuery.  I have a nested list of checkboxes.  One functionality is that you check a checkbox and it also checks all of the corresponding checkboxes having the same value.  That works.  Then, if you check a parent checkbox then all of the children (siblings) will be selected.  That also works.

What I'm having trouble with is checking a parent checkbox and then calling a function on each child (sibling) to check other checkboxes of the same value.  Basically passing each sibling to the  checkAllSameUser function.

Here's the HTML:

<input type='checkbox' class="build-checkbox" value="1"  /> 1

<input type='checkbox' class="build-checkbox" value="2"  /> 2

<input type='checkbox' class="build-checkbox" value="3"  /> 3

<input type='checkbox' class="build-checkbox" value="4"  /> 4

<input type='checkbox' class="build-checkbox" value="3"  /> 3

<input type='checkbox' class="build-checkbox" value="5"  /> 5

<input type='checkbox' class="build-checkbox" value="6"  /> 6

<input type='checkbox' class="build-checkbox" value="5"  /> 5

<input type='checkbox' class="build-checkbox" value="7"  /> 7

JQuery:

    $(".build-checkbox").change(function () {
    checkAllSameUser($(this));
});

function checkAllSameUser(user) {
    var val = user.val();
    if ($(user).is(":checked")) {

        $(":checkbox[value='" + val + "']").prop("checked", true);
    }
    else {
        $(":checkbox[value='" + val + "']").prop("checked", false);
    }
};

$(function () {
    $("input[type='checkbox']").change(function () {
        $(this).siblings('ul')
             .find("input[type='checkbox']")
             .prop('checked', this.checked);
        $(this).siblings('ul').each(function () {
            checkAllSameUser($(this).find('input[type=checkbox]'));
        });
    });
});

JSFiddle: http://jsfiddle.net/mU3FV/376/

Basically, if you hit check the '4' checkbox, then all of the '3' and '5' checkboxes on the page will also be checked (following the same logic of hitting the '3' or '5' individually). "I'm going to check each child and each matching value of each child on the page" essentially.

I'm fairly certain I'm not understanding the .each function or passing each sibling objects properly. I'd appreciate any input... JQuery and Javascript are not my strong points.

Body:
Are you looking for a logic as this?

$(".build-checkbox").change(function() {
  checkAllSameUser($(this));
});

function checkAllSameUser(user) {
  var val = user.val();
  if ($(user).is(":checked")) {
    $(":checkbox[value='" + val + "']").prop("checked", true);
  } else {
    $(":checkbox[value='" + val + "']").prop("checked", false);
  }
};

$(function() {
  $("input[type='checkbox']").change(function() {
    var val = $(this).val();
    $(this).siblings('ul').find("input[type='checkbox']").prop('checked', this.checked);
    $(this).siblings('ul').find("input[type='checkbox']").each(function() {
      checkAllSameUser($(this));
    });
  });
});

li ul {
  padding-left: 25px;
  border: none;
  display: block;
}

ul {
  border: 2px solid blue;
  padding: 5px;
  margin: 5px;
  display: inline-block;
  list-style-type: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    <input type='checkbox' class="build-checkbox" value="1" /> 1</li>
  <li>
    <input type='checkbox' class="build-checkbox" value="2" /> 2
    <ul>
      <li>
        <input type='checkbox' class="build-checkbox" value="3" /> 3</li>
    </ul>
  </li>
  <li>
    <input type='checkbox' class="build-checkbox" value="4" /> 4
    <ul>
      <li>
        <input type='checkbox' class="build-checkbox" value="3" /> 3</li>
      <li>
        <input type='checkbox' class="build-checkbox" value="5" /> 5</li>
    </ul>
  </li>
  <li>
    <input type='checkbox' class="build-checkbox" value="6" /> 6
    <ul>
      <li>
        <input type='checkbox' class="build-checkbox" value="5" /> 5</li>
      <li>
        <input type='checkbox' class="build-checkbox" value="7" /> 7</li>
    </ul>
  </li>
</ul>

Note the

$(this).siblings('ul').find("input[type='checkbox']").each(function() {
  checkAllSameUser($(this));
});

instead of

$(this).siblings('ul').each(function () {
    checkAllSameUser($(this));
});


问:
What it means lambda calculus is equivalent to turing machine
I'm trying to wrap my head around lambda calculus, and how it relates to language, compiler and binary code. What it actually means that lambda calculus is equivalent to turing machine, and where it actually manifest itself?

I don't understand how lambda calculus could supersede turing machine as a theoretical model of computation. Turing machine is about sequential instructions to mutate the state, lambda calculus is about expressions evaluating to something. It is more abstract, like a programming language of it's own, not the model of how to practically compute something, make things happen. Or let's put it this way: lambda calculus is like the road map, and turing machine like a model of car. How are these two considered equivalent? Would it be possible to run software on hardware without implementing turing machine?

How does for example, a lisp compiler and language relates to lambda calculus? In which layer is the lambda calculus implemented? Is the implementation pure in the terms of definition of lambda calculus? Where and how the theory behind lambda calculus transforms syntax into a running binary? For example, in lambda calculus numbers are encoded as special functions applied to some other function n times. Yet in syntax we use number literals. Where all these axioms are used?

答:
In computability theory, equivalence between two theoretical models of computation means that they can solve the same set of problems. Anything you can compute in a Turing Machine, you can compute using Lambda Calculus, and vice versa.

How do we prove this? It is sufficient to say that if we can model a Turing Machine in lambda calculus, than clearly lambda calculus can compute everything a Turing Machine can. And if we can solve lambda calculus on a Turing Machine, then the reverse holds true as well.

Both of these are possible, and so the models are said to be equivalent.

In practice of course, one model may easily be more practical for certain use cases. Computers today are based on the RAM state model, which in turn lends the basis of it's theory from the idea of a Turing Machine. Lambda calculus is indeed quite abstract, and it doesn't lend it's self as easily to implementation in physical hardware. The two models however both exist in the same computation class, and they can solve the same problems, and are therefor referred to as equivalent.


答: You need to use password_verify($password, $hash) to verify the password. A new hash will use a different salt and result in a new value for the hash.</p>

Title: Password Encryption Android, PHP

Body:
UPDATED:

I have my android app working fine with plain text password until now. I am trying to hash the password as next step. Cant find what the error is.

I am very sure that the communication is fine with plain text passwords.
I verified that the hashed value is getting stored in the DB properly(used varchar(80) for this attribute in the DB).

Please help.

Register.php

    <?php
include("config.php");

session_start();

// username and password sent from form

$firstName = mysqli_real_escape_string($db,$_POST["firstName"]);

$lastName = mysqli_real_escape_string($db,$_POST["lastName"]);

$email = mysqli_real_escape_string($db,$_POST["email"]);

$myusername = mysqli_real_escape_string($db,$_POST["username"]);

$mypassword = mysqli_real_escape_string($db,$_POST["password"]);

$passwordhash = password_hash($mypassword, PASSWORD_DEFAULT);

$sql = "INSERT into user VALUES ('$firstName', '$lastName', '$myusername', '$email', '$passwordhash')";

$result = mysqli_query($db,$sql);

if($result)
{

    echo "success";

}else{

    echo "failed";

}

?>

Login.php

    <?php
include("config.php");

session_start();

// username and password sent from form

$myusername = mysqli_real_escape_string($db,$_POST["username"]);

$mypassword = mysqli_real_escape_string($db,$_POST["password"]);

$sql = "SELECT * FROM user WHERE username = '$myusername'";

$result = mysqli_query($db,$sql);
$count = mysqli_num_rows($result);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$hash = $row['password'];

// If result matched $myusername and $mypassword, table row must be 1 row

if(true === password_verify($mypassword,$hash)) {

    echo "success". "\n";

    echo $row['firstName'] . "\n";

    echo $row['lastName'] . "\n";

    echo $row['username'] . "\n";

    echo $row['email'] . "\n";

}
else{

    echo " Incorrect Login. Please try again ";
}

?>


问:
Good TCP/IP networking book for a programmer?
Every day I write Web applications, and I have a good understanding of HTTP. However I want to close the gaps in my knowlege of network architecture. I'm not a sysadmin, so a hard-core sysadmin reference book would probably be a bit much for me, but I'm also not looking for a book on how to write code in any way -- I'm interested in the mechanisms underneath all that fun Web code I write.

Any recommendations?

答: Also by the great W. Richard Stevens is Unix Network Programming (http://www.amazon.com/UNIX-Network-Programming-Networking-Sockets/dp/013490012X).</p>


问:
Recover Custom Post Type Data
I have created CPT using CPT UI plugin and suddenly I lost all the important data. I don't have any backup and I need it backup. Is there any I can get it backup? I have SQL backup of last week.

Moreover I am seeing Count on CPT categories but they are showing Empty on main CPT page. for example CPT:

Animals --> showing  (0) posts

Animal Categories is showing 100 counts that means It has data but something has hide it. I remember I updated Permalinks but I don't remember the previous settings

答:
use this sqlQuery in your SQL Database (phpMyadmin or ...) and you will get a list of your custom post type posts with their info:

```<code>SELECT *
FROM {table prefix}_posts
WHERE post_type =  'your_custom_post_type_name'
AND post_status =  'publish'
</code>```

your {table prefix} can be wp or some thing else if you've change it on wp setup step you can check it in your Database or wp-config.php file in your wp root.

you can replace * in query with whatever field name you want for example:

```<code>post_content, post_title, post_excerpt
</code>```

to only get fields that you need.

Title: Recover Custom Post Type Data

Body:
use this sqlQuery in your SQL Database (phpMyadmin or ...) and you will get a list of your custom post type posts with their info:

SELECT *
FROM {table prefix}_posts
WHERE post_type =  'your_custom_post_type_name'
AND post_status =  'publish'

your {table prefix} can be wp or some thing else if you've change it on wp setup step you can check it in your Database or wp-config.php file in your wp root.

you can replace * in query with whatever field name you want for example:

post_content, post_title, post_excerpt

to only get fields that you need.


问:
Nesting with three levels of quotations
I am trying to create a php variable that has three levels of nested quotes. How do I make a third level around "tackEvent", "downloads", "all", and "nofilter"? The double quotes that I have there are not working.

```<code>  $outputList .= "<a href=files/".$content_file ." onClick='_gaq.push
(["_trackEvent", "downloads", "all", "nofilter"]);' >" . $content_name .
"</a>";
</code>```

答:
Outer quote: "

Inner quote:  '

Third-tier quote:  \"

Fourth-tier quote:  "

Title: Nesting with three levels of quotations

Body:
I am trying to create a php variable that has three levels of nested quotes. How do I make a third level around "tackEvent", "downloads", "all", and "nofilter"? The double quotes that I have there are not working.

  $outputList .= "" . $content_name .
"";

Body:
Outer quote: "

Inner quote:  '

Third-tier quote:  \"

Fourth-tier quote:  &quot;


问:
Can I add Calendar Event without giving calendar access permissions?
My react-native app needs to create a calendar event, it doesn't need to view, edit or delete event. I tried to use few react-native libraries which handle calendar but I needed to grant permissions for a calendar in each of them.

I have no knowledge of Objective C or Swift, but I would like to know if it is even possible in either native or react-native way.
Every advice is very appreciated. Thanks!

答:
Short answer is no.
You do need to be granted permission to create a calendar event.

The Human Interface Guidelines section about requesting permissions

Users must grant permission for an app to access personal information, including the current location, calendar, contact information, reminders, and photos. Although people appreciate the convenience of using an app that has access to this information, they also expect to have control over their private data. For example, people like being able to automatically tag photos with their physical location or find nearby friends, but they also want the option to disable such features.

In the apple docs it specifies that you need to add an entry to the info.plist. This text is used when the permission is requested.

Important: If your iOS app links on or after iOS 10.0 and you need to access Calendar data, be sure to include the NSCalendarsUsageDescription key in your Info.plist file.

Your app will crash without this key added to the info.plist.

This is the case for native apps, so the same will apply for react-native.


问:
Multiplication from 2 field, too many variable
i practice my beginners skill in android and now i did the application which gets 2 numbers from 2 editText and display score in next editText

Is it a good practice to do it? I belive better programmers have shortest way to do that.

```<code>public class MainActivity extends AppCompatActivity {

    private Button button;
    private EditText editText,editText2,editText3;
    private String a,b,c;
    private Double x1,x2,x3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        editText = (EditText) findViewById(R.id.editText);
        editText2 = (EditText) findViewById(R.id.editText2);
        editText3 = (EditText) findViewById(R.id.editText3);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                a = editText.getText().toString();
                b = editText2.getText().toString();
                x1 = Double.parseDouble(a);
                x2 = Double.parseDouble(b);

                calc(x1,x2);

            }
        });

    }

    private void calc(double x1, double x2){

        x3 = x1 * x2;
        c = String.valueOf(x3);
        editText3.setText(c);

    }
</code>```

答:
As MacLean Sochor commented you cannot reduce the code because those
  are the exact steps you have to perform.

Anyways, you can use following steps to reduce a code little bit and therefore, make it readable.

One suggestion I always follow is to assign listeners in XML layout:

```<code><Button
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="@string/multiply" // multiply is '*' in strings.xml
    android:onClick="multiply" /> // Here you are assigning click listener
</code>```

Assigning a suitable name to click listener makes it readable. Provided that, some may argue that the method does not accept the arguments required to perform the task its name suggests.

```<code>protected void multiply(View); // View argument is passed instead of two  numbers
</code>```

Advanced techniques to structure the code (reducing as a side effect) include Data Binding. Watch Data Binding -- Write Apps Faster (Android Dev Summit 2015) to get a quick start on data Binding.

Miscellaneous suggestions:

Refactor your variables by giving them meaningful names, for example, x1, x2, and x3 can be renamed to operand, otherOperand, and product. (Note the use of word 'other'. I did not use firstOperand, secondOperand because order does not matter in multiplication.)

Avoid using member variables for values you are going to need for function only. For example, apply suggestion 1 to variables a, b, and c and then move them inside onClick() and calc() method.

Hope this helps.

Body:
i practice my beginners skill in android and now i did the application which gets 2 numbers from 2 editText and display score in next editText

Is it a good practice to do it? I belive better programmers have shortest way to do that.

public class MainActivity extends AppCompatActivity {

    private Button button;
    private EditText editText,editText2,editText3;
    private String a,b,c;
    private Double x1,x2,x3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        editText = (EditText) findViewById(R.id.editText);
        editText2 = (EditText) findViewById(R.id.editText2);
        editText3 = (EditText) findViewById(R.id.editText3);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                a = editText.getText().toString();
                b = editText2.getText().toString();
                x1 = Double.parseDouble(a);
                x2 = Double.parseDouble(b);

                calc(x1,x2);

            }
        });

    }

    private void calc(double x1, double x2){

        x3 = x1 * x2;
        c = String.valueOf(x3);
        editText3.setText(c);

    }

Body:
As MacLean Sochor commented you cannot reduce the code because those
  are the exact steps you have to perform.

Anyways, you can use following steps to reduce a code little bit and therefore, make it readable.

One suggestion I always follow is to assign listeners in XML layout:

<Button
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="@string/multiply" // multiply is '*' in strings.xml
    android:onClick="multiply" /> // Here you are assigning click listener

Assigning a suitable name to click listener makes it readable. Provided that, some may argue that the method does not accept the arguments required to perform the task its name suggests.

protected void multiply(View); // View argument is passed instead of two  numbers

Advanced techniques to structure the code (reducing as a side effect) include Data Binding. Watch Data Binding -- Write Apps Faster (Android Dev Summit 2015) to get a quick start on data Binding.

Miscellaneous suggestions:

Refactor your variables by giving them meaningful names, for example, x1, x2, and x3 can be renamed to operand, otherOperand, and product. (Note the use of word 'other'. I did not use firstOperand, secondOperand because order does not matter in multiplication.)

Avoid using member variables for values you are going to need for function only. For example, apply suggestion 1 to variables a, b, and c and then move them inside onClick() and calc() method.

Hope this helps.


问:
how to add background color using Jquery
I am trying to add the background color to the table element.

```<code>jq("[class=detailro]").each(function (index) {
var thisAttr = jq(this).attr("pdmqa");
if (thisAttr == "customer.organization.name"){
thisAttr = jq(this).html();
jq(this).css({"background":"#000"});
console.log(thisAttr.trim());}

});
</code>```

how to add inline style property to html

How can add css property to the element

i want to achieve to change the back ground color of the th element.

thanks

答:
You can do this

$('#df_0_2').css('background', '#000');

EDIT

If you want to target the customer.organization.name you can do this

```<code>$this = $("td[pdmqa='customer.organization.name']");
$this.css('background', '#000');
</code>```

Hope this help.

SYA :)

Body:
I am trying to add the background color to the table element.

jq("[class=detailro]").each(function (index) {
var thisAttr = jq(this).attr("pdmqa");
if (thisAttr == "customer.organization.name"){
thisAttr = jq(this).html();
jq(this).css({"background":"#000"});
console.log(thisAttr.trim());}

});

how to add inline style property to html

How can add css property to the element

i want to achieve to change the back ground color of the th element.

thanks

Body:
You can do this

$('#df_0_2').css('background', '#000');

EDIT

If you want to target the customer.organization.name you can do this

$this = $("td[pdmqa='customer.organization.name']");
$this.css('background', '#000');

Hope this help.

SYA :)


问:
In Rails, a Sweeper isn't getting called in a Model-only setup
I'm working on a Rails app, where I'm using page caching to store static html output. The caching works fine. I'm having trouble expiring the caches, though.

I believe my problem is, in part, because I'm not expiring the cache from my controller. All of the actions necessary for this are being handled within the model. This seems like it should be doable, but all of the references to Model-based cache expiration that I'm finding seem to be out of date, or are otherwise not working.

In my environment.rb file, I'm calling

```<code>config.load_paths += %W( #{RAILS_ROOT}/app/sweepers )
</code>```

And I have, in the /sweepers folder, a LinkSweeper file:

```<code>class LinkSweeper < ActionController::Caching::Sweeper
  observe Link

  def after_update(link)
    clear_links_cache(link)
  end

  def clear_links_cache(link)
  # expire_page :controller => 'links', :action => 'show', :md5 => link.md5
    expire_page '/l/'+ link.md5 + '.html'
  end
end
</code>```

So ... why isn't it deleting the cached page when I update the model? (Process: using script/console, I'm selecting items from the database and saving them, but their corresponding pages aren't deleting from the cache), and I'm also calling the specific method in the Link model that would normally invoke the sweeper. Neither works.

If it matters, the cached file is an md5 hash off a key value in the Links table. The cached page is getting stored as something like /l/45ed4aade64d427...99919cba2bd90f.html.

Essentially, it seems as though the Sweeper isn't actually observing the Link. I also read (here) that it might be possible to simply add the sweeper to config.active_record.observers in environment.rb, but that didn't seem to do it (and I wasn't sure if the load_path of app/sweepers in environment.rb obviated that).

答: I wrote a bit about this topic here: Rails Cache Sweeper Confusion. Would love to hear your opinions.</p>

Body:
I'm working on a Rails app, where I'm using page caching to store static html output. The caching works fine. I'm having trouble expiring the caches, though.

I believe my problem is, in part, because I'm not expiring the cache from my controller. All of the actions necessary for this are being handled within the model. This seems like it should be doable, but all of the references to Model-based cache expiration that I'm finding seem to be out of date, or are otherwise not working.

In my environment.rb file, I'm calling

config.load_paths += %W( #{RAILS_ROOT}/app/sweepers )

And I have, in the /sweepers folder, a LinkSweeper file:

class LinkSweeper < ActionController::Caching::Sweeper
  observe Link

  def after_update(link)
    clear_links_cache(link)
  end

  def clear_links_cache(link)
  # expire_page :controller => 'links', :action => 'show', :md5 => link.md5
    expire_page '/l/'+ link.md5 + '.html'
  end
end

So ... why isn't it deleting the cached page when I update the model? (Process: using script/console, I'm selecting items from the database and saving them, but their corresponding pages aren't deleting from the cache), and I'm also calling the specific method in the Link model that would normally invoke the sweeper. Neither works.

If it matters, the cached file is an md5 hash off a key value in the Links table. The cached page is getting stored as something like /l/45ed4aade64d427...99919cba2bd90f.html.

Essentially, it seems as though the Sweeper isn't actually observing the Link. I also read (here) that it might be possible to simply add the sweeper to config.active_record.observers in environment.rb, but that didn't seem to do it (and I wasn't sure if the load_path of app/sweepers in environment.rb obviated that).


问:
What is the difference between "def" and "val" to define a function
What is the difference between:

```<code>def even: Int => Boolean = _ % 2 == 0
</code>```

and

```<code>val even: Int => Boolean = _ % 2 == 0
</code>```

Both can be called like even(10).

答:
See this:

```<code>  var x = 2 // using var as I need to change it to 3 later
  val sq = x*x // evaluates right now
  x = 3 // no effect! sq is already evaluated
  println(sq)
</code>```

Surprisingly, this will print 4 and not 9! val (even var) is evaluated immediately and assigned.

Now change val to def.. it will print 9! Def is a function call.. it will evaluate each time it is called.

Body:
What is the difference between:

def even: Int => Boolean = _ % 2 == 0

and

val even: Int => Boolean = _ % 2 == 0

Both can be called like even(10).

Body:
See this:

  var x = 2 // using var as I need to change it to 3 later
  val sq = x*x // evaluates right now
  x = 3 // no effect! sq is already evaluated
  println(sq)

Surprisingly, this will print 4 and not 9! val (even var) is evaluated immediately and assigned.

Now change val to def.. it will print 9! Def is a function call.. it will evaluate each time it is called.