问:
How can I recover my Git repository for a "missing tree" error?
We are using Gerrit for our Git repository.  On a project that has been active for several months, we are suddenly unable to push any changes.  When we execute git push we see the following error:

error: unpack failed: error Missing tree 14d62f0ed4385e3f68f226ac133fa9932a9c65c9

Executing git fsck --full yields:

```<code>dangling tree 2701c92fb6eab1826482f6bcc9598413e651a92a
dangling blob c505b3b12cfacd1e26dec8dc559820a30fc20c27
dangling blob 8907f94b5b4ec881e1b86d50681795e368c167ff
dangling blob 4938d9fc34c6e2f92c68872bfec6e070b2b3a9c2
dangling blob 8a5c8b8d35484ea1470e2d8e6c482fcb97b23d0f
dangling commit 3072d3314e20bf6c6998e1c02986d83019d3e1df
dangling tree 5377d7f7111d340854c3ee0946667c202227e603
dangling tree c3783e9ab540457924ceb9f9fb5ea1c2b97472b1
dangling blob 8b92d1765038e4ec5e721f98a2aabb305a7f9819
dangling tree 38a03153f0f18ca15846e9bd4983a86800a43a94
dangling commit 8db2d6ae5364174bebe13720a359ddb2e62d4c9d
</code>```

All of our developers are experiencing the same error when they try to push.  So far, we've tried re-initializing the gerrit repo (git init --bare ...) and pushing up to it.  We've also tried creating a new gerrit project with a separate repo.  In the end, we keep getting the same error.

Does anyone have any insight on what the cause would be, or how to recover?

答:
This generally happens when time of commit and push is different and which ultimately creates a mismatch between both the trees. Given a remote branch upstream and local branch foo

Firstly throw away all the uncommitted changes using

```<code>git reset --hard foo
</code>```

Then track the remote branch using

```<code>git branch --set-upstream-to=upstream/foo
</code>```

And finally

```<code>git pull
</code>```

Body:
We are using Gerrit for our Git repository.  On a project that has been active for several months, we are suddenly unable to push any changes.  When we execute git push we see the following error:

error: unpack failed: error Missing tree 14d62f0ed4385e3f68f226ac133fa9932a9c65c9

Executing git fsck --full yields:

dangling tree 2701c92fb6eab1826482f6bcc9598413e651a92a
dangling blob c505b3b12cfacd1e26dec8dc559820a30fc20c27
dangling blob 8907f94b5b4ec881e1b86d50681795e368c167ff
dangling blob 4938d9fc34c6e2f92c68872bfec6e070b2b3a9c2
dangling blob 8a5c8b8d35484ea1470e2d8e6c482fcb97b23d0f
dangling commit 3072d3314e20bf6c6998e1c02986d83019d3e1df
dangling tree 5377d7f7111d340854c3ee0946667c202227e603
dangling tree c3783e9ab540457924ceb9f9fb5ea1c2b97472b1
dangling blob 8b92d1765038e4ec5e721f98a2aabb305a7f9819
dangling tree 38a03153f0f18ca15846e9bd4983a86800a43a94
dangling commit 8db2d6ae5364174bebe13720a359ddb2e62d4c9d

All of our developers are experiencing the same error when they try to push.  So far, we've tried re-initializing the gerrit repo (git init --bare ...) and pushing up to it.  We've also tried creating a new gerrit project with a separate repo.  In the end, we keep getting the same error.

Does anyone have any insight on what the cause would be, or how to recover?

Body:
This generally happens when time of commit and push is different and which ultimately creates a mismatch between both the trees. Given a remote branch upstream and local branch foo

Firstly throw away all the uncommitted changes using

git reset --hard foo

Then track the remote branch using

git branch --set-upstream-to=upstream/foo

And finally

git pull


来源: stackexchange

问:
CouchDB 2 global_changes system table is getting insanely big
We have a system that basically writes 250MB of data into our CouchDB 2 instance, which generates ~50GB/day in the global_changes database.

This makes CouchDB2 consumes all the disk.

Once you get to this state, CouchDB2 goes and never comes back.

We would like to know if there is any way of limiting the size of the global_changes table, or if there is a way of managing this table, like a set of best practices.

答:
tldr: just delete it

http://docs.couchdb.org/en/latest/install/setup.html#single-node-setup

States:

Note that the last of these (referring to _global_changes) is not necessary if you do not expect to be using the global changes feed. Feel free to delete this database if you have created it, it has grown in size, and you do not need the function (and do not wish to waste system resources on compacting it regularly.

ContentLicense: CC BY-SA 3.0


问:
Branch from master or branch from branch?
I'm working on a branch (feature1) which is branched from master.
Feature1 branch has many commits and a lot work has been done.

```<code>----------- Master
   \---------------- Feature1
</code>```

A colleague needs to do some work that is closely related to branch feature1.

Should the colleague branch off from master or feature1?

Let's say the colleague branches off from feature1 and creates feature1_addon, and work continues in parallel between these two branches. The work continues for weeks in parallel.

```<code>----------- Master
   \---------------- Feature1
            \----Feature1_addon
</code>```

Eventually these two branches (feature1 & feature1_addon) must be merged into master, how should this be done without losing any work?

答:
feature1_addon branch can be created from feature1.
$ git checkout -b feacture1_addon feature1

your colleague can continue work work on addon branch.
you can continue work on feature1.

Once the feature and addon is implemented, Push both branches code to origin.

$ git push origin feature1

$ git push origin feature1_addon

Later any one of you can fetch both branches to your local.

$ git fetch && git checkout "branch to create in local"

Once the branches created in local

Checkout to master

$ git checkout master

$ git merge feature1

$ git merge feature1_addon

While merging if any conflicts came, resolve conflicts and commit the code.

With this process no work will be lost.

Body:
I'm working on a branch (feature1) which is branched from master.
Feature1 branch has many commits and a lot work has been done.

----------- Master
   \---------------- Feature1

A colleague needs to do some work that is closely related to branch feature1.

Should the colleague branch off from master or feature1?

Let's say the colleague branches off from feature1 and creates feature1_addon, and work continues in parallel between these two branches. The work continues for weeks in parallel.

----------- Master
   \---------------- Feature1
            \----Feature1_addon

Eventually these two branches (feature1 & feature1_addon) must be merged into master, how should this be done without losing any work?


问:
Simplest way to fix variables spacing? [php]
I'm trying to create a very basic multiplication table without the actual table element, but not sure how to space the numbers correctly (without using css or an html table!). What's the simplest way to do this?

<?php

  for ($i=1; $i < 11 ; $i++) {

    for ($x=1; $x< 11 ; $x++) {
      echo  $i*$x . " ";
    }
    echo "
";
  }

 ?>```

答:
Is this good enough

```<code>>     <?php for ($i=1; $i < 11 ; $i++) {
>     for ($x=1; $x< 11 ; $x++) {
>         $output = $i*$x;
>         if($output >= 10){
>             echo $output . str_repeat(' ', 4);
>         } else{
>             echo $output .  str_repeat(' ', 6); ;
>         }
>     }
>     echo "<br>"; } ?>

OUTPUT
</code>```

Body:
Is this good enough

>     <?php for ($i=1; $i < 11 ; $i++) {
>     for ($x=1; $x< 11 ; $x++) {
>         $output = $i*$x;
>         if($output >= 10){
>             echo $output . str_repeat('&nbsp;', 4);
>         } else{
>             echo $output .  str_repeat('&nbsp;', 6); ;
>         }
>     }
>     echo "<br>"; } ?>

OUTPUT


问:
Visual Studio Version Compatibility
I coded a windows desktop application about 5 years ago with "Visual Basic 2010 - Express Edition". Now, i want to make some upgrades on my program. I have VB2010 Express Edition on my computer. But i want to uninstall VB2010 Express Edition and install "Visual Studio 2017" instead of it. But I am not sure if i can run my codes on "Visual Studio 2017" or not. You may say: "try it and if can't run your code turn back to VB2010". But I am not sure if i can turn back to earlier version after installing the 2017 version.</p>

答: I don't see why you can't install Visual Studio 2017 and try running your code. If it works, you can then uninstall VB2010 and you are good to go. If you are worried about making changes to the code/project to get it to work in VS2017, then just make a copy of the project first and keep the original as a back up.</p>

Title: Visual Studio Version Compatibility


问:
C++ concepts and template specialization; how to get a user-friendly compiler error
I have two (or more) templates that can each adapt a specific set of classes, identified by a concept. To make it possible for the two templates to have the same name, they must be specializations.

```<code>template< typename T >
struct pin_in { static_assert( always_false<T>::value, . . . ); };

template< is_pin_in T >
struct pin_in< T > . . .

template< is_pin_in_out T >
struct pin_in< T > . . .
</code>```

This works OK when one of the specializations match. When none match the base template is selected, and I get the assertion failure. The mechanism works. I love concepts!

But the error message I get (GCC 7.2.0) points to the assertion. Can I somehow make the base template not be selected, so I would get an error message that tells that no template matched the argument class?

答:
Try to use std::enable_if to remove the base template from overload resolution.
Something like this:</p>

```<code>template< typename T >
struct pin_in<typename std::enable_if<false>::type> {};

template< is_pin_in T >
struct pin_in<typename std::enable_if<true>::type>< T > . . .

template< is_pin_in_out T >
struct pin_in<typename std::enable_if<true>::type>< T > . . .
</code>```

Body:
I have two (or more) templates that can each adapt a specific set of classes, identified by a concept. To make it possible for the two templates to have the same name, they must be specializations.

template< typename T >
struct pin_in { static_assert( always_false<T>::value, . . . ); };

template< is_pin_in T >
struct pin_in< T > . . .

template< is_pin_in_out T >
struct pin_in< T > . . .

This works OK when one of the specializations match. When none match the base template is selected, and I get the assertion failure. The mechanism works. I love concepts!

But the error message I get (GCC 7.2.0) points to the assertion. Can I somehow make the base template not be selected, so I would get an error message that tells that no template matched the argument class?

Body:
Try to use std::enable_if to remove the base template from overload resolution.
Something like this:

template< typename T >
struct pin_in<typename std::enable_if<false>::type> {};

template< is_pin_in T >
struct pin_in<typename std::enable_if<true>::type>< T > . . .

template< is_pin_in_out T >
struct pin_in<typename std::enable_if<true>::type>< T > . . .


问:
How to design domain model with interfaces that are dependent on the model's properties
I have a domain model (see example below) that has several interfaces that are determined based upon the value of properties within the model itself.  While the code below "works" it doesn't feel right.  I am sure that there is probably a better approach, but I haven't been able to come up with one.  I would be very interested in getting feedback with some alternate approaches.</p>

```<code>public interface IPickListGenerator
    {
        void Execute();
    }

public class SportsPicklistGenerator : IPickListGenerator
{
        public void Execute()
        {
            // Do something
        }
}

public class EntertainmentPicklistGenerator : IPickListGenerator
{
    public void Execute()
    {
        // Do something
    }
}

public interface IQuestionIsAnswerableDeterminer
{
    void Execute();
}

public class GameQuestionIsAnswerableDeterminer : IQuestionIsAnswerableDeterminer
{
    public void Execute()
    {
        // Do something
    }
}

public class RoundQuestionIsAnswerableDeterminer : IQuestionIsAnswerableDeterminer
{
    public void Execute()
    {
        // Do something
    }
}

public class Pool
{
    public enum PoolType
    {
        Sports,
        Entertainment
    }

    public enum DeadlineType
    {
        Game,
        Round
    }

    private IPickListGenerator mPickListGenerator = null;
    private IQuestionIsAnswerableDeterminer mQuestionIsAnswerableDeterminer = null;

    public PoolType Type { get; set; }
    public DeadlineType Deadline { get; set; }

    public IQuestionIsAnswerableDeterminer IsQuestionAnswerableDeterminer
    {
        get
        {
            if (mQuestionIsAnswerableDeterminer == null) SetPoolSpecificInterfaces();
            return mQuestionIsAnswerableDeterminer;
        }
    }

    public IPickListGenerator PickListGenerator
    {
        get
        {
            if (mPickListGenerator == null) SetPoolSpecificInterfaces();
            return mPickListGenerator;
        }
    }

    private void SetPoolSpecificInterfaces()
    {
        switch (Type)
        {
            case Pool.PoolType.Sports:
                mPickListGenerator = new SportsPicklistGenerator();
                break;
            case Pool.PoolType.Entertainment:
                mPickListGenerator = new EntertainmentPicklistGenerator();
                break;
        }

        switch (Deadline)
        {
            case Pool.DeadlineType.Game:
                mQuestionIsAnswerableDeterminer = new GameQuestionIsAnswerableDeterminer();
                break;
            case Pool.DeadlineType.Round:
                mQuestionIsAnswerableDeterminer = new RoundQuestionIsAnswerableDeterminer();
                break;
        }
    }
}
// Example usages:
    var pool = new Pool{ Type = Pool.PoolType.Sports, Deadline = Pool.DeadLineType.Game};
    pool.IsQuestionAnswerableDeterminer.Execute();
    pool.PickListGenerator.Execute();
</code>```

答:
You probably need to remove the dependencies from your code. Excessiveness from your code exists is in 2 ways:

you have an excessive code (interfaces)

you have an excessive constraints (enums)

Finally, I've got this, in dialog with Adam, which eliminates exception throws, the need of two switch statement, two enumerations, whilst preserving pool closures and elimination possible errors in code. For each switch statement (each interface implementation pair), you have to implement its own static method instantiating Pool class properly:

```<code>public interface IPool
{
    void Execute();
}

public class Pool : IPool
{
    private Pool() { }

    public IPickListGenerator PickListGenerator { set; private get; }
    public IQuestionIsAnswerableDeterminer IsQuestionIsAnswerableDeterminer { set; private get; }

    public static IPool GetSportsGame()
    {
        return new Pool
        {
            PickListGenerator = new SportsPicklistGenerator(),
            IsQuestionIsAnswerableDeterminer = new GameQuestionIsAnswerableDeterminer()
        };
    }
    public static IPool GetSportsEntertainment()
    {
        return new Pool
        {
            PickListGenerator = new SportsPicklistGenerator(),
            IsQuestionIsAnswerableDeterminer = new EntertainmentPicklistGenerator()
        };
    }
    public void Execute()
    {
        IsQuestionIsAnswerableDeterminer.Execute();
        PickListGenerator.Execute();
    }
}
</code>```

--- History of that post, leading to this solution:

You can improve your code by simplifying the code, because in your implementation, Pool class is limited to enumerations, and if so, the Pool class is not extensible. You probably will have to rewrite SetPoolSpecificInterfaces() again and again, when new requirements and interface implementation comes into view. So the weakest point of the current design is that particular SetPoolSpecificInterfaces() method and if so, not extensible Pool class.

If that is what you required, than interfaces is not really needed. In other case, you will not be dependent upon number of interface implementations (which is actually fixed by the corresponding enum) so, it probably can be be simplified to following code (i fixed the issues), removing these constraints:

```<code>namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Example usages:
            var pool = new Pool
            {
                PickListGenerator = new SportsPicklistGenerator(),
                IsQuestionIsAnswerableDeterminer = new GameQuestionIsAnswerableDeterminer()
            };
            pool.ExecuteIsQuestionIsAnswerableDeterminer();
            pool.ExecutePickListGenerator();
        }
    }

    public class Pool
    {
        public IPickListGenerator PickListGenerator { set; private get; }
        public IQuestionIsAnswerableDeterminer
            IsQuestionIsAnswerableDeterminer { set; private get; }

        public void ExecuteIsQuestionIsAnswerableDeterminer()
        {
            IsQuestionIsAnswerableDeterminer.Execute();
        }

        public void ExecutePickListGenerator()
        {
            PickListGenerator.Execute();
        }
    }
}
</code>```

You probably can stop here, but what if you will always call ExecuteIsQuestionIsAnswerableDeterminer() before ExecutePickListGenerator() call? then you can refacor code as follows:

```<code>    public class Pool
    {
        public IPickListGenerator PickListGenerator { set; private get; }
        public IQuestionIsAnswerableDeterminer
            IsQuestionIsAnswerableDeterminer { set; private get; }

        public void Execute()
        {
            // improvements, seen by Arnis
            if (IsQuestionIsAnswerableDeterminer == null)
            {
                thrown new ArgumentException("IsQuestionIsAnswerableDeterminer");
            }
            if (PickListGenerator == null)
            {
                thrown new ArgumentException("PickListGenerator");
            }
            IsQuestionIsAnswerableDeterminer.Execute();
            PickListGenerator.Execute();
        }
    }
</code>```

If so, you can write something looks like this:

```<code>var pool = new Pool
{
    PickListGenerator = new SportsPicklistGenerator(),
    IsQuestionIsAnswerableDeterminer = new GameQuestionIsAnswerableDeterminer()
};
pool.Execute();

// reuse the same class logic in Pool class in Execute method
pool.PickListGenerator = new GamePickListGenerator();
pool.Execute();

// reuse the same class logic in Pool class in Execute method
pool.IsQuestionIsAnswerableDeterminer = new RoundQuestionIsAnswerableDeterminer();
pool.Execute();
</code>```

As @Adam Robinson said, it changes some logic of Pool (to fix this you can use close Pool implementation), so you can fix it in this way, introducing new interface, IPool, adding private constructor to Pool class and static logic instantiation, that will eliminate the need of a swith statement completely:

```<code>public interface IPool
{
    void Execute();
}

public class Pool : IPool
{
    private Pool() { }

    public IPickListGenerator PickListGenerator { set; private get; }
    public IQuestionIsAnswerableDeterminer IsQuestionIsAnswerableDeterminer { set; private get; }

    public static IPool GetSportsGame()
    {
        return new Pool
        {
            PickListGenerator = new SportsPicklistGenerator(),
            IsQuestionIsAnswerableDeterminer = new GameQuestionIsAnswerableDeterminer()
        };
    }
    public static IPool GetSportsEntertainment()
    {
        return new Pool
        {
            PickListGenerator = new SportsPicklistGenerator(),
            IsQuestionIsAnswerableDeterminer = new EntertainmentPicklistGenerator()
        };
    }
    public void Execute()
    {
        IsQuestionIsAnswerableDeterminer.Execute();
        PickListGenerator.Execute();
    }
}
</code>```

This was edited by Arnis:

```<code>public class Pool{
  private readonly IPickListGenerator _generator;
  private readonly IQuestionIsAnswerableDeterminer _determiner;
  public Pool(IPickListGenerator generator,
    IQuestionIsAnswerableDeterminer determiner){

    if(determiner==null||generator==null)
      throw new ArgumentNullException();
    _generator=generator;
    _determiner=determiner;
  }

  public void Execute(){
    _determiner.Execute();
    _generator.Execute();
  }
}

var generator=new SportsPicklistGenerator();
var determiner=new GameQuestionIsAnswerableDeterminer();
var pool = new Pool(generator, determiner);
pool.Execute();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a domain model (see example below) that has several interfaces that are determined based upon the value of properties within the model itself.  While the code below "works" it doesn't feel right.  I am sure that there is probably a better approach, but I haven't been able to come up with one.  I would be very interested in getting feedback with some alternate approaches.

public interface IPickListGenerator
    {
        void Execute();
    }

public class SportsPicklistGenerator : IPickListGenerator
{
        public void Execute()
        {
            // Do something
        }
}

public class EntertainmentPicklistGenerator : IPickListGenerator
{
    public void Execute()
    {
        // Do something
    }
}

public interface IQuestionIsAnswerableDeterminer
{
    void Execute();
}

public class GameQuestionIsAnswerableDeterminer : IQuestionIsAnswerableDeterminer
{
    public void Execute()
    {
        // Do something
    }
}

public class RoundQuestionIsAnswerableDeterminer : IQuestionIsAnswerableDeterminer
{
    public void Execute()
    {
        // Do something
    }
}

public class Pool
{
    public enum PoolType
    {
        Sports,
        Entertainment
    }

    public enum DeadlineType
    {
        Game,
        Round
    }

    private IPickListGenerator mPickListGenerator = null;
    private IQuestionIsAnswerableDeterminer mQuestionIsAnswerableDeterminer = null;

    public PoolType Type { get; set; }
    public DeadlineType Deadline { get; set; }

    public IQuestionIsAnswerableDeterminer IsQuestionAnswerableDeterminer
    {
        get
        {
            if (mQuestionIsAnswerableDeterminer == null) SetPoolSpecificInterfaces();
            return mQuestionIsAnswerableDeterminer;
        }
    }

    public IPickListGenerator PickListGenerator
    {
        get
        {
            if (mPickListGenerator == null) SetPoolSpecificInterfaces();
            return mPickListGenerator;
        }
    }

    private void SetPoolSpecificInterfaces()
    {
        switch (Type)
        {
            case Pool.PoolType.Sports:
                mPickListGenerator = new SportsPicklistGenerator();
                break;
            case Pool.PoolType.Entertainment:
                mPickListGenerator = new EntertainmentPicklistGenerator();
                break;
        }

        switch (Deadline)
        {
            case Pool.DeadlineType.Game:
                mQuestionIsAnswerableDeterminer = new GameQuestionIsAnswerableDeterminer();
                break;
            case Pool.DeadlineType.Round:
                mQuestionIsAnswerableDeterminer = new RoundQuestionIsAnswerableDeterminer();
                break;
        }
    }
}
// Example usages:
    var pool = new Pool{ Type = Pool.PoolType.Sports, Deadline = Pool.DeadLineType.Game};
    pool.IsQuestionAnswerableDeterminer.Execute();
    pool.PickListGenerator.Execute();

Body:
You probably need to remove the dependencies from your code. Excessiveness from your code exists is in 2 ways:

you have an excessive code (interfaces)

you have an excessive constraints (enums)

Finally, I've got this, in dialog with Adam, which eliminates exception throws, the need of two switch statement, two enumerations, whilst preserving pool closures and elimination possible errors in code. For each switch statement (each interface implementation pair), you have to implement its own static method instantiating Pool class properly:

public interface IPool
{
    void Execute();
}

public class Pool : IPool
{
    private Pool() { }

    public IPickListGenerator PickListGenerator { set; private get; }
    public IQuestionIsAnswerableDeterminer IsQuestionIsAnswerableDeterminer { set; private get; }

    public static IPool GetSportsGame()
    {
        return new Pool
        {
            PickListGenerator = new SportsPicklistGenerator(),
            IsQuestionIsAnswerableDeterminer = new GameQuestionIsAnswerableDeterminer()
        };
    }
    public static IPool GetSportsEntertainment()
    {
        return new Pool
        {
            PickListGenerator = new SportsPicklistGenerator(),
            IsQuestionIsAnswerableDeterminer = new EntertainmentPicklistGenerator()
        };
    }
    public void Execute()
    {
        IsQuestionIsAnswerableDeterminer.Execute();
        PickListGenerator.Execute();
    }
}

--- History of that post, leading to this solution:

You can improve your code by simplifying the code, because in your implementation, Pool class is limited to enumerations, and if so, the Pool class is not extensible. You probably will have to rewrite SetPoolSpecificInterfaces() again and again, when new requirements and interface implementation comes into view. So the weakest point of the current design is that particular SetPoolSpecificInterfaces() method and if so, not extensible Pool class.

If that is what you required, than interfaces is not really needed. In other case, you will not be dependent upon number of interface implementations (which is actually fixed by the corresponding enum) so, it probably can be be simplified to following code (i fixed the issues), removing these constraints:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Example usages:
            var pool = new Pool
            {
                PickListGenerator = new SportsPicklistGenerator(),
                IsQuestionIsAnswerableDeterminer = new GameQuestionIsAnswerableDeterminer()
            };
            pool.ExecuteIsQuestionIsAnswerableDeterminer();
            pool.ExecutePickListGenerator();
        }
    }

    public class Pool
    {
        public IPickListGenerator PickListGenerator { set; private get; }
        public IQuestionIsAnswerableDeterminer
            IsQuestionIsAnswerableDeterminer { set; private get; }

        public void ExecuteIsQuestionIsAnswerableDeterminer()
        {
            IsQuestionIsAnswerableDeterminer.Execute();
        }

        public void ExecutePickListGenerator()
        {
            PickListGenerator.Execute();
        }
    }
}

You probably can stop here, but what if you will always call ExecuteIsQuestionIsAnswerableDeterminer() before ExecutePickListGenerator() call? then you can refacor code as follows:

    public class Pool
    {
        public IPickListGenerator PickListGenerator { set; private get; }
        public IQuestionIsAnswerableDeterminer
            IsQuestionIsAnswerableDeterminer { set; private get; }

        public void Execute()
        {
            // improvements, seen by Arnis
            if (IsQuestionIsAnswerableDeterminer == null)
            {
                thrown new ArgumentException("IsQuestionIsAnswerableDeterminer");
            }
            if (PickListGenerator == null)
            {
                thrown new ArgumentException("PickListGenerator");
            }
            IsQuestionIsAnswerableDeterminer.Execute();
            PickListGenerator.Execute();
        }
    }

If so, you can write something looks like this:

var pool = new Pool
{
    PickListGenerator = new SportsPicklistGenerator(),
    IsQuestionIsAnswerableDeterminer = new GameQuestionIsAnswerableDeterminer()
};
pool.Execute();

// reuse the same class logic in Pool class in Execute method
pool.PickListGenerator = new GamePickListGenerator();
pool.Execute();

// reuse the same class logic in Pool class in Execute method
pool.IsQuestionIsAnswerableDeterminer = new RoundQuestionIsAnswerableDeterminer();
pool.Execute();

As @Adam Robinson said, it changes some logic of Pool (to fix this you can use close Pool implementation), so you can fix it in this way, introducing new interface, IPool, adding private constructor to Pool class and static logic instantiation, that will eliminate the need of a swith statement completely:

public interface IPool
{
    void Execute();
}

public class Pool : IPool
{
    private Pool() { }

    public IPickListGenerator PickListGenerator { set; private get; }
    public IQuestionIsAnswerableDeterminer IsQuestionIsAnswerableDeterminer { set; private get; }

    public static IPool GetSportsGame()
    {
        return new Pool
        {
            PickListGenerator = new SportsPicklistGenerator(),
            IsQuestionIsAnswerableDeterminer = new GameQuestionIsAnswerableDeterminer()
        };
    }
    public static IPool GetSportsEntertainment()
    {
        return new Pool
        {
            PickListGenerator = new SportsPicklistGenerator(),
            IsQuestionIsAnswerableDeterminer = new EntertainmentPicklistGenerator()
        };
    }
    public void Execute()
    {
        IsQuestionIsAnswerableDeterminer.Execute();
        PickListGenerator.Execute();
    }
}

This was edited by Arnis:

public class Pool{
  private readonly IPickListGenerator _generator;
  private readonly IQuestionIsAnswerableDeterminer _determiner;
  public Pool(IPickListGenerator generator,
    IQuestionIsAnswerableDeterminer determiner){

    if(determiner==null||generator==null)
      throw new ArgumentNullException();
    _generator=generator;
    _determiner=determiner;
  }

  public void Execute(){
    _determiner.Execute();
    _generator.Execute();
  }
}

var generator=new SportsPicklistGenerator();
var determiner=new GameQuestionIsAnswerableDeterminer();
var pool = new Pool(generator, determiner);
pool.Execute();


问:
numpy - changes shape automatically?
I am a little bit confused by numpy.

```<code>train_images = load_images(X_train[:205])
print(train_images.shape)
train_images = load_images(X_train[:206])
print(train_images.shape)
</code>```

results in:

```<code>(205, 12288)
(206,)
</code>```

Is this a bug or how can I force numpy to keep the shape?

Here is my image load func:

```<code>def load_image(f):
    im = Image.open(path+f)
    result = np.array(list(im.getdata())).ravel()
    return result

def load_images(fs):
    result = list()
    for f in fs:
        result.append(load_image(f))
    return np.array(result)
</code>```

EDIT: The answer is that all images have to be of the same size.. And exactly one image had another size..

答: The answer is that all images have to be of the same size.. And exactly one image had another size..</p>

Title: numpy - changes shape automatically?

Body:
I am a little bit confused by numpy.

train_images = load_images(X_train[:205])
print(train_images.shape)
train_images = load_images(X_train[:206])
print(train_images.shape)

results in:

(205, 12288)
(206,)

Is this a bug or how can I force numpy to keep the shape?

Here is my image load func:

def load_image(f):
    im = Image.open(path+f)
    result = np.array(list(im.getdata())).ravel()
    return result

def load_images(fs):
    result = list()
    for f in fs:
        result.append(load_image(f))
    return np.array(result)

EDIT: The answer is that all images have to be of the same size.. And exactly one image had another size..


问:
Running a Dash app within a Flask app
I have an existing Flask app, and I want to have a route to another app. More concretely, the second app is a Plotly Dash app. How can I run my Dash app within my existing Flask app?

```<code>@app.route('/plotly_dashboard')
def render_dashboard():
    # go to dash app
</code>```

I also tried adding a route to the Dash instance, since it's a Flask app, but I get the error:

```<code>AttributeError: 'Dash' object has no attribute 'route'
</code>```

答:
Set url_base_pathname in your Dash instance.

```<code>app_flask = flask.Flask(__name__)

app_dash = dash.Dash(__name__, server=app_flask, url_base_pathname='/pathname')
</code>```

Now you can redirect to your Plotly Dashboard app under any Flask routes you want.

```<code>@app_flask.route('/plotly_dashboard')
def render_dashboard():
    return flask.redirect('/pathname')
</code>```

Title: Running a Dash app within a Flask app

Body:
I have an existing Flask app, and I want to have a route to another app. More concretely, the second app is a Plotly Dash app. How can I run my Dash app within my existing Flask app?

@app.route('/plotly_dashboard')
def render_dashboard():
    # go to dash app

I also tried adding a route to the Dash instance, since it's a Flask app, but I get the error:

AttributeError: 'Dash' object has no attribute 'route'

Body:
Set url_base_pathname in your Dash instance.

app_flask = flask.Flask(__name__)

app_dash = dash.Dash(__name__, server=app_flask, url_base_pathname='/pathname')

Now you can redirect to your Plotly Dashboard app under any Flask routes you want.

@app_flask.route('/plotly_dashboard')
def render_dashboard():
    return flask.redirect('/pathname')


问:
how can a function check for null in typescript?
in typescript 2.6 I want to write a function that does a null check. When I enable strict null-checks, typescript 2.6 complains about the following code. (Note that when using the null check directly works)

edited: corrected notNullOrUndefined since it didn't check for foo

```<code>interface A {
  foo: string | undefined;
}
const notNullOrUndefined = (a: A): boolean => {
  return a.foo != null;
}
const len = (a: A): number => {
  //if (a.foo != null) {
  if (notNullOrUndefined(a)){
    return a.foo.length;
  }
  return 0;
}
</code>```

here is the example to play with: example

What's the typescript way to solve this?

答:
This code will check for null.

```<code>"use strict";

function isNull(something: any) {
    return something === null;
}

function checkForNull() {
    console.log(isNull(''));
    console.log(isNull(null));
    console.log(isNull(undefined));
}

checkForNull();
</code>```

Output:

```<code>false
true
false
</code>```

Body:
in typescript 2.6 I want to write a function that does a null check. When I enable strict null-checks, typescript 2.6 complains about the following code. (Note that when using the null check directly works)

edited: corrected notNullOrUndefined since it didn't check for foo

interface A {
  foo: string | undefined;
}
const notNullOrUndefined = (a: A): boolean => {
  return a.foo != null;
}
const len = (a: A): number => {
  //if (a.foo != null) {
  if (notNullOrUndefined(a)){
    return a.foo.length;
  }
  return 0;
}

here is the example to play with: <a href="https://www.typescriptlang.org/play/#src=interface%20A%20%7B%0D%0A%20%20foo%3A%20string%20%7C%20undefined%3B%0D%0A%7D%0D%0Aconst%20notNullOrUndefined%20%3D%20(a%3A%20A)%3A%20boolean%20%3D%3E%20%7B%0D%0A%20%20return%20a.foo%20!%3D%20null%3B%0D%0A%7D%0D%0Aconst%20len%20%3D%20(a%3A%20A)%3A%20number%20%3D%3E%20%7B%0D%0A%20%20%2F%2Fif%20(a.foo%20!%3D%20null)%20%7B%0D%0A%20%20if%20(notNullOrUndefined(a))%7B%0D%0A%20%20%20%20return%20a.foo.length%3B%0D%0A%20%20%7D%0D%0A%20%20return%200%3B%0D%0A%7D%20" rel="nofollow noreferrer">example

What's the typescript way to solve this?

Body:
This code will check for null.

"use strict";

function isNull(something: any) {
    return something === null;
}

function checkForNull() {
    console.log(isNull(''));
    console.log(isNull(null));
    console.log(isNull(undefined));
}

checkForNull();

Output:

false
true
false


问:
Why are my Airflow tasks queued but not running?
I am new to airflow and trying to setup airflow to run ETL pipelines. I was able to install

airflow

postgres

celery

rabbitmq

I am able to test run the tutorial dag. When I try to schedule the jobs, scheduler is able to pick it up and queue the jobs which I could see on the UI but tasks are not running. Could somebody help me fix this issue?

Here is my config file:

```<code>[core]

airflow_home = /root/airflow

dags_folder = /root/airflow/dags

base_log_folder = /root/airflow/logs

executor = CeleryExecutor

sql_alchemy_conn = postgresql+psycopg2://xxxx.amazonaws.com:5432/airflow

api_client = airflow.api.client.local_client

[webserver]

web_server_host = 0.0.0.0

web_server_port = 8080

web_server_worker_timeout = 120

worker_refresh_batch_size = 1

worker_refresh_interval = 30

[celery]

celery_app_name = airflow.executors.celery_executor

celeryd_concurrency = 16

worker_log_server_port = 8793

broker_url = amqp://rabbit:rabbit@x.x.x.x/rabbitmq_vhost

celery_result_backend = db+postgresql+psycopg2://postgres:airflow@xxx.amazonaws.com:5432/airflow

flower_host = 0.0.0.0

flower_port = 5555

default_queue = default
</code>```

DAG: This is the tutorial dag i used

and the start date for my dag is -- 'start_date': datetime(2017, 4, 11),

答:
I realise your problem is already answered and was related to a celery version mismatch, but I've also seen tasks queue and never run because I changed the logs location to a place where the airflow service user did not have permission to write.

In the example airflow.cfg given in the question above:
base_log_folder = /root/airflow/logs

I am using AWS EC2 machine and changed the logs to write to
base_log_folder = /mnt/airflow/logs

In the UI there is no indication given as to why tasks are queued, it just says "unknown, all dependencies are met ..." Giving the airflow daemon/service user permission to write fixed it.

ContentLicense: CC BY-SA 4.0

Body:
I am new to airflow and trying to setup airflow to run ETL pipelines. I was able to install

airflow

postgres

celery

rabbitmq

I am able to test run the tutorial dag. When I try to schedule the jobs, scheduler is able to pick it up and queue the jobs which I could see on the UI but tasks are not running. Could somebody help me fix this issue?

Here is my config file:

[core]

airflow_home = /root/airflow

dags_folder = /root/airflow/dags

base_log_folder = /root/airflow/logs

executor = CeleryExecutor

sql_alchemy_conn = postgresql+psycopg2://xxxx.amazonaws.com:5432/airflow

api_client = airflow.api.client.local_client

[webserver]

web_server_host = 0.0.0.0

web_server_port = 8080

web_server_worker_timeout = 120

worker_refresh_batch_size = 1

worker_refresh_interval = 30

[celery]

celery_app_name = airflow.executors.celery_executor

celeryd_concurrency = 16

worker_log_server_port = 8793

broker_url = amqp://rabbit:rabbit@x.x.x.x/rabbitmq_vhost

celery_result_backend = db+postgresql+psycopg2://postgres:airflow@xxx.amazonaws.com:5432/airflow

flower_host = 0.0.0.0

flower_port = 5555

default_queue = default

DAG: This is the tutorial dag i used

and the start date for my dag is -- 'start_date': datetime(2017, 4, 11),


问:
How do I get over my fears of <% %> in my ASP.Net MVC markup?
So I totally buy into the basic tenents of ASP.NET, testability, SoC, HTML control...it's awesome.  However being new to it I have a huge hang up with the markup.  I know it comes from my hatred of classic ASP, and I can't help but feel like I've entered the twilight zone when I see this.

I don't know what the alternative is (can I use server controls, databinding etc...?)

答:
use server side comments <%-- comment --%> to separate blocks and increase readability. use extra line spacing to separate blocks too (SO seems to be killing off my line spacing here for some reason).

```<code>        <%-- Go through each testimonial --%>
        <% foreach (var testimonial in ViewData.Model.Testimonials) { %>

        <div class="testimonialFrame">
            <div class="testimonialHeader"><%= testimonial.summaryText %></div>

            <%-- Show video if available --%>
            <% if (string.IsNullOrEmpty(testimonial.Video.FullURL) == false) { %>

            <div  style="padding-top:12px">
                <% Html.RenderAction("YouTubeControl", "Application", new { youTubeId = testimonial.Video.FullURL }); %>
            </div>

            <% } %>

            <div class="roundedBox" style="margin-top:15px">
                <div id="txtTestimonialText" class="testimonialText paddedBox"><%= testimonial.TestimonialText %></div>
            </div>

            <div class="testimonialFooter"><%= testimonial.name %></div>
        </div>

        <% } %>
</code>```

OwnerDisplayName: Webjedi

LastEditorDisplayName: Fabian Steeg

Body:
use server side comments <%-- comment --%> to separate blocks and increase readability. use extra line spacing to separate blocks too (SO seems to be killing off my line spacing here for some reason).

        <%-- Go through each testimonial --%>
        <% foreach (var testimonial in ViewData.Model.Testimonials) { %>

        <div class="testimonialFrame">
            <div class="testimonialHeader"><%= testimonial.summaryText %></div>

            <%-- Show video if available --%>
            <% if (string.IsNullOrEmpty(testimonial.Video.FullURL) == false) { %>

            <div  style="padding-top:12px">
                <% Html.RenderAction("YouTubeControl", "Application", new { youTubeId = testimonial.Video.FullURL }); %>
            </div>

            <% } %>

            <div class="roundedBox" style="margin-top:15px">
                <div id="txtTestimonialText" class="testimonialText paddedBox"><%= testimonial.TestimonialText %></div>
            </div>

            <div class="testimonialFooter"><%= testimonial.name %></div>
        </div>

        <% } %>

OwnerDisplayName: Simon


答:
Other than potential logical inconsistencies (subsequently setting Type or Deadline will result in the "incorrect" value for your determiner and generator being supplied back to the user), I don't see anything wrong with the design from a larger perspective. This is very similar to the way a lot of factory patterns work: an external interface (or base class) that's implemented by multiple internal concrete classes, the correct instance of which is determined by some sort of discriminating value.

Unless the construction is expensive (and won't always be necessary), I'd suggest moving to smarter properties for Type and Deadline that set the appropriate interface implementation variables in their set blocks rather than loading them lazily in the other properties as you do now.

If the construction is expensive, I would still switch to smarter properties for Type and Deadline and clear out (and do any necessary clean up on) the values that might have been previously set.

Title: How to design domain model with interfaces that are dependent on the model's properties


问:
Get elements to align
I'm currently working on some black boards on my website and sometimes the content isn't the same size in each black board.

so what I've currently got is as following:

Achieved this by using the following code:

```<code>var biggestHeight = 0;
$('.board .content').each(function(){
    if(biggestHeight === 0) biggestHeight = $(this).height();
    if(biggestHeight < $(this).height()) bigghestHeight = $(this).height();
});
biggestHeight = biggestHeight + 15;
$('.board .content').css({
    "height" : biggestHeight + "px",
});
</code>```

I want the boards to be like this: but I want the boards to be different sizes depending on the content size, however I want the boards to be aligned at the bottom behind the grass like the first picture.

Simple example to reproduce the problem (Not exactly reproduced):

.board{
  display: inline-block;
  background: gray;
  width: 30%;
  float: left;
  margin-left: 5px;
}
#boards-container{
  position: relative;
  width: 400px;
}
#boards-container .boards{
  position: absolute
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="boards-container">
  <div class="boards">
      <div class="board">
        <p>1st Event</p>
        <p>2nd Event</p>
        <p>3rd Event 3rd Event 3rd Event 3rd Event 3rd Event</p>
      </div>
      <div class="board">
        (This should align at bottom)
        <p>1st News</p>
      </div>
      <div class="board">
        (This should align at bottom)
        <p>1st Gallery</p>
        <p>2nd Gallery</p>
        <p>3rd Gallery</p>
      </div>
  </div>
</div></code>```

NEED ANSWER TO WORK IN IE9+ aswell

答:
Perhaps not a perfect solution as it does not work in Internet Explorer.
Just a different approach towards the problem using CSS grid.

.wrapper {
  display: grid;
  grid-gap: 10px;
  grid-template-columns:  repeat(3, 140px);
  grid-template-rows: repeat( 4, 70px);
  background-color: #fff;
  color: #444;
}

.box {
  background: #ccc;
  border: 1px solid #444;
  padding: 10px;
  font-size: 14px;
}

.a {
  grid-column: 1;
  grid-row: 1 / 3;
  align-self: stretch;
}

.b {
  grid-column: 2;
  grid-row: 1 / 3;
  align-self: end;
}

.c {
  grid-column: 3;
  grid-row: 1 / 3;
  align-self: stretch;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="box a">
    <p>1st Event</p>
    <p>2nd Event</p>
    <p>3rd Event 3rd Event 3rd Event 3rd Event 3rd Event</p>
  </div>
  <div class="box b">
    (This should align at bottom)
          <p>1st News</p>
  </div>
  <div class="box c">
    (This should align at bottom)
      <p>1st Gallery</p>
      <p>2nd Gallery</p>
      <p>3rd Gallery</p>
  </div>
</div></code>```

Title: Get elements to align

Body:
I'm currently working on some black boards on my website and sometimes the content isn't the same size in each black board.

so what I've currently got is as following:

Achieved this by using the following code:

var biggestHeight = 0;
$('.board .content').each(function(){
    if(biggestHeight === 0) biggestHeight = $(this).height();
    if(biggestHeight < $(this).height()) bigghestHeight = $(this).height();
});
biggestHeight = biggestHeight + 15;
$('.board .content').css({
    "height" : biggestHeight + "px",
});

I want the boards to be like this: but I want the boards to be different sizes depending on the content size, however I want the boards to be aligned at the bottom behind the grass like the first picture.

Simple example to reproduce the problem (Not exactly reproduced):

.board{
  display: inline-block;
  background: gray;
  width: 30%;
  float: left;
  margin-left: 5px;
}
#boards-container{
  position: relative;
  width: 400px;
}
#boards-container .boards{
  position: absolute
}

1st Event

2nd Event

3rd Event 3rd Event 3rd Event 3rd Event 3rd Event

        (This should align at bottom)

1st News

        (This should align at bottom)

1st Gallery

2nd Gallery

3rd Gallery

NEED ANSWER TO WORK IN IE9+ aswell

Body:
Perhaps not a perfect solution as it does not work in Internet Explorer.
Just a different approach towards the problem using CSS grid.

.wrapper {
  display: grid;
  grid-gap: 10px;
  grid-template-columns:  repeat(3, 140px);
  grid-template-rows: repeat( 4, 70px);
  background-color: #fff;
  color: #444;
}

.box {
  background: #ccc;
  border: 1px solid #444;
  padding: 10px;
  font-size: 14px;
}

.a {
  grid-column: 1;
  grid-row: 1 / 3;
  align-self: stretch;
}

.b {
  grid-column: 2;
  grid-row: 1 / 3;
  align-self: end;
}

.c {
  grid-column: 3;
  grid-row: 1 / 3;
  align-self: stretch;
}

<div class="wrapper">
  <div class="box a">
    <p>1st Event</p>
    <p>2nd Event</p>
    <p>3rd Event 3rd Event 3rd Event 3rd Event 3rd Event</p>
  </div>
  <div class="box b">
    (This should align at bottom)
          <p>1st News</p>
  </div>
  <div class="box c">
    (This should align at bottom)
      <p>1st Gallery</p>
      <p>2nd Gallery</p>
      <p>3rd Gallery</p>
  </div>
</div>


问:
highcharts line not showing properly
I'm creating some visualisations using HightCharts. Thought series only for a specific year I automatically draw a line between actual value for the bar and the result-target.

I draw the line in this way:

```<code>{
      dashStyle: 'dash',
      lineWidth: 2,
      shadow: false,
      zIndex: 2,
      color: '#000e3e',
      data: [[0, 5], [3,3]],
        name: 'Line for Project 2 - Results'

    }
</code>```

on the data part I specify to start from column 0 which is first year and 3 which is the Results.

The problem is that in HightCharts when there's more than one value for a year the line doesn't start from the top of the bar but from the middle.

[![enter image description here][1]][1]

Is there any possible way to start drawing line from the top of the bar?

Here's the JS FIDDLE

Highcharts.chart('container', {
    title: {
        text: 'Combination chart'
    },
    xAxis: {
        categories: ['2014', '2015', '2016', 'Results']
    },
    series: [{
        type: 'column',
        name: 'Project 1',
        data: [10, 4, 1]
    }, {
        type: 'column',
        name: 'Project 2',
        data: [5, 4, 5]
    }, {
        type: 'column',
        name: 'Project 3',
        data: [2,8, 3]
    },{
      dashStyle: 'dash',
      lineWidth: 2,
      shadow: false,
      zIndex: 2,
      color: '#000e3e',
      data: [[0, 10], [3,5]],
     name: 'Line for Project 1 - Results'

    },{
      dashStyle: 'dash',
      lineWidth: 2,
      shadow: false,
      zIndex: 2,
      color: '#000e3e',
      data: [[0, 5], [3,3]],
     name: 'Line for Project 2 - Results'

    },{
      dashStyle: 'dash',
      lineWidth: 2,
      shadow: false,
      zIndex: 2,
      color: '#000e3e',
      data: [[0, 2], [3,0]],
     name: 'Line for Project 3 - Results'

    }]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div></code>```

答:
The easiest way to achieve effect you need is by setting the x values of your line series data to floating point number values, instead of integers, for example equal to 0.2 or -0.2. Please take a look on code below:

```<code>{
  dashStyle: 'dash',
  lineWidth: 2,
  shadow: false,
  zIndex: 2,
  color: '#000e3e',
  data: [[-0.2, 10], [3,5]],
    name: 'Line for Project 1 - Results'
}
</code>```

I prepared a JSFiddle example to show you how it looks.

Best regards!

Title: highcharts line not showing properly

Body:
I'm creating some visualisations using HightCharts. Thought series only for a specific year I automatically draw a line between actual value for the bar and the result-target.

I draw the line in this way:

{
      dashStyle: 'dash',
      lineWidth: 2,
      shadow: false,
      zIndex: 2,
      color: '#000e3e',
      data: [[0, 5], [3,3]],
        name: 'Line for Project 2 - Results'

    }

on the data part I specify to start from column 0 which is first year and 3 which is the Results.

The problem is that in HightCharts when there's more than one value for a year the line doesn't start from the top of the bar but from the middle.

[![enter image description here][1]][1]

Is there any possible way to start drawing line from the top of the bar?

Here's the JS FIDDLE

Highcharts.chart('container', {
    title: {
        text: 'Combination chart'
    },
    xAxis: {
        categories: ['2014', '2015', '2016', 'Results']
    },
    series: [{
        type: 'column',
        name: 'Project 1',
        data: [10, 4, 1]
    }, {
        type: 'column',
        name: 'Project 2',
        data: [5, 4, 5]
    }, {
        type: 'column',
        name: 'Project 3',
        data: [2,8, 3]
    },{
      dashStyle: 'dash',
      lineWidth: 2,
      shadow: false,
      zIndex: 2,
      color: '#000e3e',
      data: [[0, 10], [3,5]],
     name: 'Line for Project 1 - Results'

    },{
      dashStyle: 'dash',
      lineWidth: 2,
      shadow: false,
      zIndex: 2,
      color: '#000e3e',
      data: [[0, 5], [3,3]],
     name: 'Line for Project 2 - Results'

    },{
      dashStyle: 'dash',
      lineWidth: 2,
      shadow: false,
      zIndex: 2,
      color: '#000e3e',
      data: [[0, 2], [3,0]],
     name: 'Line for Project 3 - Results'

    }]
});

Body:
The easiest way to achieve effect you need is by setting the x values of your line series data to floating point number values, instead of integers, for example equal to 0.2 or -0.2. Please take a look on code below:

{
  dashStyle: 'dash',
  lineWidth: 2,
  shadow: false,
  zIndex: 2,
  color: '#000e3e',
  data: [[-0.2, 10], [3,5]],
    name: 'Line for Project 1 - Results'
}

I prepared a JSFiddle example to show you how it looks.

Best regards!


问:
Why use ReaderWriterLockSlim?
Learning about ReaderWriterLockSlim. Trying to understand why ReaderWriterLockSlim in better than any other lock like for example Monitor?

What is difference between EnterWriteLock() and EnterReadLock(). I suppose that EnterWriteLock() has more chances to get lock than EnterReadLock(). but I suppose I can use EnterReadLock() in places when I need just write - it only will be slower.

```<code>   class Program
    {

        static ReaderWriterLockSlim _rw = new ReaderWriterLockSlim();
        static List<int> _items = new List<int>();
        static Random _random = new Random();

        static void Main(string[] args)
        {
            new Thread(read).Start() ;
            new Thread(read).Start();
            new Thread(read).Start();

            new Thread(()=>write("A")).Start();
            new Thread(() => write("B")).Start();

        }

        public static void read()
        {
            while (true)
            {
                //_rw.EnterReadLock();
                _rw.EnterWriteLock();
                for (int i = 0; i < _items.Count; i++)
                {
                    Thread.Sleep(1000);
                }
                //_rw.ExitReadLock();
                _rw.ExitWriteLock();
            }
        }

        public static void write(string value)
        {
            while (true)
            {
                int newNumber = GetRandom(100);
                _rw.EnterWriteLock();
                _items.Add(newNumber);
                _rw.ExitWriteLock();
                Console.WriteLine("ThreadID={0} added={1}",Thread.CurrentThread.ManagedThreadId,newNumber);
                Thread.Sleep(100);
            }

        }

        private static int GetRandom(int v)
        {
            lock (_random)
            {
                return _random.Next(v);
            }

        }
    }
</code>```

答:
They have different semantics. A Monitor (lock) allows one thread to own the "lock", and that's it. A ReaderWriterLock[Slim] allows any number of readers, or (one writer and nobody else).

So a reader-writer setup might be useful if writes are rare and reads take a non-trivial amount of time, so that you can have multiple concurrent readers, and yet lock everyone out when you need to mutate the data.

Neither is "better". They do different things. They each have scenarios in which they are ideal, and scenarios in which they are poor choices.

Title: Why use ReaderWriterLockSlim?

Body:
Learning about ReaderWriterLockSlim. Trying to understand why ReaderWriterLockSlim in better than any other lock like for example Monitor?

What is difference between EnterWriteLock() and EnterReadLock(). I suppose that EnterWriteLock() has more chances to get lock than EnterReadLock(). but I suppose I can use EnterReadLock() in places when I need just write - it only will be slower.

   class Program
    {

        static ReaderWriterLockSlim _rw = new ReaderWriterLockSlim();
        static List<int> _items = new List<int>();
        static Random _random = new Random();

        static void Main(string[] args)
        {
            new Thread(read).Start() ;
            new Thread(read).Start();
            new Thread(read).Start();

            new Thread(()=>write("A")).Start();
            new Thread(() => write("B")).Start();

        }

        public static void read()
        {
            while (true)
            {
                //_rw.EnterReadLock();
                _rw.EnterWriteLock();
                for (int i = 0; i < _items.Count; i++)
                {
                    Thread.Sleep(1000);
                }
                //_rw.ExitReadLock();
                _rw.ExitWriteLock();
            }
        }

        public static void write(string value)
        {
            while (true)
            {
                int newNumber = GetRandom(100);
                _rw.EnterWriteLock();
                _items.Add(newNumber);
                _rw.ExitWriteLock();
                Console.WriteLine("ThreadID={0} added={1}",Thread.CurrentThread.ManagedThreadId,newNumber);
                Thread.Sleep(100);
            }

        }

        private static int GetRandom(int v)
        {
            lock (_random)
            {
                return _random.Next(v);
            }

        }
    }


问:
.NET GridView - Can you right-align just one column?
Can you easily right-align just one column in a GridView?

I have this

```<code><asp:GridView ID="GridView1" runat="server"></asp:GridView>
</code>```

It is bound to a DataTable (generated dynamically) that has many columns. I just want the 'Price' column to be right-aligned.

(Coming across this problem, I am wondering if I should be printing out HTML
 instead of using a GridView. Using HTML I would have total control.)

答:
Even though the question posted long ago, this might help someone you happens to end up at this page.

The answers given assume that the index of the column to which the alignment will be applied is known in advance or the columns are created at design time on the .aspx page; but this is not always the case.

For someone looking for a general solution in which the columns are auto generated and the index of column with header ‘Price’ not known in advance, here is a solution

```<code>protected void grData_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int i = ((DataTable)((GridView)sender).DataSource).Columns.IndexOf("Price");
        for (int j = 0; j < e.Row.Cells.Count; j++)
        {
            if (j == i)
                e.Row.Cells[j].HorizontalAlign = HorizontalAlign.Right;
            else
                e.Row.Cells[j].HorizontalAlign = HorizontalAlign.Left;
        }
   }
}
</code>```

Body:
Can you easily right-align just one column in a GridView?

I have this

<asp:GridView ID="GridView1" runat="server"></asp:GridView>

It is bound to a DataTable (generated dynamically) that has many columns. I just want the 'Price' column to be right-aligned.

(Coming across this problem, I am wondering if I should be printing out HTML
 instead of using a GridView. Using HTML I would have total control.)

Body:
Even though the question posted long ago, this might help someone you happens to end up at this page.

The answers given assume that the index of the column to which the alignment will be applied is known in advance or the columns are created at design time on the .aspx page; but this is not always the case.

For someone looking for a general solution in which the columns are auto generated and the index of column with header ‘Price’ not known in advance, here is a solution

protected void grData_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int i = ((DataTable)((GridView)sender).DataSource).Columns.IndexOf("Price");
        for (int j = 0; j < e.Row.Cells.Count; j++)
        {
            if (j == i)
                e.Row.Cells[j].HorizontalAlign = HorizontalAlign.Right;
            else
                e.Row.Cells[j].HorizontalAlign = HorizontalAlign.Left;
        }
   }
}


问:
Python: Finding a substring in a string, but returning True or False instead of the index position
I need to check if a substring is part of a specific string. The substring is 'AAA' and if it is found in the given string, it must return True. If it isn't in the string, it must return False

```<code>def isResistent(virus):
    gen = "AAA"
    if gen in virus:
        print("True")
    else:
        print("False")

isResistent('GCAAGCTGGTCGTGAAAGCT')
</code>```

It returns True or False, but besides True or False it first gives the index number or something. When I run the program several times it returns:

Output:

```<code>2
True

1
True

2
True

4
True

0
True
</code>```

Is it possible to only print True or False?

答:
Your function works fine when you use return instead:

```<code>def isResistent(virus):
    gen = "AAA"
    if gen in virus:
        return True
    else:
        return False

>>> isResistent('GCAAGCTGGTCGTGAAAGCT')
True
>>> isResistent('GCAAGCTGGTCGTGGCTGCT')
False
</code>```

I would also include gen as a function parameter, so you can test other sub strings other than "AAA" in the future:

```<code>def isResistent(virus, gen):
    return gen in virus

>>> isResistent('GCAAGCTGGTCGTGAAAGCT', 'AAA')
True
>>> isResistent('GCAAGCTGGTCGTGGCTGCT', 'AAA')
False
>>> isResistent('GCAAGCTGGTCGTGAAAGCT', 'AGC')
True
</code>```

Body:
I need to check if a substring is part of a specific string. The substring is 'AAA' and if it is found in the given string, it must return True. If it isn't in the string, it must return False

def isResistent(virus):
    gen = "AAA"
    if gen in virus:
        print("True")
    else:
        print("False")

isResistent('GCAAGCTGGTCGTGAAAGCT')

It returns True or False, but besides True or False it first gives the index number or something. When I run the program several times it returns:

Output:

2
True

1
True

2
True

4
True

0
True

Is it possible to only print True or False?

Body:
Your function works fine when you use return instead:

def isResistent(virus):
    gen = "AAA"
    if gen in virus:
        return True
    else:
        return False

>>> isResistent('GCAAGCTGGTCGTGAAAGCT')
True
>>> isResistent('GCAAGCTGGTCGTGGCTGCT')
False

I would also include gen as a function parameter, so you can test other sub strings other than "AAA" in the future:

def isResistent(virus, gen):
    return gen in virus

>>> isResistent('GCAAGCTGGTCGTGAAAGCT', 'AAA')
True
>>> isResistent('GCAAGCTGGTCGTGGCTGCT', 'AAA')
False
>>> isResistent('GCAAGCTGGTCGTGAAAGCT', 'AGC')
True


问:
HTTP Error 403.14 - Forbidden - MVC 4 with IIS Express
This seems like a question that has already been asked/answered many times. Its not.

Development Environment:
VS 2012 and MVC 4. I am using the built in IIS Express to run the app.

This error was not occurring until yesterday. It suddenly began to occur and I am stuck. Its strange that It occurs only in ONE scenario.

When I try to access http://localhost:49962/managescholars/, it shows me the error

```<code>HTTP Error 403.14 - Forbidden
The Web server is configured to not list the contents of this directory.
</code>```

But using http://localhost:49962/managescholars/Index works fine. Other action methods of same controller also work fine. such as http://localhost:49962/managescholars/create. All other controllers work fine as well.

I have tried adding the following to web.config.

```<code><system.webServer>
  <validation validateIntegratedModeConfiguration="false"/>
  <modules runAllManagedModulesForAllRequests="true" />
  <handlers/>
</system.webServer>
</code>```

I also have tried running the following command as administrator

```<code>%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir
</code>```

But none of them worked.

Edit:

I have modified my routes. They look as follows.

```<code>    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "ManageScholarLectures",
            url: "Manage/Lectures/{userFriendlyName}",
            defaults: new { controller = MVC.ManageLectures.Name ,
                            action = MVC.ManageLectures.ActionNames.Index,
                            userFriendlyName = UrlParameter.Optional }
        );

        routes.MapRoute(
            name: "ManageScholarEdit",
            url: "Manage/Scholars/{userFriendlyName}",
            defaults: new { controller = MVC.ManageScholars.Name,
                            action = MVC.ManageScholars.ActionNames.Edit }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = MVC.Home.Name,
                            action = MVC.Home.ActionNames.Index,
                            id = UrlParameter.Optional }
        );
    }
</code>```

I am using T4MVC template.

It still does not work even if I leave the default route at the bottom and remove the first two routes. What have I done wrong?

Thanks a lot in advance for your help.

答:
In my case, with Visual Studio 2015, I solved the problem with the following steps:

Stop IIS Express

Close Visual studio

Delete file applicationhost.config in {my solution directory}.vs\config

Delete directory Documents\IISExpress\config

Start VS, F5 and enjoy :)

Body:
This seems like a question that has already been asked/answered many times. Its not.

Development Environment:
VS 2012 and MVC 4. I am using the built in IIS Express to run the app.

This error was not occurring until yesterday. It suddenly began to occur and I am stuck. Its strange that It occurs only in ONE scenario.

When I try to access http://localhost:49962/managescholars/, it shows me the error

HTTP Error 403.14 - Forbidden
The Web server is configured to not list the contents of this directory.

But using http://localhost:49962/managescholars/Index works fine. Other action methods of same controller also work fine. such as http://localhost:49962/managescholars/create. All other controllers work fine as well.

I have tried adding the following to web.config.

<system.webServer>
  <validation validateIntegratedModeConfiguration="false"/>
  <modules runAllManagedModulesForAllRequests="true" />
  <handlers/>
</system.webServer>

I also have tried running the following command as administrator

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir

But none of them worked.

Edit:

I have modified my routes. They look as follows.

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "ManageScholarLectures",
            url: "Manage/Lectures/{userFriendlyName}",
            defaults: new { controller = MVC.ManageLectures.Name ,
                            action = MVC.ManageLectures.ActionNames.Index,
                            userFriendlyName = UrlParameter.Optional }
        );

        routes.MapRoute(
            name: "ManageScholarEdit",
            url: "Manage/Scholars/{userFriendlyName}",
            defaults: new { controller = MVC.ManageScholars.Name,
                            action = MVC.ManageScholars.ActionNames.Edit }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = MVC.Home.Name,
                            action = MVC.Home.ActionNames.Index,
                            id = UrlParameter.Optional }
        );
    }

I am using T4MVC template.

It still does not work even if I leave the default route at the bottom and remove the first two routes. What have I done wrong?

Thanks a lot in advance for your help.


问:
Visual studio 2017 intellisense errors got mixed-up after crash
During a heavy code-refactoring session, I got a BSOD (Blue Screen Of Death). After restart, Visual Studio started to exhibit a strange intellisense problem:

(I was in the midst of refactoring a file with few thousand lines of code, with about a hundred errors)

After a build, the errors were at the right locations. After fixing any of them, all intellisense errors moved around like crazy and became unusable. I needed another F6 (build) and wait until things sort out.

I deleted every non source controlled folder in my solution, deleted the cache, ... Nothing seemed to solve the problem.

答:
The problem turns out to be system time!!

After the crash, my system time went back a few hours.
After I fixed the time, the problem got solved.

PS: the reason for hour change is this: I've got a dual-boot Windows-Linux (Fedora). Fedora keeps the system time in UTC, while windows keeps it in Local time. So after any restart from Linux to Windows, I've got the wrong time.


问:
Navigation drawer without AppCompat theme
I am trying to setup navigation drawer "without" AppCompat. I am getting an error You need to use a Theme.AppCompat theme (or descendant) with the design library
Any ideas?

I setup my `styles.xml as:

```<code><resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="@android:style/Theme.Material.Light">
        <!-- Customize your theme here. -->
    </style>
</resources>
</code>```

and in my AndroidManifest.xml file I have the android:theme="@style/AppTheme" only.

My activity_main.xml has:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!" />

    </RelativeLayout>
    <!-- The navigation drawer -->
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
</code>```

nav_header_main and activity_main drawer contents are same as from android studio examples and my MainActivity onCreate function is pretty straightforward:

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
</code>```

My build.bradle dependencies are:

```<code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:support-v13:26.1.0'
    implementation 'com.android.support:design:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
</code>```

The error is:

```<code>12-08 15:11:19.095 16936-16936/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.xxx.xxx, PID: 16936
                                                   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxx.xxx/com.xxx.xxx.MainActivity}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class android.support.design.widget.NavigationView
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2684)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751)
                                                       at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6186)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
                                                    Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class android.support.design.widget.NavigationView
                                                    Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class android.support.design.widget.NavigationView
                                                    Caused by: java.lang.reflect.InvocationTargetException
                                                       at java.lang.reflect.Constructor.newInstance0(Native Method)
                                                       at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
                                                       at android.view.LayoutInflater.createView(LayoutInflater.java:645)
                                                       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:787)
                                                       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
                                                       at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
                                                       at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
                                                       at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:412)
                                                       at android.app.Activity.setContentView(Activity.java:2415)
                                                       at com.xxx.xxx.MainActivity.onCreate(MainActivity.java:24)
                                                       at android.app.Activity.performCreate(Activity.java:6684)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2637)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751)
                                                       at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6186)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
                                                    Caused by: java.lang.IllegalArgumentException: You need to use a Theme.AppCompat theme (or descendant) with the design library.
                                                       at android.support.design.widget.ThemeUtils.checkAppCompatTheme(ThemeUtils.java:33)
                                                       at android.support.design.widget.NavigationView.<init>(NavigationView.java:104)
                                                       at android.support.design.widget.NavigationView.<init>(NavigationView.java:98)
                                                       at java.lang.reflect.Constructor.newInstance0(Native Method)
                                                       at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
                                                       at android.view.LayoutInflater.createView(LayoutInflater.java:645)
                                                       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:787)
                                                       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
                                                       at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
                                                       at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
                                                       at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:412)
                                                       at android.app.Activity.setContentView(Activity.java:2415)
                                                       at com.xxx.xxx.MainActivity.onCreate(MainActivity.java:24)
                                                       at android.app.Activity.performCreate(Activity.java:6684)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2637)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751)
                                                       at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6186)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
</code>```

答:
```<code><style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">

    <item name="colorPrimary">#873AB0</item>
    <item name="colorPrimaryDark">#256DA8</item>
    <item name="colorAccent">#11BCD4</item>
    <item name="android:textColorPrimary">#212222</item>
    <item name="android:textColorSecondary">#646464</item>

</style>
</code>```

from above snippet remove

```<code>        <item name="android:textColorPrimary">#212222</item>
        <item name="android:textColorSecondary">#646464</item>
</code>```

check Example

Hope this helps you.

Body:
I am trying to setup navigation drawer "without" AppCompat. I am getting an error You need to use a Theme.AppCompat theme (or descendant) with the design library
Any ideas?

I setup my `styles.xml as:

<resources>

</resources>

and in my AndroidManifest.xml file I have the android:theme="@style/AppTheme" only.

My activity_main.xml has:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!" />

    </RelativeLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>

nav_header_main and activity_main drawer contents are same as from android studio examples and my MainActivity onCreate function is pretty straightforward:

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

My build.bradle dependencies are:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:support-v13:26.1.0'
    implementation 'com.android.support:design:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

The error is:

12-08 15:11:19.095 16936-16936/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.xxx.xxx, PID: 16936
                                                   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxx.xxx/com.xxx.xxx.MainActivity}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class android.support.design.widget.NavigationView
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2684)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751)
                                                       at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6186)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
                                                    Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class android.support.design.widget.NavigationView
                                                    Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class android.support.design.widget.NavigationView
                                                    Caused by: java.lang.reflect.InvocationTargetException
                                                       at java.lang.reflect.Constructor.newInstance0(Native Method)
                                                       at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
                                                       at android.view.LayoutInflater.createView(LayoutInflater.java:645)
                                                       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:787)
                                                       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
                                                       at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
                                                       at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
                                                       at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:412)
                                                       at android.app.Activity.setContentView(Activity.java:2415)
                                                       at com.xxx.xxx.MainActivity.onCreate(MainActivity.java:24)
                                                       at android.app.Activity.performCreate(Activity.java:6684)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2637)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751)
                                                       at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6186)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
                                                    Caused by: java.lang.IllegalArgumentException: You need to use a Theme.AppCompat theme (or descendant) with the design library.
                                                       at android.support.design.widget.ThemeUtils.checkAppCompatTheme(ThemeUtils.java:33)
                                                       at android.support.design.widget.NavigationView.<init>(NavigationView.java:104)
                                                       at android.support.design.widget.NavigationView.<init>(NavigationView.java:98)
                                                       at java.lang.reflect.Constructor.newInstance0(Native Method)
                                                       at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
                                                       at android.view.LayoutInflater.createView(LayoutInflater.java:645)
                                                       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:787)
                                                       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
                                                       at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
                                                       at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
                                                       at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:412)
                                                       at android.app.Activity.setContentView(Activity.java:2415)
                                                       at com.xxx.xxx.MainActivity.onCreate(MainActivity.java:24)
                                                       at android.app.Activity.performCreate(Activity.java:6684)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2637)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751)
                                                       at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6186)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

Body:
<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">

    <item name="colorPrimary">#873AB0</item>
    <item name="colorPrimaryDark">#256DA8</item>
    <item name="colorAccent">#11BCD4</item>
    <item name="android:textColorPrimary">#212222</item>
    <item name="android:textColorSecondary">#646464</item>

</style>

from above snippet remove

        <item name="android:textColorPrimary">#212222</item>
        <item name="android:textColorSecondary">#646464</item>

check Example

Hope this helps you.


问:
Angular 2: How to access an HTTP response body?
I wrote the following code in Angular 2:

```<code>this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
      subscribe((res: Response) => {
        console.log(res);
      })
</code>```

When I print the response I get in console:

I want to have access in the code to body field in the response. The 'body' field starts with an underscore, which means that it's a private field. When I change it to 'console.log(res._body)' I got an error.

Do you know any getter function that can help me here?

答:
```<code>.subscribe(data => {
            console.log(data);
            let body:string = JSON.parse(data['_body']);`
</code>```

Body:
I wrote the following code in Angular 2:

this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
      subscribe((res: Response) => {
        console.log(res);
      })

When I print the response I get in console:

I want to have access in the code to body field in the response. The 'body' field starts with an underscore, which means that it's a private field. When I change it to 'console.log(res._body)' I got an error.

Do you know any getter function that can help me here?


问:
Python: PyCharm show "shape" by "mouse over"
When debugging manipulations of large np-arrays with PyCharm I have encountered the problem that there is no quick way to check the shape of the array as hoovering the mouse over a variable shows only the first and last three elements:

Is there a way to show 500 x 1000 x 4 x 45 instead? Pressing ctrl+F1 and scrolling to the shape property becomes a bit tiresome after a while ...

答:
I am looking for the same features. So far, I found this solution:

in the debug view, open the console

click "Show Python Prompt"

in the prompt enter

```<code>import numpy as np
np.set_string_function(lambda a: str(a.shape), repr=False)
</code>```

Body:
I am looking for the same features. So far, I found this solution:

in the debug view, open the console

click "Show Python Prompt"

in the prompt enter

import numpy as np
np.set_string_function(lambda a: str(a.shape), repr=False)


问:
How can I Open Multiple Popups in Leaflet Marker at a time
Map` like this:

```<code>L.Map = L.Map.extend({
openPopup: function(popup) {
this._popup = popup;
        return this.addLayer(popup).fire('popupopen', {
            popup: this._popup
        });
    }
});
</code>```

But I am using leaflet. Is there anyway to extent like so that i can prevent closing my marker popup?

```<code>L.mapbox.accessToken = constant.accessToken;
var map = L.mapbox.map('map', 'mapbox.streets', {zoomControl: true});
</code>```

答:
Update Dec 2017
Leaflet popup options have been extended to include { autoClose: false } which has the required effect :

 var my_marker = L.marker([my_lat, my_lng], {icon: my_icon})
                  .addTo(map)
                  .bindPopup('My Popup HTML', {closeOnClick: false, autoClose: false});
```

Body:
Map` like this:

L.Map = L.Map.extend({
openPopup: function(popup) {
this._popup = popup;
        return this.addLayer(popup).fire('popupopen', {
            popup: this._popup
        });
    }
});

But I am using leaflet. Is there anyway to extent like so that i can prevent closing my marker popup?

L.mapbox.accessToken = constant.accessToken;
var map = L.mapbox.map('map', 'mapbox.streets', {zoomControl: true});


问:
configure qiskit on win10 error:numpy.distutils.system_info.NotFoundError: no lapack/blas resources found
I’m new to python and I got some problem when trying to install QISKit.

First, I was using pip install qiskit on cmd, but it showed an error

```<code>numpy.distutils.system_info.NotFoundError: no lapack/blas resources found
</code>```

I searched on internet and pip install scipy separately. It worked

```<code>Collecting scipy
  Using cached scipy-1.0.0-cp36-none-win32.whl
Requirement already satisfied: numpy>=1.8.2 in
d:\programming\python\lib\site-packages (from scipy)
Installing collected packages: scipy
Successfully installed scipy-1.0.0
</code>```

Then I tried pip install qiskit again. It showed an error:

```<code>Found existing installation: scipy 1.0.0
Uninstalling scipy-1.0.0:
  Successfully uninstalled scipy-1.0.0
Running setup.py install for scipy ... error

……

numpy.distutils.system_info.NotFoundError: no lapack/blas resources found

----------------------------------------
Rolling back uninstall of scipy
</code>```

So I used the second way:

```<code>git clone https://github.com/QISKit/qiskit-sdk-py

cd qiskit-sdk-py
</code>```

then

```<code>pip install -r requirements.txt
</code>```

again

```<code>Installing collected packages: scipy, sympy
  Found existing installation: scipy 1.0.0
    Uninstalling scipy-1.0.0:
      Successfully uninstalled scipy-1.0.0
  Running setup.py install for scipy ... error

……

    numpy.distutils.system_info.NotFoundError: no lapack/blas resources found

    ----------------------------------------
     Rolling back uninstall of scipy
</code>```

how can I solve this and add QISKit to python lib?

reference:

https://github.com/QISKit/qiskit-sdk-py/blob/master/doc/install.rst#3.1-Setup-the-environment

答:
Installing scipy, at least the version currently required by QISKit, on Windows requires that you have a couple of different compilers installed, which you probably don't. I recommend you install Anaconda. If you download the full Anaconda package, it includes the appropriate scipy binary, or alternatively you can do conda install scipy=0.19 before you do pip install qiskit.

I think that should fix your current issue but feel free to reach out with any others -- I'll be happy to help. You can also find more documentation at qiskit.org, github.com/QISKit/qiskit-sdk-py, and on the IBM Q experience community forums.

Cheers,
Doug

Body:
I’m new to python and I got some problem when trying to install QISKit.

First, I was using pip install qiskit on cmd, but it showed an error

numpy.distutils.system_info.NotFoundError: no lapack/blas resources found

I searched on internet and pip install scipy separately. It worked

Collecting scipy
  Using cached scipy-1.0.0-cp36-none-win32.whl
Requirement already satisfied: numpy>=1.8.2 in
d:\programming\python\lib\site-packages (from scipy)
Installing collected packages: scipy
Successfully installed scipy-1.0.0

Then I tried pip install qiskit again. It showed an error:

Found existing installation: scipy 1.0.0
Uninstalling scipy-1.0.0:
  Successfully uninstalled scipy-1.0.0
Running setup.py install for scipy ... error

……

numpy.distutils.system_info.NotFoundError: no lapack/blas resources found

----------------------------------------
Rolling back uninstall of scipy

So I used the second way:

git clone https://github.com/QISKit/qiskit-sdk-py

cd qiskit-sdk-py

then

pip install -r requirements.txt

again

Installing collected packages: scipy, sympy
  Found existing installation: scipy 1.0.0
    Uninstalling scipy-1.0.0:
      Successfully uninstalled scipy-1.0.0
  Running setup.py install for scipy ... error

……

    numpy.distutils.system_info.NotFoundError: no lapack/blas resources found

    ----------------------------------------
     Rolling back uninstall of scipy

how can I solve this and add QISKit to python lib?

reference:

https://github.com/QISKit/qiskit-sdk-py/blob/master/doc/install.rst#3.1-Setup-the-environment