问:
Questions about operator overloading
I have two questions about operator overloading.

For an iterator type, how is operator-> overloaded? What value should it return assuming that it is an iterator for a collection of class T objects?

Why does operator++() return by class T& while operator++(int) return by class T? I understand these two represent prefix increment and postfix increment. But why the difference in return value?

EDIT: For Alf. Code is not complete though functioning. Any suggestions for improvement are welcome.

```<code>#ifndef DHASH_H
#define DHASH_H

//#include <vector>
#include <memory>
#include <exception>
#include <new>
#include <algorithm>
#include <functional>

namespace MCol
{
    template <typename KEY, typename VALUE, typename HASH_FUNCTION, typename KEY_COMP = std::equal_to<KEY> >
        class hash_container
        {
            private:
                struct entry
                {
                    KEY _k;
                    VALUE _v;

                    entry(const KEY& k, const VALUE& v)
                        :_k(k), _v(v)
                    {}

                    entry& operator=(const entry& e)
                    {
                        this->_k = e._k;
                        this->_v = e._v;
                    }
                };

            private:
                struct bucket
                {
                    entry* a_Entries;
                    size_t sz_EntryCount;

                    bucket()
                    {
                        sz_EntryCount = 0;
                        a_Entries = NULL;
                    }

                    ~bucket()
                    {
                        for(size_t szI = 0; szI < sz_EntryCount; ++szI)
                        {
                            a_Entries[szI].~entry();
                        }
                        free(a_Entries);
                    }

                    //Grow by 1. (Perhaps later try block increment. But wikipedia suggests that there is little difference between the two)
                    inline bool insert(const KEY& k, const VALUE& v) throw (std::bad_alloc)
                    {
                        if(find(k) != NULL)
                        {
                            return false;
                        }
                        a_Entries = static_cast<entry*>(realloc(a_Entries, sizeof(entry)*(++sz_EntryCount)));
                        if(a_Entries == NULL)
                        {
                            throw std::bad_alloc();
                        }

                        new (&a_Entries[sz_EntryCount - 1]) entry(k, v);
                        return true;
                    }

                    //Find entry, swap with last valid entry, remove if necessary.
                    inline bool erase(const KEY& k) throw(std::bad_alloc)
                    {
                        //Forwards or backwards? My guess is backwards is better.
                        entry* pE = a_Entries;
                        while(pE != a_Entries + sz_EntryCount)
                        {
                            if(pE->_k == k)
                            {
                                break;
                            }
                            ++pE;
                        }

                        if(pE == a_Entries + sz_EntryCount)
                        {
                            return false;
                        }

                        //We don't need to swap if the entry is the only one in the bucket or if it is the last one.
                        entry* pLast = a_Entries + sz_EntryCount - 1;
                        if((sz_EntryCount > 1) && (pE != pLast))
                        {
                            pE = pLast;
                        }

                        a_Entries = static_cast<entry*>(realloc(a_Entries, sizeof(entry)*(--sz_EntryCount)));
                        if(a_Entries == NULL && sz_EntryCount > 0)
                        {
                            throw std::bad_alloc();
                        }

                        return true;
                    }

                    inline entry* find(const KEY& k) throw()
                    {
                        //Better implement a search policy.
                        entry* pE = a_Entries;
                        while(pE != a_Entries + sz_EntryCount)
                        {
                            if(pE->_k == k)
                            {
                                break;
                            }
                            ++pE;
                        }

                        if(pE == a_Entries + sz_EntryCount)
                        {
                            return NULL;
                        }

                        return pE;
                    }
                };

                HASH_FUNCTION& _hf;
                KEY_COMP _kc;

                size_t sz_TableSize;
                double d_MultFactor;                                            //Recalculate this as 1/sz_TableSize everytime sz_TableSize changes.
                size_t sz_NextResizeLimit;
                size_t sz_EntryCount;
                double d_ExpectedLoadFactor;
                double d_CurrentLoadFactor;

                //If the load factor is relatively high (say >0.5 assuming sizeof(entry) == 2*sizeof(size_t)), it is more space efficient to keep a straight bucket array. But if the load factor is low, memory consumption would be lower if a pointer array of Entries is used here. But, because we would not be much concerned with a little additional memory being used when there are few entries, I think array of bucket objects is better. Further, it bypasses a pointer lookup. May have to reconsider is a situation where multiple hash tables are used (Perhaps as an array).
                bucket* a_Buckets;

                hash_container(const hash_container&);
                hash_container& operator=(const hash_container&);

                inline void calculateMultFactor() throw()
                {
                    d_MultFactor = 1.0f/static_cast<double>(sz_TableSize + 1);
                    //sz_NextResizeLimit = static_cast<size_t>(d_ExpectedLoadFactor*sz_TableSize);
                    //Have a look at this.
                    //TODO
                }

                void resize(size_t szNewSize) throw(std::bad_alloc)
                {
                    if(szNewSize == 0)
                    {
                        szNewSize = 1;
                    }
                    size_t szOldSize = sz_TableSize;
                    for(size_t szI = szNewSize; szI < szOldSize; ++szI)
                    {
                        a_Buckets[szI].~bucket();
                    }

                    a_Buckets = static_cast<bucket*>(realloc(a_Buckets, sizeof(bucket)*szNewSize));
                    if(a_Buckets == NULL)
                    {
                        throw std::bad_alloc();
                    }
                    //Unnecessary at the moment. But, just in case that bucket changes.
                    for(size_t szI = szOldSize; szI < szNewSize; ++szI)
                    {
                         new (&a_Buckets[szI]) bucket();
                    }

                    sz_TableSize = szNewSize;
                    calculateMultFactor();
                }

                inline bucket* get_bucket(const KEY& k) throw()
                {
                    return a_Buckets + _hf(k, sz_TableSize);
                }

                inline bool need_resizing() const throw()
                {

                }
            public:
                //typedef iterator void*;
                //typedef const_iterator void*;

                //iterator Insert(KEY& k, VALUE& v);
                //VALUE& Find(Key& k);
                //const VALUE& Find(Key& k);
                //iterator Find(KEY k);
                //const_iterator Find(KEY k);
                //void Delete(KEY& k);
                //void Delete(iterator it);
                //void Delete(const_iterator it);
                class iterator
                {
                    private:
                        entry* p_Entry;
                        bucket* p_Bucket;

                        friend class bucket;

                    public:
                        iterator(entry* pEntry)
                            :p_Entry(pEntry)
                        {
                        }

                        iterator()
                        {
                            p_Entry = NULL;
                        }

                        iterator(const iterator& it)
                        {
                            this->p_Entry = it.p_Entry;
                        }

                        inline VALUE& operator*() const
                        {
                            return p_Entry->_v;
                        }

                        inline bool operator==(const iterator& it) const
                        {
                            return this->p_Entry == it.p_Entry;
                        }

                        inline bool operator!=(const iterator& it) const
                        {
                            return !(*this == it);
                        }

                        inline iterator& operator=(const iterator& it)
                        {
                            this->p_Entry = it.p_Entry;
                        }

                        inline VALUE* operator->() const
                        {
                            return &p_Entry->_v;
                        }

                        inline iterator operator++()
                        {
                            return *this;
                        }

                        inline iterator& operator++(int)
                        {
                            //WRONG!!!
                            //TODO : Change this.
                            return *this;
                        }
                };

            private:
                iterator _EndIt;

            public:
                hash_container(HASH_FUNCTION& hf, size_t szTableSize = 1024, double dLoadFactor = 0.7f, KEY_COMP kc = KEY_COMP())throw(std::bad_alloc)
                    :_hf(hf), sz_TableSize(szTableSize), d_ExpectedLoadFactor(dLoadFactor), _kc(kc)
                {
                    if(d_ExpectedLoadFactor < 0.1f)
                    {
                        d_ExpectedLoadFactor = 0.1f;
                    }

                    a_Buckets = NULL;
                    sz_TableSize = 0;
                    if(szTableSize == 0)
                    {
                        szTableSize = 1;
                    }
                    resize(szTableSize);
                    d_CurrentLoadFactor = 0.0f;
                    sz_EntryCount = 0;

                    _EndIt = iterator(NULL);
                }

                virtual ~hash_container()
                {
                    for(size_t szI = 0; szI < sz_TableSize; ++szI)
                    {
                        a_Buckets[szI].~bucket();
                    }
                }

                inline iterator find(const KEY& k) throw()
                {
                    bucket* pBucket = get_bucket(k);
                    return pBucket->find(k);
                }

                inline bool insert(const KEY& k, const VALUE& v) throw(std::bad_alloc)
                {
                    bucket* pBucket = get_bucket(k);
                    bool bRet = false;
                    try
                    {
                        bRet = pBucket->insert(k, v);
                    }
                    catch(std::bad_alloc& e)
                    {
                        //What now?
                        throw e;
                    }
                    if(bRet == true)
                    {
                        ++sz_EntryCount;
                    }
                    return bRet;
                }

                inline VALUE& operator[](const KEY& k) throw(std::bad_alloc)
                {
                    bucket* pBucket = get_bucket(k);

                }

                inline bool erase(const KEY& k) throw(std::bad_alloc)
                {
                    bucket* pBucket =  get_bucket(k);
                    bool bRet = false;
                    try
                    {
                        bRet = pBucket->erase(k);
                    }
                    catch(std::bad_alloc& e)
                    {
                        throw e;
                    }
                    if(bRet == true)
                    {
                        --sz_EntryCount;
                    }
                    return bRet;
                }

                inline iterator end() const
                {
                    return _EndIt;
                }

                inline size_t size() const
                {
                    return sz_EntryCount;
                }

                inline size_t table_size() const
                {
                    return sz_TableSize;
                }

                inline double current_load_factor() const
                {
                    return d_MultFactor*static_cast<double>(sz_EntryCount);
                }

                inline double expected_load_factor() const
                {
                    return d_ExpectedLoadFactor;
                }
        };
}

#endif
</code>```

答:
For an iterator type, how is operator-> overloaded?

It's not. The operator-> can only be overloaded on class types.

If you mean "How do I overload it to return an integer type".

Then the answer is you can't. The result of operator-> is itself de-referenced and as such must be a pointer type (or an object(reference) that is a class type with overload operator->()).

What value should it return assuming that it is an iterator for a collection of class T objects?

It will return a pointer to T

```<code>struct Y { int a; };
std::vector<Y> plop(/* DATA TO INIT*/);

std::vector<Y>::iterator b = plop.begin();
b->a = 5; // here b.operator->() returns a pointer to Y object.
          // This is then used to access the element `a` of the Y object.
</code>```

Why does operator++() return by class T& while operator++(int) return by class T?

Technically they can return anything. But usually they are implemented as you suggested.

This is because of the standard implementation of these methods:

```<code>class X
{
     public:
         // Simple one first. The pre-increment just increments the objects state.
         // It returns a reference to itself to be used in the expression.
         X& operator++()
         {
              /* Increment this object */
              return *this;
         }

         // Post Increment: This has to increment the current object.
         // But the value returned must have the value of the original object.
         //
         // The easy way to do this is to make a copy (that you return). The copy
         // has the original value but now is distinct from this. You can now use
         // pre-increment to increment this object and return the copy. Because
         // the copy was created locally you can not return by reference.
         X operator++(int)
         {
             X  copy(*this);
             ++(*this);
             return copy;
         }
};
</code>```

I understand these two represent prefix increment and postfix increment. But why the difference in return value?

See comments in above code.

Title: Questions about operator overloading

Body:
I have two questions about operator overloading.

For an iterator type, how is operator-> overloaded? What value should it return assuming that it is an iterator for a collection of class T objects?

Why does operator++() return by class T& while operator++(int) return by class T? I understand these two represent prefix increment and postfix increment. But why the difference in return value?

EDIT: For Alf. Code is not complete though functioning. Any suggestions for improvement are welcome.

#ifndef DHASH_H
#define DHASH_H

//#include <vector>
#include <memory>
#include <exception>
#include <new>
#include <algorithm>
#include <functional>

namespace MCol
{
    template <typename KEY, typename VALUE, typename HASH_FUNCTION, typename KEY_COMP = std::equal_to<KEY> >
        class hash_container
        {
            private:
                struct entry
                {
                    KEY _k;
                    VALUE _v;

                    entry(const KEY& k, const VALUE& v)
                        :_k(k), _v(v)
                    {}

                    entry& operator=(const entry& e)
                    {
                        this->_k = e._k;
                        this->_v = e._v;
                    }
                };

            private:
                struct bucket
                {
                    entry* a_Entries;
                    size_t sz_EntryCount;

                    bucket()
                    {
                        sz_EntryCount = 0;
                        a_Entries = NULL;
                    }

                    ~bucket()
                    {
                        for(size_t szI = 0; szI < sz_EntryCount; ++szI)
                        {
                            a_Entries[szI].~entry();
                        }
                        free(a_Entries);
                    }

                    //Grow by 1. (Perhaps later try block increment. But wikipedia suggests that there is little difference between the two)
                    inline bool insert(const KEY& k, const VALUE& v) throw (std::bad_alloc)
                    {
                        if(find(k) != NULL)
                        {
                            return false;
                        }
                        a_Entries = static_cast<entry*>(realloc(a_Entries, sizeof(entry)*(++sz_EntryCount)));
                        if(a_Entries == NULL)
                        {
                            throw std::bad_alloc();
                        }

                        new (&a_Entries[sz_EntryCount - 1]) entry(k, v);
                        return true;
                    }

                    //Find entry, swap with last valid entry, remove if necessary.
                    inline bool erase(const KEY& k) throw(std::bad_alloc)
                    {
                        //Forwards or backwards? My guess is backwards is better.
                        entry* pE = a_Entries;
                        while(pE != a_Entries + sz_EntryCount)
                        {
                            if(pE->_k == k)
                            {
                                break;
                            }
                            ++pE;
                        }

                        if(pE == a_Entries + sz_EntryCount)
                        {
                            return false;
                        }

                        //We don't need to swap if the entry is the only one in the bucket or if it is the last one.
                        entry* pLast = a_Entries + sz_EntryCount - 1;
                        if((sz_EntryCount > 1) && (pE != pLast))
                        {
                            pE = pLast;
                        }

                        a_Entries = static_cast<entry*>(realloc(a_Entries, sizeof(entry)*(--sz_EntryCount)));
                        if(a_Entries == NULL && sz_EntryCount > 0)
                        {
                            throw std::bad_alloc();
                        }

                        return true;
                    }

                    inline entry* find(const KEY& k) throw()
                    {
                        //Better implement a search policy.
                        entry* pE = a_Entries;
                        while(pE != a_Entries + sz_EntryCount)
                        {
                            if(pE->_k == k)
                            {
                                break;
                            }
                            ++pE;
                        }

                        if(pE == a_Entries + sz_EntryCount)
                        {
                            return NULL;
                        }

                        return pE;
                    }
                };

                HASH_FUNCTION& _hf;
                KEY_COMP _kc;

                size_t sz_TableSize;
                double d_MultFactor;                                            //Recalculate this as 1/sz_TableSize everytime sz_TableSize changes.
                size_t sz_NextResizeLimit;
                size_t sz_EntryCount;
                double d_ExpectedLoadFactor;
                double d_CurrentLoadFactor;

                //If the load factor is relatively high (say >0.5 assuming sizeof(entry) == 2*sizeof(size_t)), it is more space efficient to keep a straight bucket array. But if the load factor is low, memory consumption would be lower if a pointer array of Entries is used here. But, because we would not be much concerned with a little additional memory being used when there are few entries, I think array of bucket objects is better. Further, it bypasses a pointer lookup. May have to reconsider is a situation where multiple hash tables are used (Perhaps as an array).
                bucket* a_Buckets;

                hash_container(const hash_container&);
                hash_container& operator=(const hash_container&);

                inline void calculateMultFactor() throw()
                {
                    d_MultFactor = 1.0f/static_cast<double>(sz_TableSize + 1);
                    //sz_NextResizeLimit = static_cast<size_t>(d_ExpectedLoadFactor*sz_TableSize);
                    //Have a look at this.
                    //TODO
                }

                void resize(size_t szNewSize) throw(std::bad_alloc)
                {
                    if(szNewSize == 0)
                    {
                        szNewSize = 1;
                    }
                    size_t szOldSize = sz_TableSize;
                    for(size_t szI = szNewSize; szI < szOldSize; ++szI)
                    {
                        a_Buckets[szI].~bucket();
                    }

                    a_Buckets = static_cast<bucket*>(realloc(a_Buckets, sizeof(bucket)*szNewSize));
                    if(a_Buckets == NULL)
                    {
                        throw std::bad_alloc();
                    }
                    //Unnecessary at the moment. But, just in case that bucket changes.
                    for(size_t szI = szOldSize; szI < szNewSize; ++szI)
                    {
                         new (&a_Buckets[szI]) bucket();
                    }

                    sz_TableSize = szNewSize;
                    calculateMultFactor();
                }

                inline bucket* get_bucket(const KEY& k) throw()
                {
                    return a_Buckets + _hf(k, sz_TableSize);
                }

                inline bool need_resizing() const throw()
                {

                }
            public:
                //typedef iterator void*;
                //typedef const_iterator void*;

                //iterator Insert(KEY& k, VALUE& v);
                //VALUE& Find(Key& k);
                //const VALUE& Find(Key& k);
                //iterator Find(KEY k);
                //const_iterator Find(KEY k);
                //void Delete(KEY& k);
                //void Delete(iterator it);
                //void Delete(const_iterator it);
                class iterator
                {
                    private:
                        entry* p_Entry;
                        bucket* p_Bucket;

                        friend class bucket;

                    public:
                        iterator(entry* pEntry)
                            :p_Entry(pEntry)
                        {
                        }

                        iterator()
                        {
                            p_Entry = NULL;
                        }

                        iterator(const iterator& it)
                        {
                            this->p_Entry = it.p_Entry;
                        }

                        inline VALUE& operator*() const
                        {
                            return p_Entry->_v;
                        }

                        inline bool operator==(const iterator& it) const
                        {
                            return this->p_Entry == it.p_Entry;
                        }

                        inline bool operator!=(const iterator& it) const
                        {
                            return !(*this == it);
                        }

                        inline iterator& operator=(const iterator& it)
                        {
                            this->p_Entry = it.p_Entry;
                        }

                        inline VALUE* operator->() const
                        {
                            return &p_Entry->_v;
                        }

                        inline iterator operator++()
                        {
                            return *this;
                        }

                        inline iterator& operator++(int)
                        {
                            //WRONG!!!
                            //TODO : Change this.
                            return *this;
                        }
                };

            private:
                iterator _EndIt;

            public:
                hash_container(HASH_FUNCTION& hf, size_t szTableSize = 1024, double dLoadFactor = 0.7f, KEY_COMP kc = KEY_COMP())throw(std::bad_alloc)
                    :_hf(hf), sz_TableSize(szTableSize), d_ExpectedLoadFactor(dLoadFactor), _kc(kc)
                {
                    if(d_ExpectedLoadFactor < 0.1f)
                    {
                        d_ExpectedLoadFactor = 0.1f;
                    }

                    a_Buckets = NULL;
                    sz_TableSize = 0;
                    if(szTableSize == 0)
                    {
                        szTableSize = 1;
                    }
                    resize(szTableSize);
                    d_CurrentLoadFactor = 0.0f;
                    sz_EntryCount = 0;

                    _EndIt = iterator(NULL);
                }

                virtual ~hash_container()
                {
                    for(size_t szI = 0; szI < sz_TableSize; ++szI)
                    {
                        a_Buckets[szI].~bucket();
                    }
                }

                inline iterator find(const KEY& k) throw()
                {
                    bucket* pBucket = get_bucket(k);
                    return pBucket->find(k);
                }

                inline bool insert(const KEY& k, const VALUE& v) throw(std::bad_alloc)
                {
                    bucket* pBucket = get_bucket(k);
                    bool bRet = false;
                    try
                    {
                        bRet = pBucket->insert(k, v);
                    }
                    catch(std::bad_alloc& e)
                    {
                        //What now?
                        throw e;
                    }
                    if(bRet == true)
                    {
                        ++sz_EntryCount;
                    }
                    return bRet;
                }

                inline VALUE& operator[](const KEY& k) throw(std::bad_alloc)
                {
                    bucket* pBucket = get_bucket(k);

                }

                inline bool erase(const KEY& k) throw(std::bad_alloc)
                {
                    bucket* pBucket =  get_bucket(k);
                    bool bRet = false;
                    try
                    {
                        bRet = pBucket->erase(k);
                    }
                    catch(std::bad_alloc& e)
                    {
                        throw e;
                    }
                    if(bRet == true)
                    {
                        --sz_EntryCount;
                    }
                    return bRet;
                }

                inline iterator end() const
                {
                    return _EndIt;
                }

                inline size_t size() const
                {
                    return sz_EntryCount;
                }

                inline size_t table_size() const
                {
                    return sz_TableSize;
                }

                inline double current_load_factor() const
                {
                    return d_MultFactor*static_cast<double>(sz_EntryCount);
                }

                inline double expected_load_factor() const
                {
                    return d_ExpectedLoadFactor;
                }
        };
}

#endif

Body:
For an iterator type, how is operator-> overloaded?

It's not. The operator-> can only be overloaded on class types.

If you mean "How do I overload it to return an integer type".

Then the answer is you can't. The result of operator-> is itself de-referenced and as such must be a pointer type (or an object(reference) that is a class type with overload operator->()).

What value should it return assuming that it is an iterator for a collection of class T objects?

It will return a pointer to T

struct Y { int a; };
std::vector<Y> plop(/* DATA TO INIT*/);

std::vector<Y>::iterator b = plop.begin();
b->a = 5; // here b.operator->() returns a pointer to Y object.
          // This is then used to access the element `a` of the Y object.

Why does operator++() return by class T& while operator++(int) return by class T?

Technically they can return anything. But usually they are implemented as you suggested.

This is because of the standard implementation of these methods:

class X
{
     public:
         // Simple one first. The pre-increment just increments the objects state.
         // It returns a reference to itself to be used in the expression.
         X& operator++()
         {
              /* Increment this object */
              return *this;
         }

         // Post Increment: This has to increment the current object.
         // But the value returned must have the value of the original object.
         //
         // The easy way to do this is to make a copy (that you return). The copy
         // has the original value but now is distinct from this. You can now use
         // pre-increment to increment this object and return the copy. Because
         // the copy was created locally you can not return by reference.
         X operator++(int)
         {
             X  copy(*this);
             ++(*this);
             return copy;
         }
};

I understand these two represent prefix increment and postfix increment. But why the difference in return value?

See comments in above code.


来源: stackexchange

问:
Dynamic height noScrolable UICollectionView in UICollectionViewCell
I want to add a dynamic height nonScrollable UICollectionView into UICollectionViewCell. (It is easy to add a static height UICollectionView in UICollectionViewCell as explained by Ash Furrow)

After spending hours on searching through the web I still don't get it.

This is what I want

Lets call:
Main CollectionView: ParentCollectionView

Inside CollectionView: ChildCollectionView

I want to get the height of ChildCollectionView so that i can set the cell size of the ParentCollectionView in side:

```<code>func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let text = "I'm trying to get a label in a cell.."
        let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
        let estimatedFrameForEventText = (text as NSString).boundingRect(with: CGSize.init(width: view.frame.width - 30, height: 1000), options: options, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 12)], context: nil)
        return CGSize.init(width: view.frame.width - 10, height: 320 + estimatedFrameForEventText.height + 60)
}
</code>```

Also want to change the height constant of the ChildCollectionView with this:

```<code>override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: eventCellId, for: indexPath) as! EventCell
        cell.eventText.text = "I'm trying to get a label in a cell.."

        // height constraint of ChildCollectionView in ParentCell
        cell.collectionViewHeightConstraint.constant = cell.collectionView.intrinsicContentSize.height
        return cell
}
</code>```

The scrolling of ChildCollectionView is purposely disabled to show the ChildCollectionViewCells all together.

This is where I am stuck

I am not abel to preCalculate the ChildCollectionView to pass them in the ParentCollectionView delegates

Both the CollectionView uses UICollectionViewFlowLayout

I am new to iOS developing.
Any help would be appreciated  :)

答:
Just for future searches on this subject. I'm using IGListKit with a cell that contains a UICollectionView that holds my tags. My problem was that IGListKit isn't built very well on the AutoLayout principles so to prevent the collectionview cells from overlapping each other I had to calculate the height for the section manually before it's shown.

My idea was to just add the width of each tag (+ padding + minimumInterimSpace) and determine when the next tag supersedes the collection view width.

```<code>func calculateDimensions() {
   //This is how IGListKit forwards the width, could be replaced with collectionView.containerSize.width
   let width = collectionContext!.containerSize.width

   var lineWidth:CGFloat = 0.0
   var lines = 0
   for tag in data.arrTags {
       //Calculate bounds by using boundingRect
       let size = TextSize.size(tag, font: Font.fontRegular(size: 13), height: 30)
       //16= 8 padding-left + 8 padding-right
       //5 = minimumInterimSpace
       let itemWidth = 16 + size.width + 5
       let tmpWidth = lineWidth + itemWidth
       if tmpWidth > width {
           lines += 1
           lineWidth = itemWidth
       }
       lineWidth += itemWidth
    }

    sectionHeight = CGFloat( lines * 30 + (lines * 5)) + 15
}
</code>```

This method is called when IGListKit sets the size for the current section. So I did this:

```<code>override func sizeForItem(at index: Int) -> CGSize {
    calculateDimensions()
    let size = CGSize(width: collectionContext!.containerSize.width, height: sectionHeight)
    return size
}
</code>```

This will result in the following:

ContentLicense: CC BY-SA 3.0

Body:
I want to add a dynamic height nonScrollable UICollectionView into UICollectionViewCell. (It is easy to add a static height UICollectionView in UICollectionViewCell as explained by Ash Furrow)

After spending hours on searching through the web I still don't get it.

This is what I want

Lets call:
Main CollectionView: ParentCollectionView

Inside CollectionView: ChildCollectionView

I want to get the height of ChildCollectionView so that i can set the cell size of the ParentCollectionView in side:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let text = "I'm trying to get a label in a cell.."
        let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
        let estimatedFrameForEventText = (text as NSString).boundingRect(with: CGSize.init(width: view.frame.width - 30, height: 1000), options: options, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 12)], context: nil)
        return CGSize.init(width: view.frame.width - 10, height: 320 + estimatedFrameForEventText.height + 60)
}

Also want to change the height constant of the ChildCollectionView with this:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: eventCellId, for: indexPath) as! EventCell
        cell.eventText.text = "I'm trying to get a label in a cell.."

        // height constraint of ChildCollectionView in ParentCell
        cell.collectionViewHeightConstraint.constant = cell.collectionView.intrinsicContentSize.height
        return cell
}

The scrolling of ChildCollectionView is purposely disabled to show the ChildCollectionViewCells all together.

This is where I am stuck

I am not abel to preCalculate the ChildCollectionView to pass them in the ParentCollectionView delegates

Both the CollectionView uses UICollectionViewFlowLayout

I am new to iOS developing.
Any help would be appreciated  :)

Body:
Just for future searches on this subject. I'm using IGListKit with a cell that contains a UICollectionView that holds my tags. My problem was that IGListKit isn't built very well on the AutoLayout principles so to prevent the collectionview cells from overlapping each other I had to calculate the height for the section manually before it's shown.

My idea was to just add the width of each tag (+ padding + minimumInterimSpace) and determine when the next tag supersedes the collection view width.

func calculateDimensions() {
   //This is how IGListKit forwards the width, could be replaced with collectionView.containerSize.width
   let width = collectionContext!.containerSize.width

   var lineWidth:CGFloat = 0.0
   var lines = 0
   for tag in data.arrTags {
       //Calculate bounds by using boundingRect
       let size = TextSize.size(tag, font: Font.fontRegular(size: 13), height: 30)
       //16= 8 padding-left + 8 padding-right
       //5 = minimumInterimSpace
       let itemWidth = 16 + size.width + 5
       let tmpWidth = lineWidth + itemWidth
       if tmpWidth > width {
           lines += 1
           lineWidth = itemWidth
       }
       lineWidth += itemWidth
    }

    sectionHeight = CGFloat( lines * 30 + (lines * 5)) + 15
}

This method is called when IGListKit sets the size for the current section. So I did this:

override func sizeForItem(at index: Int) -> CGSize {
    calculateDimensions()
    let size = CGSize(width: collectionContext!.containerSize.width, height: sectionHeight)
    return size
}

This will result in the following:


问:
Filter from a table Active Record
I have two tables: Restaurant and Meal

restaurant has_many meals and meal belongs_to restaurant.
Hence each meal has a restaurant_id column.

I have a @meals_search variable in my controller that is a list of meals from a search of a user in a search bar.

I want to display the restaurants corresponding to the @meals_search.restaurant_id but so far I can't find the right ActiveRecord query.

For example, if @meals_search.pluck(:restaurant_id) is equal to [1,7,44,53], then I want to create a @restaurants variable that stores restaurants with id 1,7, 44 and 53.

I populate the @meals_search variable like this:

meals_controller.rb

@meals_search = @meals.search(params[:search])

model.meal.rb

```<code>  belongs_to :restaurant

def self.search(search)
  if search
    where('name LIKE ?', "%#{search}%")
  else
    all
  end
end
</code>```

Any idea ?

答:
If I understand your problem correctly, you simply need to do this:

```<code>@restaurants = Restaurant.where(id: @meals_search.pluck(:restaurant_id))
</code>```

This uses ActiveRecord subset conditions.

The above query translates to something like:

```<code>SELECT * FROM Restaurant WHERE (restaurant.in IN (1,3,5))
</code>```

Title: Filter from a table Active Record

Body:
I have two tables: Restaurant and Meal

restaurant has_many meals and meal belongs_to restaurant.
Hence each meal has a restaurant_id column.

I have a @meals_search variable in my controller that is a list of meals from a search of a user in a search bar.

I want to display the restaurants corresponding to the @meals_search.restaurant_id but so far I can't find the right ActiveRecord query.

For example, if @meals_search.pluck(:restaurant_id) is equal to [1,7,44,53], then I want to create a @restaurants variable that stores restaurants with id 1,7, 44 and 53.

I populate the @meals_search variable like this:

meals_controller.rb

@meals_search = @meals.search(params[:search])

model.meal.rb

  belongs_to :restaurant

def self.search(search)
  if search
    where('name LIKE ?', "%#{search}%")
  else
    all
  end
end

Any idea ?

Body:
If I understand your problem correctly, you simply need to do this:

@restaurants = Restaurant.where(id: @meals_search.pluck(:restaurant_id))

This uses ActiveRecord subset conditions.

The above query translates to something like:

SELECT * FROM Restaurant WHERE (restaurant.in IN (1,3,5))


问:
Check if all children of div have class
I want to check if all children of different divs (with same id/class) have the class active. A typical if/else sentence but I can't quite wrap my head around it.

See the example here, this would be true as all children have the same class:

```<code><div class="parent">
   <div class="child active"></div>
   <div class="child active"></div>
   <div class="child active"></div>
   <div class="child active"></div>
</div>
</code>```

And this would be false as not all children have the same class:

```<code><div class="parent">
   <div class="child active"></div>
   <div class="child"></div>
   <div class="child active"></div>
   <div class="child"></div>
</div>
</code>```

There are many divs alike but the amount of children vary. It's important that it's 100% of the children that have the class before it is true.

How would you make the code?

Thanks.

答:
Doing it with a for loop and jquery =>

```<code> var childs = $('.parent').find('.child');

 for (var i=0;i<=childs.length;i++)
      if (!childs[i].hasClass('active'))
          return false
 return true
</code>```

Otherwise :

```<code>  return ($('.parent').find('.child').length === $('.parent').find('.child.active').length)
</code>```

Title: Check if all children of div have class

Body:
I want to check if all children of different divs (with same id/class) have the class active. A typical if/else sentence but I can't quite wrap my head around it.

See the example here, this would be true as all children have the same class:

And this would be false as not all children have the same class:

There are many divs alike but the amount of children vary. It's important that it's 100% of the children that have the class before it is true.

How would you make the code?

Thanks.

Body:
Doing it with a for loop and jquery =>

 var childs = $('.parent').find('.child');

 for (var i=0;i<=childs.length;i++)
      if (!childs[i].hasClass('active'))
          return false
 return true

Otherwise :

  return ($('.parent').find('.child').length === $('.parent').find('.child.active').length)


问:
Construct Mongo ObjectId from timestamp with unique increment
I want to generate mongo objectid for the documents to be inserted as new with the timestamp value overwritten.  so i used below code to get objectid.

```<code>var oIdWithTimestamp = function (timestamp) {
    // Convert string date to Date object (otherwise assume timestamp is a date)
    if (typeof (timestamp) == 'string') {
        timestamp = new Date(timestamp);
    }

    // Convert date object to hex seconds since Unix epoch
    var hexSeconds = Math.floor(timestamp / 1000).toString(16);

    // Create an ObjectId with that hex timestamp
    var constructedObjectId = mongoose.Types.ObjectId(hexSeconds + "0000000000000000");

    return constructedObjectId
};
</code>```

but if i want to insert 2 documents with same timestamp it doesn't fullfill the need. I noticed there is a get_inc function used to add incrementor value to objectids. And 16777214 different objectids can be generated using same timestamp.  Any help regarding how to use this incrementor to get unique timestamp upto 16777214 is appreciated.

答:
I have tried generating random mongo objectid using below snippet.

```<code>var bson = require('bson');

var generateObjIdFromTime = function(spefictime) {
    spefictime = ~~(spefictime/1000);
    return bson.ObjectID(spefictime);
}
</code>```

It generates random mongo objectids with given timestamp.

Body:
I want to generate mongo objectid for the documents to be inserted as new with the timestamp value overwritten.  so i used below code to get objectid.

var oIdWithTimestamp = function (timestamp) {
    // Convert string date to Date object (otherwise assume timestamp is a date)
    if (typeof (timestamp) == 'string') {
        timestamp = new Date(timestamp);
    }

    // Convert date object to hex seconds since Unix epoch
    var hexSeconds = Math.floor(timestamp / 1000).toString(16);

    // Create an ObjectId with that hex timestamp
    var constructedObjectId = mongoose.Types.ObjectId(hexSeconds + "0000000000000000");

    return constructedObjectId
};

but if i want to insert 2 documents with same timestamp it doesn't fullfill the need. I noticed there is a get_inc function used to add incrementor value to objectids. And 16777214 different objectids can be generated using same timestamp.  Any help regarding how to use this incrementor to get unique timestamp upto 16777214 is appreciated.

Body:
I have tried generating random mongo objectid using below snippet.

var bson = require('bson');

var generateObjIdFromTime = function(spefictime) {
    spefictime = ~~(spefictime/1000);
    return bson.ObjectID(spefictime);
}

It generates random mongo objectids with given timestamp.


问:
hide a column from table in MS SQL Server
Can anyone please share the steps to hide the particular column from the table in SQL Server 2012 as I don't want to delete that column

By hide I mean that whenever I use the select query against that particular table it should never show me that column.

Is it possible?
I need to make the column as hidden irrespective of any user login and whatever query i use

3rd party edit

Based on the comment But the problem is whenever i open the table in sql i dont want to see that particular column i assume that the question is:

How can i configure ssms so that opening a table definition inside sql management studio to only show the columns the connected user has select right to?

The screenshot below shows all columns of the table Employee despite the fact that the login StackoverIntern has no select rights to the columns SSN, Salary

答:
Late post but I think its worth to share

Earlier to SQLSERVER-2016 there was no any option to hide few columns from table when selecting *, however SQLSERVER-2016 come up with HIDDEN keyword by which you can now set columns hidden from Select * which you don't want to show and want only for some background process of your business logic.

The HIDDEN property is optional and will hide these columns
      from a standard SELECT statement for backward compatibility with our
      application and queries. You cannot apply the HIDDEN property to an existing column

.

you can alter existing table as well lets take an example of existing table

```<code>ALTER TABLE [dbo].[Account] ALTER COLUMN [StartDate] ADD HIDDEN;
ALTER TABLE [dbo].[Account] ALTER COLUMN [EndDate] ADD HIDDEN;
</code>```

You can check this concept used more often in Temporal table

you can find more on this in below Temporal Table

ContentLicense: CC BY-SA 4.0

Body:
Late post but I think its worth to share

Earlier to SQLSERVER-2016 there was no any option to hide few columns from table when selecting *, however SQLSERVER-2016 come up with HIDDEN keyword by which you can now set columns hidden from Select * which you don't want to show and want only for some background process of your business logic.

The HIDDEN property is optional and will hide these columns
      from a standard SELECT statement for backward compatibility with our
      application and queries. You cannot apply the HIDDEN property to an existing column

.

you can alter existing table as well lets take an example of existing table

ALTER TABLE [dbo].[Account] ALTER COLUMN [StartDate] ADD HIDDEN;
ALTER TABLE [dbo].[Account] ALTER COLUMN [EndDate] ADD HIDDEN;

You can check this concept used more often in Temporal table

you can find more on this in below Temporal Table


答:
If I understand your question correctly, you want something like this? </p>

```<code>@restaurants = Restaurant.where(id: @meals_search.pluck(:restaurant_id))
</code>```

Title: Filter from a table Active Record

Body:
If I understand your question correctly, you want something like this?

@restaurants = Restaurant.where(id: @meals_search.pluck(:restaurant_id))


问:
how pytorch nn.module save submodule
I have some question about how pytorch nn.module works

```<code>import torch
import torch.nn as nn

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.sub_module = nn.Linear(10, 5)
        self.value = 3

net = Net()
print(net.__dict__)
</code>```

output

```<code>{'_modules': OrderedDict([('sub_module', Linear (10 -> 5))]),  'value': 3, ...}
</code>```

I know that every attribute of a class should be stored in __dict__, why value(a int value) is in it, but sub_module(a nn.Module) is not, instead, sub_module is stored in _modules

I read the code of nn.Module implementation, but I didn't figure that out. do anyone have any ideas?

thank you !!

答:
I will try to keep it simple.

Every time you create a new item in the class Net for instance: self.sub_module = nn.Linear(10, 5) it calls the method __setattr__ of its parent class, in this case nn.Module. Then, inside __setattr__ method, the parameters are stored to the dict they belong. In this case since nn.Linear is a module, it is stored to the _modules dict.

Here is the piece of code that does this inside the Module class  https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/module.py#L389

Title: how pytorch nn.module save submodule

Body:
I have some question about how pytorch nn.module works

import torch
import torch.nn as nn

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.sub_module = nn.Linear(10, 5)
        self.value = 3

net = Net()
print(net.__dict__)

output

{'_modules': OrderedDict([('sub_module', Linear (10 -> 5))]),  'value': 3, ...}

I know that every attribute of a class should be stored in __dict__, why value(a int value) is in it, but sub_module(a nn.Module) is not, instead, sub_module is stored in _modules

I read the code of nn.Module implementation, but I didn't figure that out. do anyone have any ideas?

thank you !!


问:
Who can explain the name "pull request' in git?
Who can explain the name "pull request' in git?

Because it is a workflow method for submitting contributions.

My question is just about the name 'pull'.

I understand the 'request' part.

What or which pulling do they mean?

Why is push request, submit request not better?

Note that I belong to the class of non-native "english" speakers.

答:
Push and pull are relative terms (and they have specific meanings in git).

Let's suppose you have two repos A and B. Now, suppose you'd like to merge additional commits on repo A to repo B. There are two ways to do it. (1) You can push (the commits) from A to B (if you have proper permission on repo B). Or, (2) you can pull from B the commits on A.

In situations where "pull requests" often used, you have access to repo A but not to repo B. Hence you cannot use push. The only option is for you to "ask" somebody who has the write access to repo B (hence the term "request") to "pull" your commits on repo A.

Hence the term "pull request".


问:
Uncaught TypeError in Chrome and Not a Function in FireFox
I want to set the variable zoom as the map.GetZoom() but I have been getting the following error in both Chrome and Firefox:

Chrome

Uncaught TypeError: Object # has no method 'getZoom'

Firefox

gmap.getZoom is not a function

zoom = gmap.getZoom();

First question What error did I make in my codes?

default.js

```<code>window.gmap = {
 zoom_Changed: function() {

 zoom = gmap.getZoom();

 if(zoom > 15) {
  document.write("hello");
 } else {
 }
 }
};
</code>```

Edit: Gmap is defined in my views.py and the zoom_Changed function is for the event listener in my views.py.

views.py

```<code>maps.event.addListener(gmap, 'zoom_changed', 'gmap.zoom_Changed');
</code>```

答:
is it getZoom() or GetZoom()?  Casing is different in the question and the code example.

what @silverbtf is saying is partially right, i believe, (hard for me to test on the netbook i'm on). however by setting gmap again to an object literal (window.gmap = {...}), you're wiping out any existing gmap variable attached to the window object.

you could possibly rewrite your code like this:

```<code>gmap.zoom_Changed = function () {
    var zoom = this.getZoom(); // or .GetZoom()
    if (zoom > 15) {
        console.log('over 15');
    } else {
        console.log('under 15');
    }
}
</code>```

this way, you're attaching a new method to the already existing gmap instead of blowing it away.

Body:
I want to set the variable zoom as the map.GetZoom() but I have been getting the following error in both Chrome and Firefox:

Chrome

Uncaught TypeError: Object # has no method 'getZoom'

Firefox

gmap.getZoom is not a function

zoom = gmap.getZoom();

First question What error did I make in my codes?

default.js

window.gmap = {
 zoom_Changed: function() {

 zoom = gmap.getZoom();

 if(zoom > 15) {
  document.write("hello");
 } else {
 }
 }
};

Edit: Gmap is defined in my views.py and the zoom_Changed function is for the event listener in my views.py.

views.py

maps.event.addListener(gmap, 'zoom_changed', 'gmap.zoom_Changed');

Body:
is it getZoom() or GetZoom()?  Casing is different in the question and the code example.

what @silverbtf is saying is partially right, i believe, (hard for me to test on the netbook i'm on). however by setting gmap again to an object literal (window.gmap = {...}), you're wiping out any existing gmap variable attached to the window object.

you could possibly rewrite your code like this:

gmap.zoom_Changed = function () {
    var zoom = this.getZoom(); // or .GetZoom()
    if (zoom > 15) {
        console.log('over 15');
    } else {
        console.log('under 15');
    }
}

this way, you're attaching a new method to the already existing gmap instead of blowing it away.

ContentLicense: CC BY-SA 2.5


答:
```<code>if($(".parent .child").length === $(".parent .child.active").length){/*true*/}
</code>```

Title: Check if all children of div have class


问:
How to open a different activity on recyclerView item onclick
i am using a recyclerView to show my listitems in the navigation drawer.I have implemented the onclickListener but i have been stuck on how to open a different activity when items are clicked. All my items do on item click as of now as per the code is to display a toast with the item position.

I would appreciate the help.

AdapterClass.java

public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder> {
    private LayoutInflater inflater;
    private Context context;
List<Information>data= Collections.emptyList();
    public AdapterClass(Context context,List<Information>data){
        this.context=context;

        inflater= LayoutInflater.from(context);
        this.data=data;
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       View view= inflater.inflate(R.layout.custom_row,parent,false);
        MyViewHolder holder=new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Information current=data.get(position);
        holder.title.setText(current.title);
        holder.icon.setImageResource(current.iconId);

    }

    @Override
    public int getItemCount() {
        return data.size();
    }
    class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        TextView title;
        ImageView icon;

        public MyViewHolder(View itemView) {
            super(itemView);
            title=(TextView)itemView.findViewById(R.id.listText);
           icon=(ImageView)itemView.findViewById(R.id.listIcon);
            itemView.setClickable(true);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {

            Toast.makeText(context,"The Item Clicked is: "+getPosition(),Toast.LENGTH_SHORT).show();
        }
    };
}```
</div>
</div>
</p>

```Log  cat error after implementing Konrad's solution

    02-27 15:24:52.833: D/AndroidRuntime(1630): --------- beginning of crash
02-27 15:24:52.834: E/AndroidRuntime(1630): FATAL EXCEPTION: main
02-27 15:24:52.834: E/AndroidRuntime(1630): Process: com.snappy.stevekamau.snappy, PID: 1630
02-27 15:24:52.834: E/AndroidRuntime(1630): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.snappy.stevekamau.snappy/com.snappy.stevekamau.snappy.YourActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()' on a null object reference
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.access$800(ActivityThread.java:144)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.os.Handler.dispatchMessage(Handler.java:102)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.os.Looper.loop(Looper.java:135)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.main(ActivityThread.java:5221)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at java.lang.reflect.Method.invoke(Native Method)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at java.lang.reflect.Method.invoke(Method.java:372)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
02-27 15:24:52.834: E/AndroidRuntime(1630): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()' on a null object reference
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.internal.widget.ToolbarWidgetWrapper.<init>(ToolbarWidgetWrapper.java:95)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.internal.widget.ToolbarWidgetWrapper.<init>(ToolbarWidgetWrapper.java:88)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.internal.app.ToolbarActionBar.<init>(ToolbarActionBar.java:84)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.app.ActionBarActivityDelegateBase.setSupportActionBar(ActionBarActivityDelegateBase.java:175)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.app.ActionBarActivity.setSupportActionBar(ActionBarActivity.java:92)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at com.snappy.stevekamau.snappy.YourActivity.onCreate(YourActivity.java:18)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.Activity.performCreate(Activity.java:5933)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
02-27 15:24:52.834: E/AndroidRuntime(1630):     ... 10 more
02-27 15:24:52.839: W/ActivityManager(464):   Force finishing activity com.snappy.stevekamau.snappy/.YourActivity
02-27 15:24:52.841: W/ActivityManager(464):   Force finishing activity com.snappy.stevekamau.snappy/.MainActivity
```

答:
Simply you can do it easy... You just need to get the context of your activity, here, from your View.

```<code>//Create intent getting the context of your View and the class where you want to go
Intent intent = new Intent(view.getContext(), YourClass.class);

//start the activity from the view/context
view.getContext().startActivity(intent); //If you are inside activity, otherwise pass context to this funtion
</code>```

Remember that you need to modify AndroidManifest.xml and place the activity...

```<code><activity
        android:name=".YourClass"
        android:label="Label for your activity"></activity>
</code>```

Body:
i am using a recyclerView to show my listitems in the navigation drawer.I have implemented the onclickListener but i have been stuck on how to open a different activity when items are clicked. All my items do on item click as of now as per the code is to display a toast with the item position.

I would appreciate the help.

AdapterClass.java

public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder> {
    private LayoutInflater inflater;
    private Context context;
List<Information>data= Collections.emptyList();
    public AdapterClass(Context context,List<Information>data){
        this.context=context;

        inflater= LayoutInflater.from(context);
        this.data=data;
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       View view= inflater.inflate(R.layout.custom_row,parent,false);
        MyViewHolder holder=new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Information current=data.get(position);
        holder.title.setText(current.title);
        holder.icon.setImageResource(current.iconId);

    }

    @Override
    public int getItemCount() {
        return data.size();
    }
    class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        TextView title;
        ImageView icon;

        public MyViewHolder(View itemView) {
            super(itemView);
            title=(TextView)itemView.findViewById(R.id.listText);
           icon=(ImageView)itemView.findViewById(R.id.listIcon);
            itemView.setClickable(true);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {

            Toast.makeText(context,"The Item Clicked is: "+getPosition(),Toast.LENGTH_SHORT).show();
        }
    };
}

Log  cat error after implementing Konrad's solution

    02-27 15:24:52.833: D/AndroidRuntime(1630): --------- beginning of crash
02-27 15:24:52.834: E/AndroidRuntime(1630): FATAL EXCEPTION: main
02-27 15:24:52.834: E/AndroidRuntime(1630): Process: com.snappy.stevekamau.snappy, PID: 1630
02-27 15:24:52.834: E/AndroidRuntime(1630): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.snappy.stevekamau.snappy/com.snappy.stevekamau.snappy.YourActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()' on a null object reference
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.access$800(ActivityThread.java:144)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.os.Handler.dispatchMessage(Handler.java:102)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.os.Looper.loop(Looper.java:135)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.main(ActivityThread.java:5221)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at java.lang.reflect.Method.invoke(Native Method)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at java.lang.reflect.Method.invoke(Method.java:372)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
02-27 15:24:52.834: E/AndroidRuntime(1630): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()' on a null object reference
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.internal.widget.ToolbarWidgetWrapper.<init>(ToolbarWidgetWrapper.java:95)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.internal.widget.ToolbarWidgetWrapper.<init>(ToolbarWidgetWrapper.java:88)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.internal.app.ToolbarActionBar.<init>(ToolbarActionBar.java:84)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.app.ActionBarActivityDelegateBase.setSupportActionBar(ActionBarActivityDelegateBase.java:175)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.app.ActionBarActivity.setSupportActionBar(ActionBarActivity.java:92)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at com.snappy.stevekamau.snappy.YourActivity.onCreate(YourActivity.java:18)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.Activity.performCreate(Activity.java:5933)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
02-27 15:24:52.834: E/AndroidRuntime(1630):     ... 10 more
02-27 15:24:52.839: W/ActivityManager(464):   Force finishing activity com.snappy.stevekamau.snappy/.YourActivity
02-27 15:24:52.841: W/ActivityManager(464):   Force finishing activity com.snappy.stevekamau.snappy/.MainActivity

Body:
Simply you can do it easy... You just need to get the context of your activity, here, from your View.

//Create intent getting the context of your View and the class where you want to go
Intent intent = new Intent(view.getContext(), YourClass.class);

//start the activity from the view/context
view.getContext().startActivity(intent); //If you are inside activity, otherwise pass context to this funtion

Remember that you need to modify AndroidManifest.xml and place the activity...

<activity
        android:name=".YourClass"
        android:label="Label for your activity"></activity>


问:
MySQL - How to change value in column?
I have a OpenCart store with more than 23000 products and I need to change one option (Requeres Shipping) for all of my products. I need to change that option in my database. I have a table n0v_product with with column shipping with value 0. I need to change shipping value to 1 for all products. How to update the value in the column with phpMyAdmin?

答:
Run this in a test database before running it on production but this should do the job.</p>

```<code>UPDATE n0v_product
SET shipping = '1'
WHERE shipping = '0'
</code>```

Title: MySQL - How to change value in column?

Body:
Run this in a test database before running it on production but this should do the job.

UPDATE n0v_product
SET shipping = '1'
WHERE shipping = '0'


问:
Compiling C++ with Soundtouch
I am trying to write an application in C++ that uses soundtouch libraries. I am unable to figure out what library to use to link it with. Specifically, I am using SoundTouch.h.

I have this code compiled in C as well. The library I used then was lsoundtouch4c to link. I have not been able to find information on this any where else, so help is most welcome.

Thanks,

Sriram

答:
Code written in C++ that uses sound touch libraries can be linked using the following libraries:

```<code>/usr/local/lib
SoundTouch
</code>```

So, the linking in a makefile will look something like this:

```<code>main: <some-dependencies>
     g++ <your g++ options> <object files> -L/usr/local/lib -lSoundTouch
</code>```

Sriram.

Title: Compiling C++ with Soundtouch

Body:
Code written in C++ that uses sound touch libraries can be linked using the following libraries:

/usr/local/lib
SoundTouch

So, the linking in a makefile will look something like this:

main: <some-dependencies>
     g++ <your g++ options> <object files> -L/usr/local/lib -lSoundTouch

Sriram.


问:
jQuery Scroll After Focus
Can someone help me?

code before :

```<code>return $(window).scroll(function() {
  angular.element(":focus").blur();
  return angular.element("div.datepicker.datepicker-dropdown.dropdown-menu").hide();
});
</code>```

code I make :

```<code>$(startDateEl).on('click', function(){
  $("div.datepicker.datepicker-dropdown.dropdown-menu").focusin().on('scroll', function(){
    $("div.datepicker.datepicker-dropdown.dropdown-menu").hide();
  });
});
</code>```

The problem is when in phone scroll it hide keyboard because it using window.
this using directive angular and custom date. after to next page this windows scroll event function always active, and then I refactor the code what I want to question is how to make this run sequential after .focus() to datepicker and then the .scroll() function active to hide datepicker

or how to .scroll() without using target element window?

答:
the answer is

// for desktop

```<code>            $("div.datepicker.datepicker-dropdown.dropdown-menu").on('mouseleave', function(){
              $("div.datepicker.datepicker-dropdown.dropdown-menu").hide();
              $(startDateEl).blur();
            });
</code>```

// for mobile

```<code>    $("#main").bind('touchmove', function(){
      $("div.datepicker.datepicker-dropdown.dropdown-menu").hide();
      $(startDateEl).blur();
    });
</code>```

Title: jQuery Scroll After Focus

Body:
Can someone help me?

code before :

return $(window).scroll(function() {
  angular.element(":focus").blur();
  return angular.element("div.datepicker.datepicker-dropdown.dropdown-menu").hide();
});

code I make :

$(startDateEl).on('click', function(){
  $("div.datepicker.datepicker-dropdown.dropdown-menu").focusin().on('scroll', function(){
    $("div.datepicker.datepicker-dropdown.dropdown-menu").hide();
  });
});

The problem is when in phone scroll it hide keyboard because it using window.
this using directive angular and custom date. after to next page this windows scroll event function always active, and then I refactor the code what I want to question is how to make this run sequential after .focus() to datepicker and then the .scroll() function active to hide datepicker

or how to .scroll() without using target element window?

Body:
the answer is

// for desktop

            $("div.datepicker.datepicker-dropdown.dropdown-menu").on('mouseleave', function(){
              $("div.datepicker.datepicker-dropdown.dropdown-menu").hide();
              $(startDateEl).blur();
            });

// for mobile

    $("#main").bind('touchmove', function(){
      $("div.datepicker.datepicker-dropdown.dropdown-menu").hide();
      $(startDateEl).blur();
    });


问:
Android button background color
I am trying to set the background color of a button in my app and I am unable to achieve the result that I want...

The color that I am trying to set is holo_green_light(#ff99cc00). In order to do it, I am using setColorFilter(0xff99cc00, PorterDuff.Mode.MULTIPLY);

The color that I get is not the holo_green_light but a mix of lightgrey and holo_green_light.

I have tried using the LightingColorFilter without much success.

Is there a way to do it programatically, so that the button appears like a button and not a flat rectangle with the color that I need.

答:
If you want to keep the general styling (rounded corners etc.) and just change the background color then I use the backgroundTint property</p>

```<code>android:backgroundTint="@android:color/holo_green_light"
</code>```

Title: Android button background color

Body:
If you want to keep the general styling (rounded corners etc.) and just change the background color then I use the backgroundTint property

android:backgroundTint="@android:color/holo_green_light"


问:
SearchView: when click Done button nothing happens
Here snippet:

```<code> searchViewEditText.setImeOptions(EditorInfo.IME_ACTION_DONE);
        searchViewEditText.setSingleLine(true);
</code>```

As result when keyboard open, the button Done is show.
OK.

Here result:

But when I click on button Done nothing happen. I expect that keyboard will be hide.

答:
I think that you will have to close the Keyboard programatically. To do so, add the following logic to the TextView Listener:

```<code>editText = (EditText) findViewById(R.id.edit_text);

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            InputMethodManager inputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
               //Replace <<active view>> With the active view
                inputMethodManager.hideSoftInputFromWindow(<<active view>>.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
            return false;
        }
    });
</code>```

I hope this helps you :)

Body:
Here snippet:

 searchViewEditText.setImeOptions(EditorInfo.IME_ACTION_DONE);
        searchViewEditText.setSingleLine(true);

As result when keyboard open, the button Done is show.
OK.

Here result:

But when I click on button Done nothing happen. I expect that keyboard will be hide.

Body:
I think that you will have to close the Keyboard programatically. To do so, add the following logic to the TextView Listener:

editText = (EditText) findViewById(R.id.edit_text);

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            InputMethodManager inputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
               //Replace <<active view>> With the active view
                inputMethodManager.hideSoftInputFromWindow(<<active view>>.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
            return false;
        }
    });

I hope this helps you :)


答:
You can do this with the :not css property

var childs = $('.parent').find('div.child:not(.active)');
if (childs.length > 0) {
console.log('not all active')
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
   <div class="child active"></div>
   <div class="child active"></div>
   <div class="child active"></div>
   <div class="child active"></div>
</div></code>```

Title: Check if all children of div have class

Body:
I want to check if all children of different divs (with same id/class) have the class active. A typical if/else sentence but I can't quite wrap my head around it.

See the example here, this would be true as all children have the same class:

And this would be false as not all children have the same class:

There are many divs alike but the amount of children vary. It's important that it's 100% of the children that have the class before it is true.

How would you make the code?

Thanks.

Body:
You can do this with the :not css property

var childs = $('.parent').find('div.child:not(.active)');
if (childs.length > 0) {
console.log('not all active')
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
   <div class="child active"></div>
   <div class="child active"></div>
   <div class="child active"></div>
   <div class="child active"></div>
</div>


问:
Why "C:\Program Files" used as default. Is there any violations or degradation in performance if we change it?
Why does Microsoft recommend "C:\Program Files" for default installation destination? Are there any specific reason for that? And if I change the location is that going to effect the performance of the system and the application?</p>

答:
There is no particular reason you NEED to install in any particular folder (barring a few exceptions where you can't).

However, think hard about why you're asking this. If you want to hardcode your path, that is laziness and you can get burned on it. Make sure your program can handle being installed in the folder of your user's choice. What if you hardcode in C:\BuggyProgram\ and your user wants to install you in his J: drive? You're FUBAR'ed then.

In short, a well written program doesn't really CARE where it is installed. Take that approach.

OwnerDisplayName: Maharajan

LastEditorDisplayName: bdukes

OwnerDisplayName: bigwoody


问:
How to use MockRestServiceServer with multiple URLs?
I need to configure multiple expectations on an instance of MockRestServiceServer.  The expectations are for two different URLs:

Call URL #1

Call URL #1 (for a second time)

Call URL #2

The same URL is called twice, then a 3rd call is made to the same URL with different request params.

I have one instance of a load-balanced RestTemplate available to inject into my test, and I pass this to MockRestServiceServer.createServer().

I've tried to inline these 3 expectations to my MockRestServiceServer instance but the test fails claiming the 3rd URL was expected but it saw the 1st.  It seems like I'm either overwriting the expectations or there's something stateful being shared here that's keeping the mock server in the wrong state.

Can anyone show me an example of how to do this correctly?

答:
Your problem can be solved if you use not default expectation manager within the Mock Server org.springframework.test.web.client.MockRestServiceServer#MockRestServiceServer: it accepts a parameter of org.springframework.test.web.client.RequestExpectationManager.

You can pass this type: org.springframework.test.web.client.UnorderedRequestExpectationManager


问:
Combine consecutive date ranges
Using SQL Server 2008 R2,

I'm trying to combine date ranges into the maximum date range given that one end date is next to the following start date.

The data is about different employments. Some employees may have ended their employment and have rejoined at a later time. Those should count as two different employments (example ID 5). Some people have different types of employment, running after each other (enddate and startdate neck-to-neck), in this case it should be considered as one employment in total (example ID 30).

An employment period that has not ended has an enddate that is null.

Some examples is probably enlightening:

```<code>declare @t as table  (employmentid int, startdate datetime, enddate datetime)

insert into @t values
(5, '2007-12-03', '2011-08-26'),
(5, '2013-05-02', null),
(30, '2006-10-02', '2011-01-16'),
(30, '2011-01-17', '2012-08-12'),
(30, '2012-08-13', null),
(66, '2007-09-24', null)

-- expected outcome
EmploymentId StartDate   EndDate
5            2007-12-03  2011-08-26
5            2013-05-02  NULL
30           2006-10-02  NULL
66           2007-09-24  NULL
</code>```

I've been trying different "islands-and-gaps" techniques but haven't been able to crack this one.

答:
A modified script for combining all overlapping periods.
 For example

01.01.2001-01.01.2010

05.05.2005-05.05.2015

will give one period:

01.01.2001-05.05.2015

tbl.enddate must be completed

```<code>;WITH cte
  AS(
SELECT
  a.employmentid
  ,a.startdate
  ,a.enddate
from tbl a
left join tbl c on a.employmentid=c.employmentid
    and a.startdate > c.startdate
    and a.startdate <= dateadd(day, 1, c.enddate)
WHERE c.employmentid IS NULL

UNION all

SELECT
  a.employmentid
  ,a.startdate
  ,a.enddate
from cte a
inner join tbl c on a.startdate=c.startdate
    and (c.startdate = dateadd(day, 1, a.enddate) or (c.enddate > a.enddate and c.startdate <= a.enddate))
)
select distinct employmentid,
          startdate,
          nullif(max(enddate),'31.12.2099') enddate
from cte
group by employmentid, startdate
</code>```

Title: Combine consecutive date ranges

Body:
Using SQL Server 2008 R2,

I'm trying to combine date ranges into the maximum date range given that one end date is next to the following start date.

The data is about different employments. Some employees may have ended their employment and have rejoined at a later time. Those should count as two different employments (example ID 5). Some people have different types of employment, running after each other (enddate and startdate neck-to-neck), in this case it should be considered as one employment in total (example ID 30).

An employment period that has not ended has an enddate that is null.

Some examples is probably enlightening:

declare @t as table  (employmentid int, startdate datetime, enddate datetime)

insert into @t values
(5, '2007-12-03', '2011-08-26'),
(5, '2013-05-02', null),
(30, '2006-10-02', '2011-01-16'),
(30, '2011-01-17', '2012-08-12'),
(30, '2012-08-13', null),
(66, '2007-09-24', null)

-- expected outcome
EmploymentId StartDate   EndDate
5            2007-12-03  2011-08-26
5            2013-05-02  NULL
30           2006-10-02  NULL
66           2007-09-24  NULL

I've been trying different "islands-and-gaps" techniques but haven't been able to crack this one.

Body:
A modified script for combining all overlapping periods.
 For example

01.01.2001-01.01.2010

05.05.2005-05.05.2015

will give one period:

01.01.2001-05.05.2015

tbl.enddate must be completed

;WITH cte
  AS(
SELECT
  a.employmentid
  ,a.startdate
  ,a.enddate
from tbl a
left join tbl c on a.employmentid=c.employmentid
    and a.startdate > c.startdate
    and a.startdate <= dateadd(day, 1, c.enddate)
WHERE c.employmentid IS NULL

UNION all

SELECT
  a.employmentid
  ,a.startdate
  ,a.enddate
from cte a
inner join tbl c on a.startdate=c.startdate
    and (c.startdate = dateadd(day, 1, a.enddate) or (c.enddate > a.enddate and c.startdate <= a.enddate))
)
select distinct employmentid,
          startdate,
          nullif(max(enddate),'31.12.2099') enddate
from cte
group by employmentid, startdate


问:
Restcord channel->getChannelMessages() gives the wrong return
I'm trying to load all messages that have been posted after a specific message ID, but no matter what I input, it returns all messages with the limit provided.

Sample message id: 380407098300956691

My Code;

```<code>$pull->channel->getChannelMessages(['channel.id' => 000000000000000000,'before'=> 0,'after'=> 380407098300956691,'around'=> 0,'limit'=> 20])
</code>```

(taken from example page: http://www.restcord.com/Channel/Get%20Channel%20Messages/)

Am I missing something here? (the 000000000000000000 is fake of course)

答:
Seemed to be an issue in the release of Restcord,
Switching to the dev branch solved my issue.</p>

Body:
I'm trying to load all messages that have been posted after a specific message ID, but no matter what I input, it returns all messages with the limit provided.

Sample message id: 380407098300956691

My Code;

$pull->channel->getChannelMessages(['channel.id' => 000000000000000000,'before'=> 0,'after'=> 380407098300956691,'around'=> 0,'limit'=> 20])

(taken from example page: http://www.restcord.com/Channel/Get%20Channel%20Messages/)

Am I missing something here? (the 000000000000000000 is fake of course)


问:
How to Output a Double Value with all the Decimal Places in Debugger or Console
I wish to extract double value completely when I am debugging an application, so that I can use it to construct a test case to feed into my geometry algorithm.

How to extract the double value out-- down to very last decimal places allowed by the double datatypes in C#-- and output it in either debugger windows, or using Console.WriteLine command?

Edit: My problem is that the algorithm that takes the double value as input will only fail if I insist of input the whole double value, right down to the very last digit. And since I want to reproduce it in a test case, that's why I would need such a full representation of the double value.

答:
I have a DoubleConverter class which does exactly what you want, by the sounds of it. Use it like this:

```<code>string text = DoubleConverter.ToExactString(doubleValue);
</code>```

You need to make sure you understand that just because the output has a large number of digits, that doesn't mean it has that much precision. You may want to read my article on binary floating point in .NET for more information - or you may be aware of all of this to start with, of course.

Note that if you only want a string value which can be round-tripped, you don't need any extra code - just use the "r" format specifier:

```<code>string text = doubleValue.ToString("r");
</code>```

I agree with Jackson Pope's general approach of using tolerance in equality comparisons for tests, but I do find it useful sometimes to see the exact value represented by a double. It can make it easier to understand why a particular calculation has come out one way or another.

Body:
I have a DoubleConverter class which does exactly what you want, by the sounds of it. Use it like this:

string text = DoubleConverter.ToExactString(doubleValue);

You need to make sure you understand that just because the output has a large number of digits, that doesn't mean it has that much precision. You may want to read my article on binary floating point in .NET for more information - or you may be aware of all of this to start with, of course.

Note that if you only want a string value which can be round-tripped, you don't need any extra code - just use the "r" format specifier:

string text = doubleValue.ToString("r");

I agree with Jackson Pope's general approach of using tolerance in equality comparisons for tests, but I do find it useful sometimes to see the exact value represented by a double. It can make it easier to understand why a particular calculation has come out one way or another.


问:
How to iterate a child object angular 4?
Already have a service that passes objects to the DOM.

```<code>@Injectable()
export class DbService {
    db:Database[] = [
        {
        "id":0,
        "img":"../../../assets/img/logo/gro.png",
        "name":"Company,
        "type":"company type",
        "hours": "9:00AM-9:00PM",
        "number": 9999999,
        "email": 'info@company.com',
        "items": [
                    {'Beverage':['Bigga', 'Soda', 'Wata', 'Sprite']},
                    {'Canned':['Mackerel', 'Corn Beef', 'Tuna']}

                ]
        }...
</code>```

Made it iterate here...

```<code>        <div class="storeDoor col-md-4 " *ngFor="let butt of db" [routerLink]="['/store', butt.name]">
            <div class="row">
                <div class="col-md-5">
                    <img src="{{butt.img}}" width="70%">
                </div>
                <div class="col-md-7">
                   <h3 class=" ">
                      {{butt.name}}
                   </h3>
                   <h6>
                      {{butt.type}}
                   </h6>
               </div>
            </div>
        </div>
</code>```

And this opened the store front dynamically ...

```<code>                <div class="">
                        <h2 id="name" class="">{{store[0].name}}</h2>
                        <p style="color:grey; font-size: 16px"> Open Hours: {{store[0].hours}}</p>
                        <hr>

                </div>
                <div class="info">
                    <h5 class="badge badge-info">10/10</h5>
                    <h5>999 rating</h5>
                    <h5><i class="fa fa-phone fa-lg"></i> {{store[0].number}}</h5>
                    <h5>{{store[0].email}}</h5>

                    <button class="btn">Create Group Order</button>
                </div>
</code>```

But now while the store is open, I am lost in how to iterate the items object, displaying only the  key of the child object (Beverage, Canned)...

```<code>    <div class="aisle" >
        <a class="w3-bar-item" href="#" ></a>

    </div>
</code>```

答:
Try the below code which will print beverages and cannes seperately.

```<code><div *ngFor="let butt of db" >
    <div *ngFor="let items of butt.items">
      <div *ngFor="let beverages of items.Beverage">
        {{beverages}}
      </div>
      <div *ngFor="let canned of items.Canned">
        {{canned}}
      </div>
    </div>
  </div>
</code>```

In component file get the data from service layer

```<code>    import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {appService} from '../../providers/app.service';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  db : any;

  constructor(public navCtrl: NavController, public appService : appService, public getMonthsService : GetMonthsService) {
    this.db=appService.db;
  }

}
</code>```

In service file place your sample input

```<code>import { Injectable }     from '@angular/core';

@Injectable()
export class appService{
  service : any="summa";
  db:any[] = [
        {
        "id":0,
        "img":"../../../assets/img/logo/gro.png",
        "name":"Company",
        "type":"company type",
        "hours": "9:00AM-9:00PM",
        "number": 9999999,
        "email": 'info@company.com',
        "items": [
                    {'Beverage':['Bigga', 'Soda', 'Wata', 'Sprite']},
                    {'Canned':['Mackerel', 'Corn Beef', 'Tuna']}

                ]
        }
  ];
}
</code>```

Body:
Already have a service that passes objects to the DOM.

@Injectable()
export class DbService {
    db:Database[] = [
        {
        "id":0,
        "img":"../../../assets/img/logo/gro.png",
        "name":"Company,
        "type":"company type",
        "hours": "9:00AM-9:00PM",
        "number": 9999999,
        "email": 'info@company.com',
        "items": [
                    {'Beverage':['Bigga', 'Soda', 'Wata', 'Sprite']},
                    {'Canned':['Mackerel', 'Corn Beef', 'Tuna']}

                ]
        }...

Made it iterate here...

                      {{butt.name}}

                      {{butt.type}}

And this opened the store front dynamically ...

{{store[0].name}}

 Open Hours: {{store[0].hours}}

10/10

999 rating

 {{store[0].number}}

{{store[0].email}}

                    <button class="btn">Create Group Order</button>

But now while the store is open, I am lost in how to iterate the items object, displaying only the  key of the child object (Beverage, Canned)...

Body:
Try the below code which will print beverages and cannes seperately.

<div *ngFor="let butt of db" >
    <div *ngFor="let items of butt.items">
      <div *ngFor="let beverages of items.Beverage">
        {{beverages}}
      </div>
      <div *ngFor="let canned of items.Canned">
        {{canned}}
      </div>
    </div>
  </div>

In component file get the data from service layer

    import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {appService} from '../../providers/app.service';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  db : any;

  constructor(public navCtrl: NavController, public appService : appService, public getMonthsService : GetMonthsService) {
    this.db=appService.db;
  }

}

In service file place your sample input

import { Injectable }     from '@angular/core';

@Injectable()
export class appService{
  service : any="summa";
  db:any[] = [
        {
        "id":0,
        "img":"../../../assets/img/logo/gro.png",
        "name":"Company",
        "type":"company type",
        "hours": "9:00AM-9:00PM",
        "number": 9999999,
        "email": 'info@company.com',
        "items": [
                    {'Beverage':['Bigga', 'Soda', 'Wata', 'Sprite']},
                    {'Canned':['Mackerel', 'Corn Beef', 'Tuna']}

                ]
        }
  ];
}


问:
Check if all children of div have class
I want to check if all children of different divs (with same id/class) have the class active. A typical if/else sentence but I can't quite wrap my head around it.

See the example here, this would be true as all children have the same class:

```<code><div class="parent">
   <div class="child active"></div>
   <div class="child active"></div>
   <div class="child active"></div>
   <div class="child active"></div>
</div>
</code>```

And this would be false as not all children have the same class:

```<code><div class="parent">
   <div class="child active"></div>
   <div class="child"></div>
   <div class="child active"></div>
   <div class="child"></div>
</div>
</code>```

There are many divs alike but the amount of children vary. It's important that it's 100% of the children that have the class before it is true.

How would you make the code?

Thanks.

答:
There are multiple ways to do it!
Simplest one being:

if($('.parent .child.active').length === $('.parent .child').length){
 //return true
  console.log('true');
}
else{
 //return false
  console.log('false');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
   <div class="child active"></div>
   <div class="child"></div>
   <div class="child active"></div>
   <div class="child"></div>
</div></code>```

Title: Check if all children of div have class

Body:
There are multiple ways to do it!
Simplest one being:

if($('.parent .child.active').length === $('.parent .child').length){
 //return true
  console.log('true');
}
else{
 //return false
  console.log('false');
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
   <div class="child active"></div>
   <div class="child"></div>
   <div class="child active"></div>
   <div class="child"></div>
</div>