问:
c++ boost interprocess exchange (copy) non-shared and shared string vector
I want to achieve what was achieved in the answer to this question, but for a vector of strings i.e. string objects. I want to be able to write common code that can be used with either heap memory or shared memory. I have emulated the code and wrote a class to implement a vector of strings that would work for with both heap memory or shared memory. I got it working for the most part. However, when I try to initialize/create a shared memory vector of strings from a heap allocated vector of strings I am getting compile errors. In the question referenced above, shared memory vector was initialized from non-shared memory vector (to quote "this works because of ... MAGIC!"). Not sure if its because that question was dealing with a vector of ints which are easily copyable and movable. I have provided the copy constructor for the shared memory string class but it still doesn't work. I've provided my code below (commented out the code that's giving me compilation errors). Any help is appreciated. Thanks.

```<code>#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/container/scoped_allocator.hpp>
#include <iostream>
#include <string>
#include <sstream>

namespace bip = boost::interprocess;

namespace generic
{

template <typename T, typename Alloc/* = std::allocator<T>*/ >
using vector = bip::vector<T, typename Alloc::template rebind<T>::other >;

template <typename Alloc/* = std::allocator<T>*/ >
using GenericString = bip::basic_string<char, std::char_traits<char>
                           , typename Alloc::template rebind<char>::other>;

template <typename Alloc>
class String
{
public:
  typedef Alloc allocator_type; // ties in with uses_allocator/scoped_allocator

  String(Alloc alloc = Alloc())
  : mString(alloc)
  {
  }

  String(const std::string str, Alloc alloc = Alloc())
  : mString(str.c_str(), alloc)
  {
  }

  String(const char* str, Alloc alloc = Alloc())
  : mString(str, alloc)
  {
  }

  template <typename OtherAlloc>
  String(String<OtherAlloc> const& other, Alloc alloc = Alloc())
  : mString(other.mString.begin(), other.mString.end(), alloc)
  {
  }

  std::string ToString() { return std::string(mString.begin(), mString.end()); }

  friend std::ostream& operator<<(std::ostream& os, const String& str)
  {
    os << str.mString;
    return os;
  }

private:
  template<typename OtherAlloc> friend struct String;
  GenericString<Alloc> mString;
};

template <typename Alloc>
class StringVector
{
public:
  typedef Alloc allocator_type; // ties in with uses_allocator/scoped_allocator
  typedef vector<String<Alloc>, Alloc> GenericStringVector;
  using Iterator = typename GenericStringVector::iterator;
  using ConstIterator = typename GenericStringVector::const_iterator;

  StringVector(Alloc alloc = Alloc())
  : mStrings(alloc)
  {
  }

  template <typename OtherAlloc>
  StringVector(StringVector<OtherAlloc> const& other, Alloc alloc = Alloc())
  : mStrings(other.mStrings.begin(), other.mStrings.end(), alloc)
  {
  }

  void Add(const String<Alloc> str) { mStrings.emplace_back(str); }

  void Remove(Iterator iter) { mStrings.erase(iter); }

  void Clear() { mStrings.clear(); }

  void Print() const
  {
    std::cout << "[";
    for (ConstIterator it = mStrings.begin(); it != mStrings.end(); it++)
      std::cout << (it == mStrings.begin() ? "" : ", ") << *it;
    std::cout << "]\n";
  }

private:
  template<typename OtherAlloc> friend struct StringVector;
  GenericStringVector mStrings;
};

}

namespace heap
{
  using VAlloc = std::allocator<void>;
  using String = generic::String<VAlloc>;
  using StringVector = generic::StringVector<VAlloc>;
}

namespace shared
{
  using VAlloc =boost::container::scoped_allocator_adaptor<
          bip::allocator<void, bip::managed_shared_memory::segment_manager> >;

  using String = generic::String<VAlloc>;
  using StringVector = generic::StringVector<VAlloc>;
}

int main(void)
{
  struct shm_remove {
      shm_remove()  { bip::shared_memory_object::remove("MySharedMemory"); }
      ~shm_remove() { bip::shared_memory_object::remove("MySharedMemory"); }
  } remover;

  std::cout << "Heap based storage: \n";
  heap::StringVector svec;

  svec.Add(heap::String("test1"));
  svec.Add(heap::String("test2"));
  svec.Add(heap::String("test3"));
  svec.Add(heap::String("test4"));
  svec.Print();

  std::cout << "Shared memory storage: \n";
  bip::managed_shared_memory seg(bip::create_only, "MySharedMemory", 65536);
  shared::VAlloc shalloc(seg.get_segment_manager());

  shared::StringVector sh_svec(shalloc);
  sh_svec.Add(shared::String("test1", shalloc));
  sh_svec.Add(shared::String("test2", shalloc));
  sh_svec.Add(shared::String("test3", shalloc));
  sh_svec.Add(shared::String("test4", shalloc));
  sh_svec.Print();

  shared::StringVector sh_svec2(sh_svec, shalloc);
  sh_svec2.Print();

  //shared::StringVector sh_svec3(svec, shalloc);   // gives compile error :(
  //sh_svec3.Print();
}
</code>```

Including compilation errors:

```<code>In file included from src/test_string_vector.cc:5:0:
/usr/include/boost/container/scoped_allocator.hpp: In instantiation of ‘boost::container::container_detail::scoped_allocator_adaptor_base<OuterAlloc>::scoped_allocator_adaptor_base() [with OuterAlloc = boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> >]’:
/usr/include/boost/container/scoped_allocator.hpp:963:7:   required from ‘boost::container::scoped_allocator_adaptor<OuterAlloc, InnerAllocs>::scoped_allocator_adaptor() [with OuterAlloc = boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> >; InnerAllocs = {}]’
/usr/include/boost/container/vector.hpp:1174:15:   required from ‘void boost::container::vector<T, Allocator>::assign(FwdIt, FwdIt, typename boost::container::container_detail::enable_if_c<((! boost::container::container_detail::is_convertible<InIt, typename boost::container::allocator_traits<Allocator>::size_type>::value) && ((! boost::container::container_detail::is_input_iterator<InIt>::value) && (! boost::move_detail::is_same<typename boost::container::container_detail::version<Allocator>::type, boost::container::container_detail::integral_constant<unsigned int, 0u> >::value)))>::type*) [with FwdIt = boost::container::container_detail::vec_iterator<generic::String<std::allocator<void> >*, true>; T = generic::String<boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > > >; Allocator = boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<generic::String<boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > > >, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > >; typename boost::container::container_detail::enable_if_c<((! boost::container::container_detail::is_convertible<InIt, typename boost::container::allocator_traits<Allocator>::size_type>::value) && ((! boost::container::container_detail::is_input_iterator<InIt>::value) && (! boost::move_detail::is_same<typename boost::container::container_detail::version<Allocator>::type, boost::container::container_detail::integral_constant<unsigned int, 0u> >::value)))>::type = void]’
/usr/include/boost/container/vector.hpp:864:7:   required from ‘boost::container::vector<T, Allocator>::vector(InIt, InIt, const allocator_type&) [with InIt = boost::container::container_detail::vec_iterator<generic::String<std::allocator<void> >*, true>; T = generic::String<boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > > >; Allocator = boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<generic::String<boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > > >, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > >; boost::container::vector<T, Allocator>::allocator_type = boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<generic::String<boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > > >, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > >]’
src/test_string_vector.cc:78:65:   required from ‘generic::StringVector<Alloc>::StringVector(const generic::StringVector<OtherAlloc>&, Alloc) [with OtherAlloc = std::allocator<void>; Alloc = boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > >]’
src/test_string_vector.cc:151:46:   required from here
/usr/include/boost/container/scoped_allocator.hpp:762:7: error: no matching function for call to ‘boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> >::allocator()’
       {}
       ^
In file included from /usr/include/boost/interprocess/segment_manager.hpp:38:0,
                 from /usr/include/boost/interprocess/detail/managed_memory_impl.hpp:30,
                 from /usr/include/boost/interprocess/managed_shared_memory.hpp:25,
                 from src/test_string_vector.cc:1:
/usr/include/boost/interprocess/allocators/allocator.hpp:142:4: note: candidate: template<class T2> boost::interprocess::allocator<T, SegmentManager>::allocator(const boost::interprocess::allocator<T2, SegmentManager>&)
    allocator(const allocator<T2, SegmentManager> &other)
    ^
/usr/include/boost/interprocess/allocators/allocator.hpp:142:4: note:   template argument deduction/substitution failed:
In file included from src/test_string_vector.cc:5:0:
/usr/include/boost/container/scoped_allocator.hpp:762:7: note:   candidate expects 1 argument, 0 provided
       {}
       ^
In file included from /usr/include/boost/interprocess/segment_manager.hpp:38:0,
                 from /usr/include/boost/interprocess/detail/managed_memory_impl.hpp:30,
                 from /usr/include/boost/interprocess/managed_shared_memory.hpp:25,
                 from src/test_string_vector.cc:1:
/usr/include/boost/interprocess/allocators/allocator.hpp:136:4: note: candidate: boost::interprocess::allocator<T, SegmentManager>::allocator(const boost::interprocess::allocator<T, SegmentManager>&) [with T = void; SegmentManager = boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index>]
    allocator(const allocator &other)
    ^
/usr/include/boost/interprocess/allocators/allocator.hpp:136:4: note:   candidate expects 1 argument, 0 provided
/usr/include/boost/interprocess/allocators/allocator.hpp:131:4: note: candidate: boost::interprocess::allocator<T, SegmentManager>::allocator(boost::interprocess::allocator<T, SegmentManager>::segment_manager*) [with T = void; SegmentManager = boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index>; boost::interprocess::allocator<T, SegmentManager>::segment_manager = boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index>]
    allocator(segment_manager *segment_mngr)
    ^
/usr/include/boost/interprocess/allocators/allocator.hpp:131:4: note:   candidate expects 1 argument, 0 provided
Makefile:16: recipe for target 'obj/test_string_vector.o' failed
make: *** [obj/test_string_vector.o] Error 1
</code>```

答:
You did not provide your compilation errors, however just by briefly looking at the code and some working knowlege of boost::interprocess , I think your problem lies in std::allocator used for boost::interprocess , but I am not 100% sure, so please provide compilation errors.
In the meantime if you like

you can look at our open-source stack solution for Shared, Mmap, Heap
memory_types.hpp
I think you can  use boost::interprocess::allocator with boost::interprocess::managed_heap_memory::segment_manager or something like that.
Please also specify if you use C++03 or C++11 compiler as I think in C++03 it was
typedef T* pointer_type and that will not work with boost shared memory as it needs offset_ptr , basically offset from the beginning  of memory segment and not an absolute address.

I modified your code you had used shared::StringVector to store SHM structure
So now it compiles:

```<code>heap::StringVector sh_svec3(svec);   // does not gives compile error :-)
sh_svec3.Print();
</code>```

Body:
I want to achieve what was achieved in the answer to this question, but for a vector of strings i.e. string objects. I want to be able to write common code that can be used with either heap memory or shared memory. I have emulated the code and wrote a class to implement a vector of strings that would work for with both heap memory or shared memory. I got it working for the most part. However, when I try to initialize/create a shared memory vector of strings from a heap allocated vector of strings I am getting compile errors. In the question referenced above, shared memory vector was initialized from non-shared memory vector (to quote "this works because of ... MAGIC!"). Not sure if its because that question was dealing with a vector of ints which are easily copyable and movable. I have provided the copy constructor for the shared memory string class but it still doesn't work. I've provided my code below (commented out the code that's giving me compilation errors). Any help is appreciated. Thanks.

#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/container/scoped_allocator.hpp>
#include <iostream>
#include <string>
#include <sstream>

namespace bip = boost::interprocess;

namespace generic
{

template <typename T, typename Alloc/* = std::allocator<T>*/ >
using vector = bip::vector<T, typename Alloc::template rebind<T>::other >;

template <typename Alloc/* = std::allocator<T>*/ >
using GenericString = bip::basic_string<char, std::char_traits<char>
                           , typename Alloc::template rebind<char>::other>;

template <typename Alloc>
class String
{
public:
  typedef Alloc allocator_type; // ties in with uses_allocator/scoped_allocator

  String(Alloc alloc = Alloc())
  : mString(alloc)
  {
  }

  String(const std::string str, Alloc alloc = Alloc())
  : mString(str.c_str(), alloc)
  {
  }

  String(const char* str, Alloc alloc = Alloc())
  : mString(str, alloc)
  {
  }

  template <typename OtherAlloc>
  String(String<OtherAlloc> const& other, Alloc alloc = Alloc())
  : mString(other.mString.begin(), other.mString.end(), alloc)
  {
  }

  std::string ToString() { return std::string(mString.begin(), mString.end()); }

  friend std::ostream& operator<<(std::ostream& os, const String& str)
  {
    os << str.mString;
    return os;
  }

private:
  template<typename OtherAlloc> friend struct String;
  GenericString<Alloc> mString;
};

template <typename Alloc>
class StringVector
{
public:
  typedef Alloc allocator_type; // ties in with uses_allocator/scoped_allocator
  typedef vector<String<Alloc>, Alloc> GenericStringVector;
  using Iterator = typename GenericStringVector::iterator;
  using ConstIterator = typename GenericStringVector::const_iterator;

  StringVector(Alloc alloc = Alloc())
  : mStrings(alloc)
  {
  }

  template <typename OtherAlloc>
  StringVector(StringVector<OtherAlloc> const& other, Alloc alloc = Alloc())
  : mStrings(other.mStrings.begin(), other.mStrings.end(), alloc)
  {
  }

  void Add(const String<Alloc> str) { mStrings.emplace_back(str); }

  void Remove(Iterator iter) { mStrings.erase(iter); }

  void Clear() { mStrings.clear(); }

  void Print() const
  {
    std::cout << "[";
    for (ConstIterator it = mStrings.begin(); it != mStrings.end(); it++)
      std::cout << (it == mStrings.begin() ? "" : ", ") << *it;
    std::cout << "]\n";
  }

private:
  template<typename OtherAlloc> friend struct StringVector;
  GenericStringVector mStrings;
};

}

namespace heap
{
  using VAlloc = std::allocator<void>;
  using String = generic::String<VAlloc>;
  using StringVector = generic::StringVector<VAlloc>;
}

namespace shared
{
  using VAlloc =boost::container::scoped_allocator_adaptor<
          bip::allocator<void, bip::managed_shared_memory::segment_manager> >;

  using String = generic::String<VAlloc>;
  using StringVector = generic::StringVector<VAlloc>;
}

int main(void)
{
  struct shm_remove {
      shm_remove()  { bip::shared_memory_object::remove("MySharedMemory"); }
      ~shm_remove() { bip::shared_memory_object::remove("MySharedMemory"); }
  } remover;

  std::cout << "Heap based storage: \n";
  heap::StringVector svec;

  svec.Add(heap::String("test1"));
  svec.Add(heap::String("test2"));
  svec.Add(heap::String("test3"));
  svec.Add(heap::String("test4"));
  svec.Print();

  std::cout << "Shared memory storage: \n";
  bip::managed_shared_memory seg(bip::create_only, "MySharedMemory", 65536);
  shared::VAlloc shalloc(seg.get_segment_manager());

  shared::StringVector sh_svec(shalloc);
  sh_svec.Add(shared::String("test1", shalloc));
  sh_svec.Add(shared::String("test2", shalloc));
  sh_svec.Add(shared::String("test3", shalloc));
  sh_svec.Add(shared::String("test4", shalloc));
  sh_svec.Print();

  shared::StringVector sh_svec2(sh_svec, shalloc);
  sh_svec2.Print();

  //shared::StringVector sh_svec3(svec, shalloc);   // gives compile error :(
  //sh_svec3.Print();
}

Including compilation errors:

In file included from src/test_string_vector.cc:5:0:
/usr/include/boost/container/scoped_allocator.hpp: In instantiation of ‘boost::container::container_detail::scoped_allocator_adaptor_base<OuterAlloc>::scoped_allocator_adaptor_base() [with OuterAlloc = boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> >]’:
/usr/include/boost/container/scoped_allocator.hpp:963:7:   required from ‘boost::container::scoped_allocator_adaptor<OuterAlloc, InnerAllocs>::scoped_allocator_adaptor() [with OuterAlloc = boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> >; InnerAllocs = {}]’
/usr/include/boost/container/vector.hpp:1174:15:   required from ‘void boost::container::vector<T, Allocator>::assign(FwdIt, FwdIt, typename boost::container::container_detail::enable_if_c<((! boost::container::container_detail::is_convertible<InIt, typename boost::container::allocator_traits<Allocator>::size_type>::value) && ((! boost::container::container_detail::is_input_iterator<InIt>::value) && (! boost::move_detail::is_same<typename boost::container::container_detail::version<Allocator>::type, boost::container::container_detail::integral_constant<unsigned int, 0u> >::value)))>::type*) [with FwdIt = boost::container::container_detail::vec_iterator<generic::String<std::allocator<void> >*, true>; T = generic::String<boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > > >; Allocator = boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<generic::String<boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > > >, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > >; typename boost::container::container_detail::enable_if_c<((! boost::container::container_detail::is_convertible<InIt, typename boost::container::allocator_traits<Allocator>::size_type>::value) && ((! boost::container::container_detail::is_input_iterator<InIt>::value) && (! boost::move_detail::is_same<typename boost::container::container_detail::version<Allocator>::type, boost::container::container_detail::integral_constant<unsigned int, 0u> >::value)))>::type = void]’
/usr/include/boost/container/vector.hpp:864:7:   required from ‘boost::container::vector<T, Allocator>::vector(InIt, InIt, const allocator_type&) [with InIt = boost::container::container_detail::vec_iterator<generic::String<std::allocator<void> >*, true>; T = generic::String<boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > > >; Allocator = boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<generic::String<boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > > >, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > >; boost::container::vector<T, Allocator>::allocator_type = boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<generic::String<boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > > >, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > >]’
src/test_string_vector.cc:78:65:   required from ‘generic::StringVector<Alloc>::StringVector(const generic::StringVector<OtherAlloc>&, Alloc) [with OtherAlloc = std::allocator<void>; Alloc = boost::container::scoped_allocator_adaptor<boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > >]’
src/test_string_vector.cc:151:46:   required from here
/usr/include/boost/container/scoped_allocator.hpp:762:7: error: no matching function for call to ‘boost::interprocess::allocator<void, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> >::allocator()’
       {}
       ^
In file included from /usr/include/boost/interprocess/segment_manager.hpp:38:0,
                 from /usr/include/boost/interprocess/detail/managed_memory_impl.hpp:30,
                 from /usr/include/boost/interprocess/managed_shared_memory.hpp:25,
                 from src/test_string_vector.cc:1:
/usr/include/boost/interprocess/allocators/allocator.hpp:142:4: note: candidate: template<class T2> boost::interprocess::allocator<T, SegmentManager>::allocator(const boost::interprocess::allocator<T2, SegmentManager>&)
    allocator(const allocator<T2, SegmentManager> &other)
    ^
/usr/include/boost/interprocess/allocators/allocator.hpp:142:4: note:   template argument deduction/substitution failed:
In file included from src/test_string_vector.cc:5:0:
/usr/include/boost/container/scoped_allocator.hpp:762:7: note:   candidate expects 1 argument, 0 provided
       {}
       ^
In file included from /usr/include/boost/interprocess/segment_manager.hpp:38:0,
                 from /usr/include/boost/interprocess/detail/managed_memory_impl.hpp:30,
                 from /usr/include/boost/interprocess/managed_shared_memory.hpp:25,
                 from src/test_string_vector.cc:1:
/usr/include/boost/interprocess/allocators/allocator.hpp:136:4: note: candidate: boost::interprocess::allocator<T, SegmentManager>::allocator(const boost::interprocess::allocator<T, SegmentManager>&) [with T = void; SegmentManager = boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index>]
    allocator(const allocator &other)
    ^
/usr/include/boost/interprocess/allocators/allocator.hpp:136:4: note:   candidate expects 1 argument, 0 provided
/usr/include/boost/interprocess/allocators/allocator.hpp:131:4: note: candidate: boost::interprocess::allocator<T, SegmentManager>::allocator(boost::interprocess::allocator<T, SegmentManager>::segment_manager*) [with T = void; SegmentManager = boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index>; boost::interprocess::allocator<T, SegmentManager>::segment_manager = boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index>]
    allocator(segment_manager *segment_mngr)
    ^
/usr/include/boost/interprocess/allocators/allocator.hpp:131:4: note:   candidate expects 1 argument, 0 provided
Makefile:16: recipe for target 'obj/test_string_vector.o' failed
make: *** [obj/test_string_vector.o] Error 1

Body:
You did not provide your compilation errors, however just by briefly looking at the code and some working knowlege of boost::interprocess , I think your problem lies in std::allocator used for boost::interprocess , but I am not 100% sure, so please provide compilation errors.
In the meantime if you like

you can look at our open-source stack solution for Shared, Mmap, Heap
memory_types.hpp
I think you can  use boost::interprocess::allocator with boost::interprocess::managed_heap_memory::segment_manager or something like that.
Please also specify if you use C++03 or C++11 compiler as I think in C++03 it was
typedef T* pointer_type and that will not work with boost shared memory as it needs offset_ptr , basically offset from the beginning  of memory segment and not an absolute address.

I modified your code you had used shared::StringVector to store SHM structure
So now it compiles:

heap::StringVector sh_svec3(svec);   // does not gives compile error :-)
sh_svec3.Print();


来源: stackexchange

问:
Java parse String containing integers and multiple delimiters
Here is an example String, which contains 2 delimiters used for parsing the String to integers:

```<code>"1,25,3-6,14,16-19"
</code>```

The integers in the aforementioned string have to be parsed and added to ArrayList cotaining integers. So the ArrayList has to contain:

```<code>1,3,4,5,6,14,16,17,18,19,25
</code>```

The values in the original string are never mentioned twice. So, there are no crossing sections. Below you can see the incomplete code I wrote so far, but I think that I'm going in a completely wrong direction and there should be an easier way to solve the parsing.

```<code>List<Integer> temp = new ArrayList<>();
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char[] strCh = str.toCharArray();
for (int j = 0; j < strCh.length; j++) {
    char c = strCh[j];
    String number = "";
    char operator = 'n';
    if (Character.isDigit(c)) {
        do {
            number += c;
            j++;
            if (j != strCh.length - 1)
                c = strCh[j];
           } while (j < strCh.length && Character.isDigit(c));
    } else if (c == ',') {
        operator = ',';
        temp.add(Integer.parseInt(number));
        number = "";
    } else if (c == '-') {
        //still not sure
    }
}
</code>```

答:
You can try something like this:

```<code>String input = "1,25,3-6,14,16-19";

List<Integer> output = new ArrayList<Integer>();

for(String s : input.split(",")){
    try{
        if(!s.contains("-")){
           output.add(Integer.parseInt(s));
        }
        else{
            int i= Integer.parseInt(s.split("-")[0]);
            int upperBound = Integer.parseInt(s.split("-")[1]);
            for(;i<=upperBound;i++){
                 output.add(i);
            }
        }
    }catch(NumberFormatException e){
            e.printStackTrace();
    }
}
Collections.sort(output); // sort the result
System.out.println(output); // test
</code>```

Output

```<code>[1, 3, 4, 5, 14, 16, 17, 18, 19, 25]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is an example String, which contains 2 delimiters used for parsing the String to integers:

"1,25,3-6,14,16-19"

The integers in the aforementioned string have to be parsed and added to ArrayList cotaining integers. So the ArrayList has to contain:

1,3,4,5,6,14,16,17,18,19,25

The values in the original string are never mentioned twice. So, there are no crossing sections. Below you can see the incomplete code I wrote so far, but I think that I'm going in a completely wrong direction and there should be an easier way to solve the parsing.

List<Integer> temp = new ArrayList<>();
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char[] strCh = str.toCharArray();
for (int j = 0; j < strCh.length; j++) {
    char c = strCh[j];
    String number = "";
    char operator = 'n';
    if (Character.isDigit(c)) {
        do {
            number += c;
            j++;
            if (j != strCh.length - 1)
                c = strCh[j];
           } while (j < strCh.length && Character.isDigit(c));
    } else if (c == ',') {
        operator = ',';
        temp.add(Integer.parseInt(number));
        number = "";
    } else if (c == '-') {
        //still not sure
    }
}

Body:
You can try something like this:

String input = "1,25,3-6,14,16-19";

List<Integer> output = new ArrayList<Integer>();

for(String s : input.split(",")){
    try{
        if(!s.contains("-")){
           output.add(Integer.parseInt(s));
        }
        else{
            int i= Integer.parseInt(s.split("-")[0]);
            int upperBound = Integer.parseInt(s.split("-")[1]);
            for(;i<=upperBound;i++){
                 output.add(i);
            }
        }
    }catch(NumberFormatException e){
            e.printStackTrace();
    }
}
Collections.sort(output); // sort the result
System.out.println(output); // test

Output

[1, 3, 4, 5, 14, 16, 17, 18, 19, 25]


问:
Live Search with Node.js and MongoDB
So I am trying to make a live search feature where a user can search for other users based on username and the relevant results will be shown on the webpage. So far, I have only come across resources that show how to do this for PHP and MySQL. How can this be achieved for Node.js and MongoDB? I'm using socket.io in my project, could this be used at all?

Thanks for the help, and if any of my code is needed, just let me know!

答:
Basically, you would watch when the user writes in the username input field( using the keyup event) and send the value of the input field to the server using socket.io, on the server, when you receive the value in the event you will do a query on the database(model.findOne in mongoose) with that value and return the user if he exists. The key here is to make the database do an index on the username for a faster search by making the username field unique in mongoose or by creating a new index manually.

Example:

Frontend with jquery:

```<code>$(document).ready(function() {
   var username = $('#username');
   username.keyup(function() {
      var value = username.val();
      socket.emit('find_user', value);
   });
});

socket.on('find_user_result', function(user) {
    // treat result here
});
</code>```

Backend with mongoose:

```<code>socket.on('find_user', function(value) {
    User.findOne({username: value}, function(err, user) {
        if (err) throw err;
        if (!user) socket.emit('find_user_result', {});
        else socket.emit('find_user_result', user);
    });
})
</code>```

Title: Live Search with Node.js and MongoDB

Body:
Basically, you would watch when the user writes in the username input field( using the keyup event) and send the value of the input field to the server using socket.io, on the server, when you receive the value in the event you will do a query on the database(model.findOne in mongoose) with that value and return the user if he exists. The key here is to make the database do an index on the username for a faster search by making the username field unique in mongoose or by creating a new index manually.

Example:

Frontend with jquery:

$(document).ready(function() {
   var username = $('#username');
   username.keyup(function() {
      var value = username.val();
      socket.emit('find_user', value);
   });
});

socket.on('find_user_result', function(user) {
    // treat result here
});

Backend with mongoose:

socket.on('find_user', function(value) {
    User.findOne({username: value}, function(err, user) {
        if (err) throw err;
        if (!user) socket.emit('find_user_result', {});
        else socket.emit('find_user_result', user);
    });
})


问:
register new user from api route using laravel passport
I have installed laravel 5.3 and passport pakage.
I followed the documentaition step by step
I can use the following route POST /oauth/token with the following parameters

username

password

client_secret

grant_type

client_id

and I get the following response

```<code>{
  "token_type": "Bearer",
  "expires_in": 31536000,
  "access_token": "access token here",
  "refresh_token": "refresh token here"
}
</code>```

then I request GET /api/user

with the following header

Authorization = "Bearer access token here"

accept = application/json (optional)

and this is work fine and so all apis.

the problem I have is the user who I authinticated and entered his username and password in the first request and return me back the access token is a user I have created from laravel web view /register

How can I create new user or register new user from the api route file

like POST /api/register

the user at first time need to register to be authinticated after that.

Should I create this route without oauth to register then if success the registration he request POST /oauth/token to be authinticated or what?
Am I missing something ??

update
the clent_secret is it right to be constant in all users requests or each user should have diffrent clent_secret, and if it is how to create aclent secret if it neaded to authinticate user ?

答:
The fastest way to do this is adding an exception to your verifyCsrfToken.php class

```<code>protected $except = [
        'register'
    ];
</code>```

Then you can post to your register model, and afterwards accessing this account with oauth/token.

ContentLicense: CC BY-SA 4.0

Body:
I have installed laravel 5.3 and passport pakage.
I followed the documentaition step by step
I can use the following route POST /oauth/token with the following parameters

username

password

client_secret

grant_type

client_id

and I get the following response

{
  "token_type": "Bearer",
  "expires_in": 31536000,
  "access_token": "access token here",
  "refresh_token": "refresh token here"
}

then I request GET /api/user

with the following header

Authorization = "Bearer access token here"

accept = application/json (optional)

and this is work fine and so all apis.

the problem I have is the user who I authinticated and entered his username and password in the first request and return me back the access token is a user I have created from laravel web view /register

How can I create new user or register new user from the api route file

like POST /api/register

the user at first time need to register to be authinticated after that.

Should I create this route without oauth to register then if success the registration he request POST /oauth/token to be authinticated or what?
Am I missing something ??

update
the clent_secret is it right to be constant in all users requests or each user should have diffrent clent_secret, and if it is how to create aclent secret if it neaded to authinticate user ?

Body:
The fastest way to do this is adding an exception to your verifyCsrfToken.php class

protected $except = [
        'register'
    ];

Then you can post to your register model, and afterwards accessing this account with oauth/token.


问:
Error on Infinite scroll with Ajax, PHP and MySQL
I am trying to implement an infinite scroll in my application but at the moment of reaching the end of my page, this throws the error that places.

This is the ajax code:

```<code><script type="text/javascript">
    $(window).scroll(function() {
        if($(window).scrollTop() + $(window).height() >= $(document).height()) {
            var last_id = $(".post-id:last").attr("id");
            loadMoreData(last_id);
        }
    });

    function loadMoreData(last_id){
      $.ajax(
            {
                url: '/loadMoreData.php?last_id=' + last_id,
                type: "get",
                beforeSend: function()
                {
                    $('.ajax-load').show();
                }
            })
            .done(function(data)
            {
                $('.ajax-load').hide();
                $("#post-data").append(data);
            })
            .fail(function(jqXHR, ajaxOptions, thrownError)
            {
                  alert('server not responding...');
            });
    }
</script>
</code>```

Here, is where I show the data from th DataBase:

```<code><?php while ($post = $result -> fetch(PDO::FETCH_ASSOC)){ ?>

    <div class="box-list" id="post-data">
        <div class="item">
            <div class="row">
              <p class="post-id hidde" id="<?php echo $post['id']; ?>">
                <div class="col-md-1 hidden-sm hidden-xs">
                    <div class="img-item"><img src="<?php echo OTRA; ?>/images/<?php echo $post['thumb']; ?>" alt=""></div>
                </div>
                <div class="col-md-11">
                    <h3 class="no-margin-top"><a href="single.php?id=<?php echo $post['id']; ?>"><?php echo $post['titulo']; ?> <i class="fa fa-link color-white-mute font-1x"></i></a></h3>
                    <h5><span class="color-black"><?php echo $post['company']; ?></span> - <span class="color-white-mute"><?php echo $post['locacion']; ?></span></h5>
                    <p class="text-truncate "><?php echo $post['extracto']; ?></p>
                    <div>
                    <span class="color-white-mute"><?php echo fecha($post['fecha']); ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
<?php } ?>
</code>```

and this id the other PHP file to load more data:

```<code><?php session_start();

require 'extras/config.php';
require 'functions.php';

comprobarSession();

$conexion = conexion($bd_config);

$qry = "SELECT * FROM publications WHERE id > '$_GET['last_id']' ORDER BY id DESC LIMIT 8";
$result = $conexion->query($qry);
print_r ($result);

$json = include('views/empleos.php');

echo json_encode($json);
</code>```

on the Developer Tool of Chrome the error that show me is

jquery.js:8706 GET http://localhost/loadMoreData.php?last_id=9 404 (Not Found)

答: What is the name of that php file?  Sounds like it  is not loadMoreData.php?  Perhaps it is loadData.php, and the AJAX call should be changed?

Body:
I am trying to implement an infinite scroll in my application but at the moment of reaching the end of my page, this throws the error that places.

This is the ajax code:

Here, is where I show the data from th DataBase:

<?php while ($post = $result -> fetch(PDO::FETCH_ASSOC)){ ?>

              <p class="post-id hidde" id="<?php echo $post['id']; ?>">

<img src="<?php echo OTRA; ?>/images/<?php echo $post['thumb']; ?>" alt="">

<a href="single.php?id=<?php echo $post['id']; ?>"><?php echo $post['titulo']; ?>

<?php echo $post['company']; ?> - <?php echo $post['locacion']; ?>

<?php echo $post['extracto']; ?>

                    <?php echo fecha($post['fecha']); ?>

<?php } ?>

and this id the other PHP file to load more data:

<?php session_start();

require 'extras/config.php';
require 'functions.php';

comprobarSession();

$conexion = conexion($bd_config);

$qry = "SELECT * FROM publications WHERE id > '$_GET['last_id']' ORDER BY id DESC LIMIT 8";
$result = $conexion->query($qry);
print_r ($result);

$json = include('views/empleos.php');

echo json_encode($json);

on the Developer Tool of Chrome the error that show me is

jquery.js:8706 GET http://localhost/loadMoreData.php?last_id=9 404 (Not Found)


问:
How to initiate a singleton in Swift?
I have a class called HTTPHelper which is responsible for doing all my back end API requests. All methods in this class are class methods. As you know instance properties cannot be used from within a class method. I have some properties that need initialization with a do{}catch{} block which currently are being initiated from within an init(){} like so:

```<code>class HTTPHelper{
    init(){
        do {
            //initiate property
        } catch{}
    }
}
</code>```

My question is, is there a mechanism similar to an init(){} that would initiated a static property for a singleton?

答:
You can assign a property to the result of a closure or function (note the = and () at the end to execute the closure—this is not the same as a computed property, where the value is re-created every time). Instead, the first time you access the property the value is lazily computed once using your function/closure and then stored in the property for future access.

```<code>class MyClass {
    static let myProperty: String = {
        do {
            return try blah()
        } catch {
            // error handling
        }
    }()
}
</code>```

Of course, this is just a special case of assigning the result of a function to a property:

```<code>class MyClass {
    static let myProperty: String = MyClass.createMyString()

    static func createMyString() -> String {
        do {
            return try blah()
        } catch {
            // error handling
        }
    }
}
</code>```

Title: How to initiate a singleton in Swift?

Body:
I have a class called HTTPHelper which is responsible for doing all my back end API requests. All methods in this class are class methods. As you know instance properties cannot be used from within a class method. I have some properties that need initialization with a do{}catch{} block which currently are being initiated from within an init(){} like so:

class HTTPHelper{
    init(){
        do {
            //initiate property
        } catch{}
    }
}

My question is, is there a mechanism similar to an init(){} that would initiated a static property for a singleton?

Body:
You can assign a property to the result of a closure or function (note the = and () at the end to execute the closure—this is not the same as a computed property, where the value is re-created every time). Instead, the first time you access the property the value is lazily computed once using your function/closure and then stored in the property for future access.

class MyClass {
    static let myProperty: String = {
        do {
            return try blah()
        } catch {
            // error handling
        }
    }()
}

Of course, this is just a special case of assigning the result of a function to a property:

class MyClass {
    static let myProperty: String = MyClass.createMyString()

    static func createMyString() -> String {
        do {
            return try blah()
        } catch {
            // error handling
        }
    }
}


问:
echo outputs -e parameter in bash scripts. How can I prevent this?
I've read the man pages on echo, and it tells me that the -e parameter will allow an escaped character, such as an escaped n for newline, to have its special meaning. When I type the command

```<code>$ echo -e 'foo\nbar'
</code>```

into an interactive bash shell, I get the expected output:

```<code>foo
bar
</code>```

But when I use this same command (i've tried this command character for character as a test case) I get the following output:

```<code>-e foo
 bar
</code>```

It's as if echo is interpretting the -e as a parameter (because the newline still shows up) yet also it interprets the -e as a string to echo. What's going on here? How can I prevent the -e showing up?

答:
Use

alias echo /usr/bin/echo

to force 'echo' invoking coreutils' echo which interpret '-e' parameter.

ContentLicense: CC BY-SA 2.5

Body:
I've read the man pages on echo, and it tells me that the -e parameter will allow an escaped character, such as an escaped n for newline, to have its special meaning. When I type the command

$ echo -e 'foo\nbar'

into an interactive bash shell, I get the expected output:

foo
bar

But when I use this same command (i've tried this command character for character as a test case) I get the following output:

-e foo
 bar

It's as if echo is interpretting the -e as a parameter (because the newline still shows up) yet also it interprets the -e as a string to echo. What's going on here? How can I prevent the -e showing up?


问:
Porting CRC Calculation algorithm from C to Java
I need to calculate a CRC for a data array that is identical to the result of the _crc16_update function in avr-libc.

I understand the _crc16_update function to be:

```<code>uint16_t crc16_update(uint16_t crc, uint8_t a)
{
    int i;

    crc ^= a;
    for (i = 0; i < 8; ++i)
    {
        if (crc & 1)
            crc = (crc >> 1) ^ 0xA001;
        else
            crc = (crc >> 1);
    }

    return crc;
}
</code>```

My current code in an Android app to calculate the same CRC:

```<code>private short crc16Update( short crc, byte a )
{
    short i;

    crc ^= a;
    for( i = 0; i < 8; ++i )
    {
        if ( (crc & 1) > 0 )
            crc = (crc >>> 1) ^ 0xA001;
        else
            crc = (crc >>> 1);
     }

    return crc;
}
</code>```

I call that method with the following loop (_hexBytes is the array containing the data, _crc is supposed to hold the value identical to the CRC calculated by the avr-libc function):

```<code>for( Byte b : _hexBytes )
    _crc = crc16Update( _crc, b );
</code>```

I'm not getting the same result on both ends.  Can anybody see an error in my code to calculate the CRC?

Here is some test data I've used:

Data: [0x0c, 0x94, 0x39]

CRC from my Java code: 0x0827

CRC from the avr-libc code: 0xd16e

Maybe it's related to the Java short being signed?

答:
Throw it away and use the table-driven version, which is at least 8 times as fast. You have to adjust the parameters of course, e.g. your polynomial is 0xA001, which looks like POLYNOMIAL_IBM below.</p>

```<code>/**
 * CRC16. An implementation of {@link java.util.zip.Checksum} for 16-bit cyclic redundancy checks.
 *
 */

import java.util.zip.Checksum;

/**
 * CRC16. An implementation of {@link java.util.zip.Checksum} for 16-bit cyclic redundancy checks.
 *
 * @author Esmond Pitt.
 */
public class CRC16 implements Checksum
{
    public enum Algorithm
    {
        CRC_CCIT(POLYNOMIAL_CCITT, INIT_CCITT),
        XMODEM(POLYNOMIAL_XMODEM, (short)0),
        ARC(POLYNOMIAL_ARC, (short)0),
        IBM(POLYNOMIAL_IBM, (short)0),
        ANSI(POLYNOMIAL_IBM, (short)0);

        Algorithm(int polynomial, short initialValue)
        {
            this.polynomial = polynomial;
            this.initialValue = initialValue;
        }

        int polynomial;
        short initialValue;
    };

    /**
     * CRC-CCITT polynomial, used by X.25, V.41, Bluetooth, PPP, IrDA, BACnet; known as CRC-CCITT
     */
    public static final int POLYNOMIAL_CCITT = 0x1021;
    public static final short INIT_CCITT = (short)0xffff;
    /**
     * CRC-16 polynomial, used by XMODEM, USB, many others; also known as CRC-16
     */
    public static final int POLYNOMIAL_IBM = 0xa001;
    public static final int POLYNOMIAL_XMODEM   = 0x8408;
    public static final int POLYNOMIAL_ARC = 0x8005;

//  private final int   polynomial;
    private final short init;
    private final short[]   crcTable = new short[256];
    private short   value;

    /**
     * Construct a CRC16-CCIT, with polynomial=0x1021 and initial value=0xffff.
     */
    public CRC16()
    {
        this(Algorithm.CRC_CCIT);
    }

    /**
     *  COnstruct a polynomial specifying the algorithm.
     *
     * @param algorithm Algorithm
     */
    public CRC16(Algorithm algorithm)
    {
        this(algorithm.polynomial, algorithm.initialValue);
    }

    /**
     * Construct a CRC16 specifying the polynomial and initial value.
     * @param polynomial Polynomial, typically one of the POLYNOMIAL_* constants.
     * @param init Initial value, typically either 0xffff or zero.
     */
    public CRC16(int polynomial, short init)
    {
//      this.polynomial = polynomial;
        this.value = this.init = init;
        for (int dividend = 0; dividend < 256; dividend++)
        {
            int remainder = dividend << 8;
            for (int bit = 8; bit > 0; --bit)
                if ((remainder & 0x8000) != 0)
                    remainder = (remainder << 1) ^ polynomial;
                else
                    remainder <<= 1;
            crcTable[dividend] = (short)remainder;
        }
    }

    @Override
    public void update(byte[] buffer, int offset, int len)
    {
        for (int i = 0; i < len; i++)
        {
            int data = buffer[offset+i] ^ (value >>> 8);
            value = (short)(crcTable[data & 0xff] ^ (value << 8));
        }
    }

    /**
     * Updates the current checksum with the specified array of bytes.
     * Equivalent to calling <code>update(buffer, 0, buffer.length)</code>.
     * @param buffer the byte array to update the checksum with
     */
    public void update(byte[] buffer)
    {
        update(buffer, 0, buffer.length);
    }

    @Override
    public void update(int b)
    {
        update(new byte[]{(byte)b}, 0, 1);
    }

    @Override
    public long getValue()
    {
        return value;
    }

    @Override
    public void reset()
    {
        value = init;
    }

    /** Tester */
    public static void  main(String[] args)
    {
        byte[]  data = new byte[]{0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39};
        CRC16   crc16 = new CRC16();
        crc16.update(data,0,data.length);
        System.out.println("CCITT:\t\t\tinit=0xffff poly=0x1021 CRC16(\"123456789\")=0x29b1");
        System.out.println("Calculated:\t\tinit=0x"+Integer.toHexString(INIT_CCITT & 0xffff)+" poly=0x"+Integer.toHexString(POLYNOMIAL_CCITT)+" CRC16(\"123456789\")=0x"+Long.toHexString(crc16.getValue()));
        System.out.println("Test successful:\t"+(crc16.getValue() == 0x29b1));

        String  s = "hello";

        crc16 = new CRC16(POLYNOMIAL_IBM, INIT_CCITT);
        data = new byte[]{0x02, 0x14, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
        crc16.update(data, 0, data.length);
        System.out.println("CRC16=0x"+Integer.toHexString((int)crc16.getValue()  & 0xffff));
    }
}
</code>```

Body:
I need to calculate a CRC for a data array that is identical to the result of the _crc16_update function in avr-libc.

I understand the _crc16_update function to be:

uint16_t crc16_update(uint16_t crc, uint8_t a)
{
    int i;

    crc ^= a;
    for (i = 0; i < 8; ++i)
    {
        if (crc & 1)
            crc = (crc >> 1) ^ 0xA001;
        else
            crc = (crc >> 1);
    }

    return crc;
}

My current code in an Android app to calculate the same CRC:

private short crc16Update( short crc, byte a )
{
    short i;

    crc ^= a;
    for( i = 0; i < 8; ++i )
    {
        if ( (crc & 1) > 0 )
            crc = (crc >>> 1) ^ 0xA001;
        else
            crc = (crc >>> 1);
     }

    return crc;
}

I call that method with the following loop (_hexBytes is the array containing the data, _crc is supposed to hold the value identical to the CRC calculated by the avr-libc function):

for( Byte b : _hexBytes )
    _crc = crc16Update( _crc, b );

I'm not getting the same result on both ends.  Can anybody see an error in my code to calculate the CRC?

Here is some test data I've used:

Data: [0x0c, 0x94, 0x39]

CRC from my Java code: 0x0827

CRC from the avr-libc code: 0xd16e

Maybe it's related to the Java short being signed?

Body:
Throw it away and use the table-driven version, which is at least 8 times as fast. You have to adjust the parameters of course, e.g. your polynomial is 0xA001, which looks like POLYNOMIAL_IBM below.

/**
 * CRC16. An implementation of {@link java.util.zip.Checksum} for 16-bit cyclic redundancy checks.
 *
 */

import java.util.zip.Checksum;

/**
 * CRC16. An implementation of {@link java.util.zip.Checksum} for 16-bit cyclic redundancy checks.
 *
 * @author Esmond Pitt.
 */
public class CRC16 implements Checksum
{
    public enum Algorithm
    {
        CRC_CCIT(POLYNOMIAL_CCITT, INIT_CCITT),
        XMODEM(POLYNOMIAL_XMODEM, (short)0),
        ARC(POLYNOMIAL_ARC, (short)0),
        IBM(POLYNOMIAL_IBM, (short)0),
        ANSI(POLYNOMIAL_IBM, (short)0);

        Algorithm(int polynomial, short initialValue)
        {
            this.polynomial = polynomial;
            this.initialValue = initialValue;
        }

        int polynomial;
        short initialValue;
    };

    /**
     * CRC-CCITT polynomial, used by X.25, V.41, Bluetooth, PPP, IrDA, BACnet; known as CRC-CCITT
     */
    public static final int POLYNOMIAL_CCITT = 0x1021;
    public static final short INIT_CCITT = (short)0xffff;
    /**
     * CRC-16 polynomial, used by XMODEM, USB, many others; also known as CRC-16
     */
    public static final int POLYNOMIAL_IBM = 0xa001;
    public static final int POLYNOMIAL_XMODEM   = 0x8408;
    public static final int POLYNOMIAL_ARC = 0x8005;

//  private final int   polynomial;
    private final short init;
    private final short[]   crcTable = new short[256];
    private short   value;

    /**
     * Construct a CRC16-CCIT, with polynomial=0x1021 and initial value=0xffff.
     */
    public CRC16()
    {
        this(Algorithm.CRC_CCIT);
    }

    /**
     *  COnstruct a polynomial specifying the algorithm.
     *
     * @param algorithm Algorithm
     */
    public CRC16(Algorithm algorithm)
    {
        this(algorithm.polynomial, algorithm.initialValue);
    }

    /**
     * Construct a CRC16 specifying the polynomial and initial value.
     * @param polynomial Polynomial, typically one of the POLYNOMIAL_* constants.
     * @param init Initial value, typically either 0xffff or zero.
     */
    public CRC16(int polynomial, short init)
    {
//      this.polynomial = polynomial;
        this.value = this.init = init;
        for (int dividend = 0; dividend < 256; dividend++)
        {
            int remainder = dividend << 8;
            for (int bit = 8; bit > 0; --bit)
                if ((remainder & 0x8000) != 0)
                    remainder = (remainder << 1) ^ polynomial;
                else
                    remainder <<= 1;
            crcTable[dividend] = (short)remainder;
        }
    }

    @Override
    public void update(byte[] buffer, int offset, int len)
    {
        for (int i = 0; i < len; i++)
        {
            int data = buffer[offset+i] ^ (value >>> 8);
            value = (short)(crcTable[data & 0xff] ^ (value << 8));
        }
    }

    /**
     * Updates the current checksum with the specified array of bytes.
     * Equivalent to calling <code>update(buffer, 0, buffer.length)</code>.
     * @param buffer the byte array to update the checksum with
     */
    public void update(byte[] buffer)
    {
        update(buffer, 0, buffer.length);
    }

    @Override
    public void update(int b)
    {
        update(new byte[]{(byte)b}, 0, 1);
    }

    @Override
    public long getValue()
    {
        return value;
    }

    @Override
    public void reset()
    {
        value = init;
    }

    /** Tester */
    public static void  main(String[] args)
    {
        byte[]  data = new byte[]{0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39};
        CRC16   crc16 = new CRC16();
        crc16.update(data,0,data.length);
        System.out.println("CCITT:\t\t\tinit=0xffff poly=0x1021 CRC16(\"123456789\")=0x29b1");
        System.out.println("Calculated:\t\tinit=0x"+Integer.toHexString(INIT_CCITT & 0xffff)+" poly=0x"+Integer.toHexString(POLYNOMIAL_CCITT)+" CRC16(\"123456789\")=0x"+Long.toHexString(crc16.getValue()));
        System.out.println("Test successful:\t"+(crc16.getValue() == 0x29b1));

        String  s = "hello";

        crc16 = new CRC16(POLYNOMIAL_IBM, INIT_CCITT);
        data = new byte[]{0x02, 0x14, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
        crc16.update(data, 0, data.length);
        System.out.println("CRC16=0x"+Integer.toHexString((int)crc16.getValue()  & 0xffff));
    }
}


问:
What are the reasons and cases that cause git merge conflicts?

What are

the necessary and sufficient conditions, and/or

all the cases or some common cases

that can cause  git merge report merge conflict?

How does git merge determine whether a line or some lines contain
merge conflict(s)?

For example, I sometimes see cases like the following, where either
Part 1 or Part 2 is empty in

```<code><<<<<<< HEAD
(Part 1)
=======
(Part 2)
>>>>>>> some-other-branch
</code>```

It looks unlikely to have a merge conflict to me. So what are some possible reasons that
cases like that have merge conflicts?

Comparing  the merge conflicts reported by git merge  and the
differences reported by git diff,  is it correct that

the differences reported by git diff might not necessarily be in the places of the merge conflicts reported by git merge, and

the merge conflicts reported by git merge might not necessarily be in the places of the differences reported by git
diff?

Thanks.

答:
There are multiple parts to a complete, correct answer.  First, we have to get to a normal three way merge in the first place (which in Git requires using -s recursive or -s resolve, and if using -s recursive, finding a single merge base and two other commits).  You may, however, want to skip right down to the third section.

The elements required for a normal three-way merge

To do any merge at all, you need:

a merge base commit B,1

a current commit L (left side, aka HEAD) that has B as an ancestor,

another commit R that also has B as an ancestor.

Since "is ancestor" allows node equality in the commit graph (technically it's a predecessor-or-equal ≼ comparison), it's possible to have B = L and/or B = R.  If this is the case, however, then no merging is ever required, and if you do force a merge (using git merge --no-ff—this implies B = L and L ≺ R; the two unforced cases are "fast forward" not-actually-a-merge and a "nothing to merge" error) there will be no merge conflicts.  So we may as well assume that the merge base precedes both sides of the merge.

1Using --allow-unrelated-histories, you can have Git substitute in the empty tree for an actual base commit, if L and R have no lowest common ancestor nodes.  This, however, causes all identified files to be add/add conflicts.

Given a merge, the elements required for a conflict

Next, to get a conflict in some file path, you need either what I call a "high level" conflict or a "low level" conflict (or both).  For this to occur, Git must identify (i.e., match together) files in B, L, and R.  Due to the ability to add new files, rename files, and delete files, this does not require that the file have the same name in all three commits.  In particular:

If path P exists in all three of B, L, and R, the three files with path P are identified together.  (That is, there's a path PB, such as path/to/foo.txt, that has a matching PL path/to/foo.txt and PR path/to/foo.txt.  Obviously this file is "the same file" all throughout the merge, so Git identifies the three paths as one file.)

Or, there may be up to three different paths, PB path/to/basename, PL path2/to2/left, and PR path3/to3/right.  One or more of these may not even exist.  These result in: add/add conflict, if ∄ PB and PL = PR; a rename/delete conflict, if PB equals one of the left or right paths, but the other does not exist; or a rename/rename conflict, if PB ≠ PL ≠ PR.

If there is not already a high level conflict (add/add, rename/rename, or rename/delete), there may still be a rename/modify or rename/delete conflict, as long as the hash IDs of the blobs (file contents) named by the two or three path names do not match.

All of these "high level" conflicts cause a merge conflict, but do not by themselves result in any conflict markers.  To get that, we must now actually merge the base file with the two side files (which means all three files must exist, or for the add/add case, we take a trivial empty file as the base version).

This merge may or may not have its own conflicts.  If the merge adds low level conflicts, we will get conflict markers.  If there is no high level conflict (the path is the same in all three commits) but a full merge is required (the hashes all differ), we may get a low level conflict with conflict markers.

What Git requires for a conflict within a file

To get a merge conflict within one file in the work-tree, Git must see the same line changed by both left and right side versions, but changed in different ways.  (Remember, all three hashes must differ, so that Git is combining a set of changes from, in effect, diff PB PL with those from diff PB PR.)

The most obvious and least confusing cases

The most obvious case occurs for one side (let's choose the left side first) to say:

```<code> unchanged context
-changed line
+replacement 1
 more unchanged context
</code>```

and the other to say:

```<code> unchanged context
-changed line
+replacement 2
 more unchanged context
</code>```

Here one or more lines are deleted and in their stead, one or more lines are inserted, but the inserted lines do not match.  In this case the merge conflict style presents this as:

```<code>unchanged context
<<<<<<< left-label
replacement 1
=======
replacement 2
>>>>>>> right-label
more unchanged context
</code>```

The diff3 context style presents this instead as:

```<code>unchanged context
<<<<<<< left-label
replacement 1
||||||| merged common ancestors
changed line
=======
replacement 2
>>>>>>> right-label
more unchanged context
</code>```

If we merely add text, but add different text, at the same line, we also get a merge conflict.  Again, the added text from each side shows up in the conflict markers.  (If we add the same text to both sides—either as new text, or as replacement text for a changed line, Git takes one copy of this addition and there is no conflict.)

The somewhat confusing cases

If one but not both of the replacement lines is empty—i.e., if the left or right side diff reads:

```<code> unchanged context
-changed line
 more unchanged context
</code>```

then one but not both of the replacement lines in the merge or diff3 style marked-up file is missing.  (If both diffs simply delete the original lines, there is no conflict: Git takes one deletion.)

Similarly, if one side adds a line above or below a line that the other side deletes, you get a conflict.  This time the conflict shows that the side that retained-and-then-added a has all the lines, and other other side has no lines.  For instance:

```<code> some merge conflict.
 Line that will conflict.
+add line below it
 Rest of the
</code>```

vs:

```<code> some merge conflict.
-Line that will conflict.
 Rest of the
</code>```

(and the same occurs if you add the line above instead of below).

This is where the diff3 conflict style is very helpful.  Here's the entire merged file for the one of these cases:

```<code>We need a base file
in which to make
some merge conflict.
<<<<<<< HEAD
||||||| merged common ancestors
Line that will conflict.
=======
Change the line that will conflict.
>>>>>>> b2
Rest of the
base file for the
merge conflict example.
</code>```

Note that it's now obvious—or at least, less mysterious—that there was a line that read Line that will conflict. in the base version, which I deleted entirely from the left side HEAD version and replaced with a different line in the right side b2 version.

Body:
What are

the necessary and sufficient conditions, and/or

all the cases or some common cases

that can cause  git merge report merge conflict?

How does git merge determine whether a line or some lines contain
merge conflict(s)?

For example, I sometimes see cases like the following, where either
Part 1 or Part 2 is empty in

<<<<<<>>>>>> some-other-branch

It looks unlikely to have a merge conflict to me. So what are some possible reasons that
cases like that have merge conflicts?

Comparing  the merge conflicts reported by git merge  and the
differences reported by git diff,  is it correct that

the differences reported by git diff might not necessarily be in the places of the merge conflicts reported by git merge, and

the merge conflicts reported by git merge might not necessarily be in the places of the differences reported by git
diff?

Thanks.

Body:
There are multiple parts to a complete, correct answer.  First, we have to get to a normal three way merge in the first place (which in Git requires using -s recursive or -s resolve, and if using -s recursive, finding a single merge base and two other commits).  You may, however, want to skip right down to the third section.

The elements required for a normal three-way merge

To do any merge at all, you need:

a merge base commit B,1

a current commit L (left side, aka HEAD) that has B as an ancestor,

another commit R that also has B as an ancestor.

Since "is ancestor" allows node equality in the commit graph (technically it's a predecessor-or-equal ≼ comparison), it's possible to have B = L and/or B = R.  If this is the case, however, then no merging is ever required, and if you do force a merge (using git merge --no-ff—this implies B = L and L ≺ R; the two unforced cases are "fast forward" not-actually-a-merge and a "nothing to merge" error) there will be no merge conflicts.  So we may as well assume that the merge base precedes both sides of the merge.

1Using --allow-unrelated-histories, you can have Git substitute in the empty tree for an actual base commit, if L and R have no lowest common ancestor nodes.  This, however, causes all identified files to be add/add conflicts.

Given a merge, the elements required for a conflict

Next, to get a conflict in some file path, you need either what I call a "high level" conflict or a "low level" conflict (or both).  For this to occur, Git must identify (i.e., match together) files in B, L, and R.  Due to the ability to add new files, rename files, and delete files, this does not require that the file have the same name in all three commits.  In particular:

If path P exists in all three of B, L, and R, the three files with path P are identified together.  (That is, there's a path PB, such as path/to/foo.txt, that has a matching PL path/to/foo.txt and PR path/to/foo.txt.  Obviously this file is "the same file" all throughout the merge, so Git identifies the three paths as one file.)

Or, there may be up to three different paths, PB path/to/basename, PL path2/to2/left, and PR path3/to3/right.  One or more of these may not even exist.  These result in: add/add conflict, if ∄ PB and PL = PR; a rename/delete conflict, if PB equals one of the left or right paths, but the other does not exist; or a rename/rename conflict, if PB ≠ PL ≠ PR.

If there is not already a high level conflict (add/add, rename/rename, or rename/delete), there may still be a rename/modify or rename/delete conflict, as long as the hash IDs of the blobs (file contents) named by the two or three path names do not match.

All of these "high level" conflicts cause a merge conflict, but do not by themselves result in any conflict markers.  To get that, we must now actually merge the base file with the two side files (which means all three files must exist, or for the add/add case, we take a trivial empty file as the base version).

This merge may or may not have its own conflicts.  If the merge adds low level conflicts, we will get conflict markers.  If there is no high level conflict (the path is the same in all three commits) but a full merge is required (the hashes all differ), we may get a low level conflict with conflict markers.

What Git requires for a conflict within a file

To get a merge conflict within one file in the work-tree, Git must see the same line changed by both left and right side versions, but changed in different ways.  (Remember, all three hashes must differ, so that Git is combining a set of changes from, in effect, diff PB PL with those from diff PB PR.)

The most obvious and least confusing cases

The most obvious case occurs for one side (let's choose the left side first) to say:

 unchanged context
-changed line
+replacement 1
 more unchanged context

and the other to say:

 unchanged context
-changed line
+replacement 2
 more unchanged context

Here one or more lines are deleted and in their stead, one or more lines are inserted, but the inserted lines do not match.  In this case the merge conflict style presents this as:

unchanged context
<<<<<<< left-label
replacement 1
=======
replacement 2
>>>>>>> right-label
more unchanged context

The diff3 context style presents this instead as:

unchanged context
<<<<<<< left-label
replacement 1
||||||| merged common ancestors
changed line
=======
replacement 2
>>>>>>> right-label
more unchanged context

If we merely add text, but add different text, at the same line, we also get a merge conflict.  Again, the added text from each side shows up in the conflict markers.  (If we add the same text to both sides—either as new text, or as replacement text for a changed line, Git takes one copy of this addition and there is no conflict.)

The somewhat confusing cases

If one but not both of the replacement lines is empty—i.e., if the left or right side diff reads:

 unchanged context
-changed line
 more unchanged context

then one but not both of the replacement lines in the merge or diff3 style marked-up file is missing.  (If both diffs simply delete the original lines, there is no conflict: Git takes one deletion.)

Similarly, if one side adds a line above or below a line that the other side deletes, you get a conflict.  This time the conflict shows that the side that retained-and-then-added a has all the lines, and other other side has no lines.  For instance:

 some merge conflict.
 Line that will conflict.
+add line below it
 Rest of the

vs:

 some merge conflict.
-Line that will conflict.
 Rest of the

(and the same occurs if you add the line above instead of below).

This is where the diff3 conflict style is very helpful.  Here's the entire merged file for the one of these cases:

We need a base file
in which to make
some merge conflict.
<<<<<<< HEAD
||||||| merged common ancestors
Line that will conflict.
=======
Change the line that will conflict.
>>>>>>> b2
Rest of the
base file for the
merge conflict example.

Note that it's now obvious—or at least, less mysterious—that there was a line that read Line that will conflict. in the base version, which I deleted entirely from the left side HEAD version and replaced with a different line in the right side b2 version.


问:
Matching only Arabic and English Alphanumeric with one space allowed only
I have got a forum site and I am currently working on the final piece, the registration form and I want to validate the username. It should only contain Arabic and English alphanumerics and a maximum of one space between words.

I've got the english alphanumeric part working but not the Arabic nor the double spaces.

I am using the preg_match() function to match the username input with the RegEX.

What I currently have:

```<code>!preg_match('/\p{Arabic}/', $username) && !preg_match('/^[A-Za-z0-9]$/')
//this is currently inside and if statement, so if they both don't match then it is false.
</code>```

答:
You should put the unicode properties inside your regular regex because this can all be done with 1 regex. You also need to quantify that character class otherwise you only allow 1 character. This regex should do it.

```<code>^[\p{Arabic}a-zA-Z\p{N}]+\h?[\p{N}\p{Arabic}a-zA-Z]*$
</code>```

Use the u modifier in PHP so unicode works as expected.

PHP Usage:

```<code>preg_match('/^[\p{Arabic}a-zA-Z\p{N}]+\h?[\p{N}\p{Arabic}a-zA-Z]*$/u', $string);
</code>```

Demo: https://regex101.com/r/fsRchS/2/

Body:
I have got a forum site and I am currently working on the final piece, the registration form and I want to validate the username. It should only contain Arabic and English alphanumerics and a maximum of one space between words.

I've got the english alphanumeric part working but not the Arabic nor the double spaces.

I am using the preg_match() function to match the username input with the RegEX.

What I currently have:

!preg_match('/\p{Arabic}/', $username) && !preg_match('/^[A-Za-z0-9]$/')
//this is currently inside and if statement, so if they both don't match then it is false.

Body:
You should put the unicode properties inside your regular regex because this can all be done with 1 regex. You also need to quantify that character class otherwise you only allow 1 character. This regex should do it.

^[\p{Arabic}a-zA-Z\p{N}]+\h?[\p{N}\p{Arabic}a-zA-Z]*$

Use the u modifier in PHP so unicode works as expected.

PHP Usage:

preg_match('/^[\p{Arabic}a-zA-Z\p{N}]+\h?[\p{N}\p{Arabic}a-zA-Z]*$/u', $string);

Demo: https://regex101.com/r/fsRchS/2/


问:
How to auto-initiate ESLint in Atom using modified rules?
I'm just getting into Atom and ESLint - heck still a noob using Node and npm.

I've got a project working fine with Atom, Linter and ESLint, and I customized the rules of the "standard" config (as opposed to Google or AirBnB).

When I start a new project, however, nothing is carried over.  It looks like I have to re-init ESLint, and then it asks for the config file again, which is obviously not my customized version.

How can I get ESLint to run automatically whenever Atom opens a JS file, using my custom rules?

Thanks in advance and let me know if my terminology is off...

答: In most cases, we recommend checking .eslintrc files into source control. This makes sure that every developer working on a project is using the same ESLint config. However, if you want to have a shared config for all of your personal projects, you can put a .eslintrc file in your home directory. If a project doesn't specify its own .eslintrc, ESLint will look in your home directory and use that config instead. You can read more about that in our configuring docs.


问:
MySQL : search multiple columns with a single statement
I have a MySQL(5.7) table like this.

```<code>+--------+--------------+--------+-------+----------+--------+
| Field  | Type         | Null   | Key   | Default  | Extra  |
|--------+--------------+--------+-------+----------+--------|
| colA   | varchar(50)  | NO     | PRI   | <null>   |        |
| colB   | int(11)      | YES    |       | <null>   |        |
| colC   | int(11)      | YES    |       | <null>   |        |
| colD   | int(11)      | YES    |       | <null>   |        |
| colE   | int(11)      | YES    |       | <null>   |        |
| colF   | int(11)      | YES    |       | <null>   |        |
| colG   | int(11)      | YES    |       | <null>   |        |
| colH   | int(11)      | YES    |       | <null>   |        |
| colI   | int(11)      | YES    |       | <null>   |        |
| colJ   | int(11)      | YES    |       | <null>   |        |
| colK   | int(11)      | YES    |       | <null>   |        |
| colL   | int(11)      | YES    |       | <null>   |        |
| colM   | int(11)      | YES    |       | <null>   |        |
</code>```

I would like to search all the colB, colC, ..., colM mod 100 is 1 or 2. I know I can do this with this.

```<code>SELECT * FROM MYTABLE WHERE
(mod(colB, 100) = 1 OR mod(colB, 100) = 2) AND
(mod(colC, 100) = 1 OR mod(colC, 100) = 2) AND
(mod(colD, 100) = 1 OR mod(colD, 100) = 2) AND
                 :
(mod(colM, 100) = 1 OR mod(colM, 100) = 2)
</code>```

This SQL is very long and inefficient. Can I do this more smart?

答:
Your query is pretty much the only way to do it.  You can simplify it using in:

```<code>where mod(colB, 100) in (1, 2) AND
      mod(colC, 100) in (1, 2) AND
      . . .
</code>```

More importantly, though, the need for this type of operation suggests that all the columns are representing a similar entity.  That further suggests that you should be storing the values as one row per pair.  Such a table would look something like this:

```<code>colA
colType
colValue
</code>```

The query would be much simpler and shorter with this data structure.

Body:
I have a MySQL(5.7) table like this.

+--------+--------------+--------+-------+----------+--------+
| Field  | Type         | Null   | Key   | Default  | Extra  |
|--------+--------------+--------+-------+----------+--------|
| colA   | varchar(50)  | NO     | PRI   | <null>   |        |
| colB   | int(11)      | YES    |       | <null>   |        |
| colC   | int(11)      | YES    |       | <null>   |        |
| colD   | int(11)      | YES    |       | <null>   |        |
| colE   | int(11)      | YES    |       | <null>   |        |
| colF   | int(11)      | YES    |       | <null>   |        |
| colG   | int(11)      | YES    |       | <null>   |        |
| colH   | int(11)      | YES    |       | <null>   |        |
| colI   | int(11)      | YES    |       | <null>   |        |
| colJ   | int(11)      | YES    |       | <null>   |        |
| colK   | int(11)      | YES    |       | <null>   |        |
| colL   | int(11)      | YES    |       | <null>   |        |
| colM   | int(11)      | YES    |       | <null>   |        |

I would like to search all the colB, colC, ..., colM mod 100 is 1 or 2. I know I can do this with this.

SELECT * FROM MYTABLE WHERE
(mod(colB, 100) = 1 OR mod(colB, 100) = 2) AND
(mod(colC, 100) = 1 OR mod(colC, 100) = 2) AND
(mod(colD, 100) = 1 OR mod(colD, 100) = 2) AND
                 :
(mod(colM, 100) = 1 OR mod(colM, 100) = 2)

This SQL is very long and inefficient. Can I do this more smart?

Body:
Your query is pretty much the only way to do it.  You can simplify it using in:

where mod(colB, 100) in (1, 2) AND
      mod(colC, 100) in (1, 2) AND
      . . .

More importantly, though, the need for this type of operation suggests that all the columns are representing a similar entity.  That further suggests that you should be storing the values as one row per pair.  Such a table would look something like this:

colA
colType
colValue

The query would be much simpler and shorter with this data structure.


问:
Can't Install NuGet packages that require Newtonsoft.Json.10.0.1 in Visual Studio 2015
I've been having problem installing NuGet packages that require Newtonsoft.Json.10.0.1
I just recently installed it and when ever I try installing packages that need it, I get this error:

```<code>Severity    Code    Description Project File    Line
Error       An error occurred while retrieving package metadata for 'Newtonsoft.Json.10.0.1' from source 'C:\Users\Sharon Umute\documents\visual studio 2015\Projects\sermon\packages'.         0
</code>```

I tried upgrading to Newtonsoft.Json.10.0.2 and adding the path to Environment Variables but I keep getting the same error.
I've checked the path, the Newtonsoft.Json.10.0.2 folder contains lib, tools, and Newtonsoft.Json.10.0.1.nupkg.
I'd really appreciate some help with this.

答: open packages.config, delete <package id="Newtonsoft.Json"..>, then refresh it

Body:
I've been having problem installing NuGet packages that require Newtonsoft.Json.10.0.1
I just recently installed it and when ever I try installing packages that need it, I get this error:

Severity    Code    Description Project File    Line
Error       An error occurred while retrieving package metadata for 'Newtonsoft.Json.10.0.1' from source 'C:\Users\Sharon Umute\documents\visual studio 2015\Projects\sermon\packages'.         0

I tried upgrading to Newtonsoft.Json.10.0.2 and adding the path to Environment Variables but I keep getting the same error.
I've checked the path, the Newtonsoft.Json.10.0.2 folder contains lib, tools, and Newtonsoft.Json.10.0.1.nupkg.
I'd really appreciate some help with this.


问:
How to call asynchronous recursive functions after each other?
I am using trying to have typing text in a div that has three different lines of text. So I want to call the function typed_text() for line one, then call it again for line two, then line three. I tried to use promises, but I was lost when it came to using setTimeout() and recursion.

I call the function something like this.

```<code>typed_text("#line_one", frame.text_one, 0, 25)
        typed_text("#line_two", frame.text_two, 0, 25)
        typed_text("#line_three", frame.text_three, 0, 25)

        function typed_text(div, text, index, interval)
        {
            if (quit_typed_text == true) {
                interval = 0;
            }
            if (index < text.length) {
                $(div).append(text[index++]);
                setTimeout(function() {typed_text(div, text, index, interval); }, interval);
            } else {
                click_disabled = false;
            }

        }
</code>```

Edit: Here is what I was attempting using recursion and promises

```<code>    typed_text("#text_one", frame.text_one, 0, 25).then(typed_text("#text_two", frame.text_two, 0, 25));

function typed_text(div, text, index, interval)
{
    return new Promise(function (resolve) {
        if (quit_typed_text == true) {
            interval = 0;
        }
        if (index >= text.length) {
            click_disabled = false;
            resolve();
        }
    }).then(function() {
        if (index < text.length) {
            $(div).append(text[index++]);
            /* Problem is here, setTimeout.then() does not exist as a function */
            setTimeout(function() {typed_text(div, text, index, interval); }, interval);
        }
    });
}
</code>```

答:
using promises, your typed_text function can be rewritten as follows

```<code>function typed_text(div, text, index, interval) {
    return new Promise(function(resolve) {
        var doit = function() {
            if (quit_typed_text == true) {
                interval = 0;
            }
            if (index < text.length) {
                $(div).append(text[index++]);
                setTimeout(doit, interval);
            } else {
                click_disabled = false; // not sure this should be here
                resolve();
            }
        };
        doit(); // oops forgot this line
    });
}
</code>```

Then, to use it, simply use promise chaining as follows:

```<code>typed_text("#line_one", frame.text_one, 0, 25).then(function() {
    return typed_text("#line_two", frame.text_two, 0, 25);
}).then(function() {
    return typed_text("#line_three", frame.text_three, 0, 25);
}).then(function() {
    // all done here - perhaps this is where click_disabled = false should be?
});
</code>```

Body:
I am using trying to have typing text in a div that has three different lines of text. So I want to call the function typed_text() for line one, then call it again for line two, then line three. I tried to use promises, but I was lost when it came to using setTimeout() and recursion.

I call the function something like this.

typed_text("#line_one", frame.text_one, 0, 25)
        typed_text("#line_two", frame.text_two, 0, 25)
        typed_text("#line_three", frame.text_three, 0, 25)

        function typed_text(div, text, index, interval)
        {
            if (quit_typed_text == true) {
                interval = 0;
            }
            if (index < text.length) {
                $(div).append(text[index++]);
                setTimeout(function() {typed_text(div, text, index, interval); }, interval);
            } else {
                click_disabled = false;
            }

        }

Edit: Here is what I was attempting using recursion and promises

    typed_text("#text_one", frame.text_one, 0, 25).then(typed_text("#text_two", frame.text_two, 0, 25));

function typed_text(div, text, index, interval)
{
    return new Promise(function (resolve) {
        if (quit_typed_text == true) {
            interval = 0;
        }
        if (index >= text.length) {
            click_disabled = false;
            resolve();
        }
    }).then(function() {
        if (index < text.length) {
            $(div).append(text[index++]);
            /* Problem is here, setTimeout.then() does not exist as a function */
            setTimeout(function() {typed_text(div, text, index, interval); }, interval);
        }
    });
}

Body:
using promises, your typed_text function can be rewritten as follows

function typed_text(div, text, index, interval) {
    return new Promise(function(resolve) {
        var doit = function() {
            if (quit_typed_text == true) {
                interval = 0;
            }
            if (index < text.length) {
                $(div).append(text[index++]);
                setTimeout(doit, interval);
            } else {
                click_disabled = false; // not sure this should be here
                resolve();
            }
        };
        doit(); // oops forgot this line
    });
}

Then, to use it, simply use promise chaining as follows:

typed_text("#line_one", frame.text_one, 0, 25).then(function() {
    return typed_text("#line_two", frame.text_two, 0, 25);
}).then(function() {
    return typed_text("#line_three", frame.text_three, 0, 25);
}).then(function() {
    // all done here - perhaps this is where click_disabled = false should be?
});


问:
Using regex to parse kindle "My Clippings.txt" file
I am currently trying to use python to parse the notes file for my kindle so that I can keep them more organized than the chronologically ordered list that the kindle automatically saves notes in. Unfortunately, I'm having trouble using regex to parse the file. Here's my code so far:

```<code>import re

def parse_file(in_file):
    read_file = open(in_file, 'r')
    file_lines = read_file.readlines()
    read_file.close()
    raw_note = "".join(file_lines)

    # Regex parts
    title_regex = "(.+)"
    title_author_regex = "(.+) \((.+)\)"

    loc_norange_regex = "(.+) (Location|on Page) ([0-9]+)"
    loc_range_regex = "(.+) (Location|on Page) ([0-9]+)-([0-9]+)"

    date_regex = "([a-zA-Z]+), ([a-zA-Z]+) ([0-9]+), ([0-9]+)"  # Date
    time_regex = "([0-9]+):([0-9]+) (AM|PM)"  # Time

    content_regex = "(.*)"
    footer_regex = "=+"

    nl_re = "\r*\n"

    # No author
    regex_noauthor_str =\
    title_regex + nl_re +\
    "- Your " + loc_range_regex + " | Added on " +\
    date_regex + ", " + time_regex + nl_re +\
    content_regex + nl_re +\
    footer_regex

    regex_noauthor = re.compile(regex_noauthor_str)
    print regex_noauthor.findall(raw_note)

parse_file("testnotes")
</code>```

Here is the contents of "testnotes":

```<code>Title
- Your Highlight Location 3360-3362 | Added on Wednesday, March 21, 2012, 12:16 AM

Note content goes here
==========
</code>```

What I want:

```<code>[('Title', 'Highlight', 'Location', '3360', '3362', 'Wednesday', 'March', '21', '2012', '12', '16', 'AM',
</code>```

But when I run the program, I get:

```<code>[('Title', 'Highlight', 'Location', '3360', '3362', '', '', '', '', '', '', '', '')]
</code>```

I'm fairly new to regex, but I feel like this should be fairly straightforward.

答: Should anyone need an update to this, the following works with Paperwhite & Voyage Kindles in 2017 : https://gist.github.com/laffan/7b945d256028d2ffaacd4d99be40ca34</p>

Body:
I am currently trying to use python to parse the notes file for my kindle so that I can keep them more organized than the chronologically ordered list that the kindle automatically saves notes in. Unfortunately, I'm having trouble using regex to parse the file. Here's my code so far:

import re

def parse_file(in_file):
    read_file = open(in_file, 'r')
    file_lines = read_file.readlines()
    read_file.close()
    raw_note = "".join(file_lines)

    # Regex parts
    title_regex = "(.+)"
    title_author_regex = "(.+) \((.+)\)"

    loc_norange_regex = "(.+) (Location|on Page) ([0-9]+)"
    loc_range_regex = "(.+) (Location|on Page) ([0-9]+)-([0-9]+)"

    date_regex = "([a-zA-Z]+), ([a-zA-Z]+) ([0-9]+), ([0-9]+)"  # Date
    time_regex = "([0-9]+):([0-9]+) (AM|PM)"  # Time

    content_regex = "(.*)"
    footer_regex = "=+"

    nl_re = "\r*\n"

    # No author
    regex_noauthor_str =\
    title_regex + nl_re +\
    "- Your " + loc_range_regex + " | Added on " +\
    date_regex + ", " + time_regex + nl_re +\
    content_regex + nl_re +\
    footer_regex

    regex_noauthor = re.compile(regex_noauthor_str)
    print regex_noauthor.findall(raw_note)

parse_file("testnotes")

Here is the contents of "testnotes":

Title
- Your Highlight Location 3360-3362 | Added on Wednesday, March 21, 2012, 12:16 AM

Note content goes here
==========

What I want:

[('Title', 'Highlight', 'Location', '3360', '3362', 'Wednesday', 'March', '21', '2012', '12', '16', 'AM',

But when I run the program, I get:

[('Title', 'Highlight', 'Location', '3360', '3362', '', '', '', '', '', '', '', '')]

I'm fairly new to regex, but I feel like this should be fairly straightforward.


问:
search in laravel database with live results
I'm working with Laravel 5.4 and I have a list of users in admin panel I want to add search box in top of my users list to search them and I want to results be live (when typing words results shows) I guess should use Ajax for that(not sure!)

Let say this is my users list code:

```<code>@foreach ($users as $user)
  <td>{{ $user->first_name }}</td>
  <td>{{ $user->last_name }}</td>
  <td>{{ $user->username }}</td>
  <td>{{ $user->email }}</td>
@endforeach
</code>```

How can I get that search to work with it?

Should I install any plugin or just use Vue.Js or ...?

Thanks.

答:
You could use https://datatables.net/

Include in your html (if you're using gulp, use in your file who controls the dependencies)

```

    <table id="myTable">
        <thead>
            <th>First name</th>
            <th>Last name</th>
            <th>Username</th>
            <th>Email</th>
        </thead>
        <tbody>
            @foreach($users as $user)
            <td> {{ $user->first_name }} </td>
            <td> {{ $user->last_name }} </td>
            <td> {{ $user->username}} </td>
            <td> {{ $user->email }} </td>
            @endforeach
        </tbody>
    </table>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.15/css/dataTables.bootstrap.css" />

    <script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.15/js/jquery.dataTables.js">

    <script>
    $(document).ready(function(){
        $('#myTable').DataTable();
    });
    </script>

```

Body:
I'm working with Laravel 5.4 and I have a list of users in admin panel I want to add search box in top of my users list to search them and I want to results be live (when typing words results shows) I guess should use Ajax for that(not sure!)

Let say this is my users list code:

@foreach ($users as $user)
  {{ $user->first_name }}
  {{ $user->last_name }}
  {{ $user->username }}
  {{ $user->email }}
@endforeach

How can I get that search to work with it?

Should I install any plugin or just use Vue.Js or ...?

Thanks.

Body:
You could use https://datatables.net/

Include in your html (if you're using gulp, use in your file who controls the dependencies)

    <table id="myTable">
        <thead>
            <th>First name</th>
            <th>Last name</th>
            <th>Username</th>
            <th>Email</th>
        </thead>
        <tbody>
            @foreach($users as $user)
            <td> {{ $user->first_name }} </td>
            <td> {{ $user->last_name }} </td>
            <td> {{ $user->username}} </td>
            <td> {{ $user->email }} </td>
            @endforeach
        </tbody>
    </table>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.15/css/dataTables.bootstrap.css" />

    <script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.15/js/jquery.dataTables.js">

    <script>
    $(document).ready(function(){
        $('#myTable').DataTable();
    });
    </script>


问:
How to offer multiple versions of an API with different database schemas?
In Kevin Goldsmith's 2015 talk about microservices at Spotify (from 15:25 - 17:43), he mentions that when they create a new version of an API they just create a new server, and keep the old server running with the old version for as long as there are still clients calling it (in this case, a smart lamp with Spotify embedded on it).

I am confused about how they would be able to maintain and offer older versions for potentially years, when surely there would be database schema changes during that timeframe?

I can see a few possible solutions, but none of them seem very reasonable:

Using the same database across all versions, only ever add new tables, and new nullable fields. Never delete fields, nor rename fields, nor set fields to non-nullable, nor delete tables, nor rename tables.

Using a different database per version, keep each version's data separate.

Using a different database per version, keep each version's data separate, but write a way to migrate and pass the requests from one version to another, so that each version receives the request with the valid parameters for that version.

Solution 1 sounds like it would induce way too much code smell, with legacy code everywhere (which Kevin, in my opinion, seems to suggest they certainly do not do).

Solution 2 sounds like a nightmare to pull data out of for other services, or for reporting. What if the information about an entity that you want is in another version's database than the one you request?

Solution 3 sounds like more of a nightmare as you would have to write code to migrate a request for your version, to the versions above and below yours. This would mean that you can't just leave the existing (the one currently in production) version as-is when creating a new version, as you would need to add migrations to move the request both forward and backward so that all versions received the correct parameters for the request.

Hopefully I am just missing something simple here, and there is a magic solution to make this problem easier, but I really cannot see how they could accomplish this?

Thanks!

答:
I have no idea how spotify does this internally.

Just at a guess though from the way he was talking about it, I'm not sure these microservices were storing any data at all. I got the feeling that they were essentially a presentation layer on top of something else (perhaps an internal service layer).

If a microservice can have multiple versions active, and it is also the owner of some data then one of two things are probably happening:

Schema consistancy is applied at the service level, if a change is made to the schema it must be updated in all historic versions. In the case of multiple versions being deployed independantly this would nessecitate a deploy of all versions on a schema change (he didnt talk like this was the case, but this is how I've always done versioning)

Each version owns an independant copy of the data. To do this you really need to have a pub/sub model in the system and perform all modifications as a result of some kind of message. (to me this seems pretty inefficient unless its very low churn, but perhaps at that scale it might make sense, there is also a problem with how to prime a new version with data)

I dont think running a schema and never changing it would really work long term. Things change and changes are nessacary. One of the biggest benifits of microservies/SOA (IMO) is that change is easier as the domains are small and containted. You can do things like completely change the storage mechanism (perhaps even to a new type of storage) reasonably safely and quickly as the volume of code is low.

More thoughts on microservice versioning in my article, Microservice versioning; How to make breaking changes without breaking stuff


问:
Remove from Dictionary by Key and Retrieve Value
Is there a way to remove an entry from a Dictionary (by Key) AND retrieve its Value in the same step?

For example, I'm calling

```<code>Dictionary.Remove(Key);
</code>```

but I also want it to return the Value at the same time. The function only returns a bool.

I know I can do something like

```<code>Value = Dictionary[Key];
Dictionary.Remove(Key);
</code>```

but it seems like this will search the dictionary twice (once to get the value, and another time to remove it from the dictionary). How can I (if possible) do both WITHOUT searching the dictionary twice?

答:
The concurrentDictionary has a TryRemove method that attempts to remove and return the value that has the specified key from the System.Collections.Concurrent.ConcurrentDictionary<TKey, TValue>.
It returns the default value of the TValue type if key does not exist.

https://msdn.microsoft.com/en-us/library/dd287129(v=vs.110).aspx

Body:
Is there a way to remove an entry from a Dictionary (by Key) AND retrieve its Value in the same step?

For example, I'm calling

Dictionary.Remove(Key);

but I also want it to return the Value at the same time. The function only returns a bool.

I know I can do something like

Value = Dictionary[Key];
Dictionary.Remove(Key);

but it seems like this will search the dictionary twice (once to get the value, and another time to remove it from the dictionary). How can I (if possible) do both WITHOUT searching the dictionary twice?


问:
Count Stored Procedures in Database?
How can i count the number of stored procedures in my database and is it a bad practice to have too many stored procedures?</p>

答:
```<code>Select count(*) from sysobjects where xtype = 'P'
</code>```

OwnerDisplayName: Jack

Title: Count Stored Procedures in Database?

LastEditorDisplayName: Cade Roux

OwnerDisplayName: JPunyon