问:
Evaluating a mathematical expression in a string form
This is a standard interview question, evaluate a mathematical expression given in the form of a string.

So provided, '3+3-6*2'
The answer should be -6

Now if the expressions only support four operations +,-,*,/
Then is there a simple way to do it using a stack.

I've solved it by converting the infix notation to postfix and then solving it using a stack - but I'm looking for a different approach that supports only these four operations. This is my solution,

def evaluate(self, s: str) -> int:
    expr = [i for i in re.split(r'(\d+|\W+)', s) if i]
    rpn = self.convertToPostfix(expr)
    return self.evalPostfix(rpn)

def convertToPostfix(self, infix: list) -> list:
    stack = collections.deque()
    result = []
    for item in infix:
        if item.isdigit():
            result.append(item)
        else:
            while len(stack) > 0 and self.has_higher_precedence(stack[-1], item):
                result.append(stack[-1])
                stack.pop()
            stack.append(item)
    while len(stack) > 0:
        result.append(stack.pop())
    return result

def has_higher_precedence(self, a: str, b: str) -> bool:
    if a == '/' and b == '*' or b == '+' or b == '-':
        return True
    if a == '*' and b == '+' or '-':
        return True
    if a == '+' and b == '-':
        return True
    return False

def evalPostfix(self, p: list) -> int:
    stack = collections.deque()
    for item in p:
        if item.isdigit():
            stack.append(int(item))
        elif item[1:].isdigit():
            stack.append(int(item))
        else:
            curr = stack.pop()
            prev = stack.pop()
            if item == '+':
                total = prev + curr
            elif item == '-':
                total = prev - curr
            elif item == '*':
                total = prev * curr
            else:
                total = prev / curr
            stack.append(total)
    return stack.pop()
```

Also I'm aware that this can be solved by designing a recursive lexical parser but that's beyond the scope of this question.

So my question is, is there a simple way to do this in O(n) time using a stack if there are only four operators

答:
You can modify the Shunting-yard algorithm to parse and evaluate in a single pass. There is no need for the intermediate step of converting to postfix. Restricting the problem to just the four standard mathematical operators with no parentheses doesn't change the basic approach.

Here's the standard Shunting-yard algorithm, from the linked article. I've added line numbers for reference below:

```<code> 1: while there are tokens to be read:
 2: read a token.
 3: if the token is a number, then push it to the output queue.
 4: if the token is an operator, then:
 5:     while (there is an operator at the top of the operator stack with
 6:         greater precedence) or (the operator at the top of the operator stack has
 7:                        equal precedence and
 8:                        the operator is left associative) and
 9:                      (the operator at the top of the stack is not a left bracket):
10:             pop operators from the operator stack, onto the output queue.
11:     push the read operator onto the operator stack.
12: if the token is a left bracket (i.e. "("), then:
13:     push it onto the operator stack.
14: if the token is a right bracket (i.e. ")"), then:
15:     while the operator at the top of the operator stack is not a left bracket:
16:         pop operators from the operator stack onto the output queue.
17:     pop the left bracket from the stack.
        /* if the stack runs out without finding a left bracket, then there are
18:     mismatched parentheses. */
19: if there are no more tokens to read:
20:     while there are still operator tokens on the stack:
21:         /* if the operator token on the top of the stack is a bracket, then
22:         there are mismatched parentheses. */
23:         pop the operator onto the output queue.
24: exit.
</code>```

The modifications involve replacing the output queue with an operand stack: a stack of integers. So, for example, on line 3 instead of pushing the number to the output queue, you push the number onto the operand stack. This will of course require you to convert the character to an integer.

Then, on line 10 where you pop operators from the operator stack and push to the output queue, you instead:

Pop an operator

Pop two operands from the operand stack

Perform the operation

Push the result back onto the operand stack

You replace lines 16 and 23 with the same kind of logic.

If at any time when you're evaluating, there are not enough operands on the operand stack, then you have mismatched operators: something like 2+3+- (unless you decide to support unary + and unary -), or  2*/3.

When you've reached line 24, the operator stack is empty and the operand stack should contain a single value: the final result. If is more than one item on the operand stack, then you have too many operands (shouldn't happen).

So replace line 24 with a pop from the operand stack, and you can return that as the result.

The Shunting-yard is actually a very simplified version of the "recursive lexical parser" that you mentioned. But rather than building stack frames through recursion, it manipulates the stacks directly.

Modifying your code to do this shouldn't be too difficult. Below is a modified version of your convertToPostfix function, called evaluateInfix, that does it all in a single pass. Note that I'm not a Python programmer, so I won't guarantee the code to work flawlessly, but it should give you the idea:

```<code>def evaluateInfix(self, infix: list) -> int:
    operatorStack = collections.deque()
    operandStack = collections.deque()
    result = []
    for item in infix:
        if item.isdigit():
            val = convertDigitToNumber(item)  // however that's done
            // push to operand stack
            operandStack.append(val)
        else:
            while len(operatorStack) > 0 and self.has_higher_precedence(operatorStack[-1], item):
                // pop two operands from stack, evaluate, and push result
                // call this "pop and eval"
                op2 = operandStack[-1]
                operandStack.pop()
                op1 = operandStack[-1]
                operandStack.pop()
                operator = operatorStack[-1]
                operatorStack.pop()
                val = evaluate(operator, op1, op2) // this function evaluates op1 <operator> op2

                // push result back onto operand stack
                operandStack.append(val)
            operatorStack.append(item)
    while len(operatorStack) > 0:
        // insert "pop and eval" code here
    // at this point there should be a single value on the operand stack
    return operandStack[-1]
</code>```

The evaluate function takes an operator and two operands, does the operation, and returns the result. So given ('+', 3, 5), it would compute 3+5, and return 8.

The idea here is that whenever you evaluate, you're taking two operands and a single operator.

Test case: 3+5*2.

```<code>       operand    operator
char    stack      stack
--------------------------
  3     [3]       []
  +     [3]       [+]
  5     [3,5]     [+]
  *     [3,5]     [+,*]
  2     [3,5,2]   [+,*]
 <end>
 at this point, we're at the end of the string.
 Pop 2 and 5 from the operand stack, pop * from the operator stack,
 and evaluate
        [3,10]    [+]
 pop and eval again
        [13]      []
 operator stack is empty. Pop result from operand stack and return.
</code>```

Body:
This is a standard interview question, evaluate a mathematical expression given in the form of a string.

So provided, '3+3-6*2'
The answer should be -6

Now if the expressions only support four operations +,-,*,/
Then is there a simple way to do it using a stack.

I've solved it by converting the infix notation to postfix and then solving it using a stack - but I'm looking for a different approach that supports only these four operations. This is my solution,

def evaluate(self, s: str) -> int:
    expr = [i for i in re.split(r'(\d+|\W+)', s) if i]
    rpn = self.convertToPostfix(expr)
    return self.evalPostfix(rpn)

def convertToPostfix(self, infix: list) -> list:
    stack = collections.deque()
    result = []
    for item in infix:
        if item.isdigit():
            result.append(item)
        else:
            while len(stack) > 0 and self.has_higher_precedence(stack[-1], item):
                result.append(stack[-1])
                stack.pop()
            stack.append(item)
    while len(stack) > 0:
        result.append(stack.pop())
    return result

def has_higher_precedence(self, a: str, b: str) -> bool:
    if a == '/' and b == '*' or b == '+' or b == '-':
        return True
    if a == '*' and b == '+' or '-':
        return True
    if a == '+' and b == '-':
        return True
    return False

def evalPostfix(self, p: list) -> int:
    stack = collections.deque()
    for item in p:
        if item.isdigit():
            stack.append(int(item))
        elif item[1:].isdigit():
            stack.append(int(item))
        else:
            curr = stack.pop()
            prev = stack.pop()
            if item == '+':
                total = prev + curr
            elif item == '-':
                total = prev - curr
            elif item == '*':
                total = prev * curr
            else:
                total = prev / curr
            stack.append(total)
    return stack.pop()

Also I'm aware that this can be solved by designing a recursive lexical parser but that's beyond the scope of this question.

So my question is, is there a simple way to do this in O(n) time using a stack if there are only four operators

Body:
You can modify the Shunting-yard algorithm to parse and evaluate in a single pass. There is no need for the intermediate step of converting to postfix. Restricting the problem to just the four standard mathematical operators with no parentheses doesn't change the basic approach.

Here's the standard Shunting-yard algorithm, from the linked article. I've added line numbers for reference below:

 1: while there are tokens to be read:
 2: read a token.
 3: if the token is a number, then push it to the output queue.
 4: if the token is an operator, then:
 5:     while (there is an operator at the top of the operator stack with
 6:         greater precedence) or (the operator at the top of the operator stack has
 7:                        equal precedence and
 8:                        the operator is left associative) and
 9:                      (the operator at the top of the stack is not a left bracket):
10:             pop operators from the operator stack, onto the output queue.
11:     push the read operator onto the operator stack.
12: if the token is a left bracket (i.e. "("), then:
13:     push it onto the operator stack.
14: if the token is a right bracket (i.e. ")"), then:
15:     while the operator at the top of the operator stack is not a left bracket:
16:         pop operators from the operator stack onto the output queue.
17:     pop the left bracket from the stack.
        /* if the stack runs out without finding a left bracket, then there are
18:     mismatched parentheses. */
19: if there are no more tokens to read:
20:     while there are still operator tokens on the stack:
21:         /* if the operator token on the top of the stack is a bracket, then
22:         there are mismatched parentheses. */
23:         pop the operator onto the output queue.
24: exit.

The modifications involve replacing the output queue with an operand stack: a stack of integers. So, for example, on line 3 instead of pushing the number to the output queue, you push the number onto the operand stack. This will of course require you to convert the character to an integer.

Then, on line 10 where you pop operators from the operator stack and push to the output queue, you instead:

Pop an operator

Pop two operands from the operand stack

Perform the operation

Push the result back onto the operand stack

You replace lines 16 and 23 with the same kind of logic.

If at any time when you're evaluating, there are not enough operands on the operand stack, then you have mismatched operators: something like 2+3+- (unless you decide to support unary + and unary -), or  2*/3.

When you've reached line 24, the operator stack is empty and the operand stack should contain a single value: the final result. If is more than one item on the operand stack, then you have too many operands (shouldn't happen).

So replace line 24 with a pop from the operand stack, and you can return that as the result.

The Shunting-yard is actually a very simplified version of the "recursive lexical parser" that you mentioned. But rather than building stack frames through recursion, it manipulates the stacks directly.

Modifying your code to do this shouldn't be too difficult. Below is a modified version of your convertToPostfix function, called evaluateInfix, that does it all in a single pass. Note that I'm not a Python programmer, so I won't guarantee the code to work flawlessly, but it should give you the idea:

def evaluateInfix(self, infix: list) -> int:
    operatorStack = collections.deque()
    operandStack = collections.deque()
    result = []
    for item in infix:
        if item.isdigit():
            val = convertDigitToNumber(item)  // however that's done
            // push to operand stack
            operandStack.append(val)
        else:
            while len(operatorStack) > 0 and self.has_higher_precedence(operatorStack[-1], item):
                // pop two operands from stack, evaluate, and push result
                // call this "pop and eval"
                op2 = operandStack[-1]
                operandStack.pop()
                op1 = operandStack[-1]
                operandStack.pop()
                operator = operatorStack[-1]
                operatorStack.pop()
                val = evaluate(operator, op1, op2) // this function evaluates op1 <operator> op2

                // push result back onto operand stack
                operandStack.append(val)
            operatorStack.append(item)
    while len(operatorStack) > 0:
        // insert "pop and eval" code here
    // at this point there should be a single value on the operand stack
    return operandStack[-1]

The evaluate function takes an operator and two operands, does the operation, and returns the result. So given ('+', 3, 5), it would compute 3+5, and return 8.

The idea here is that whenever you evaluate, you're taking two operands and a single operator.

Test case: 3+5*2.

       operand    operator
char    stack      stack
--------------------------
  3     [3]       []
  +     [3]       [+]
  5     [3,5]     [+]
  *     [3,5]     [+,*]
  2     [3,5,2]   [+,*]
 <end>
 at this point, we're at the end of the string.
 Pop 2 and 5 from the operand stack, pop * from the operator stack,
 and evaluate
        [3,10]    [+]
 pop and eval again
        [13]      []
 operator stack is empty. Pop result from operand stack and return.


来源: stackexchange

问:
Network client simulator design

I am trying to design a software in c++ that will send request bytes (following a standard **application level** protocol whose fields to be populated will be taken from a text file) using **UDP protocol**.
Now this client must be able to send these requests at very high rate..upto **2000 transactions per second** and should also receive the response if it gets within a specified timeout else don't receive it

I will be using boost library for all the socket things but I am not sure about the design of it for such high speed application :(

I think I have to use a highly multi-threaded application (again Boost will be used). Am I right ? Do I have to create a seperate thread for each request ? But I think only one thread must be waiting to recieve the response else if many threads are waiting for a response how can we distinguish for which threads request we have got the response for !!

Hope that question is clear. I just need some help regarding the design points and suspected problems that I may face.

答:
I'm halfway through a network client of my own at the moment, so perhaps I can impart some advice and some resources to look at.  There are many more experienced in this area, and hopefully they'll chime in :)

Firstly, you're about boost.  Once you get used to how it all hangs together, boost::asio is a great toolkit for writing network-code.  Essentially, you create an io_service and call run to execute until all work is complete, or runOne to perform a single IO action.  On their own, this isn't that helpful.  The power comes from when you either run runOne in it's own loop:

```<code>boost::asio::io_service myIOService;
while(true)
{
    myIOService.runOne();
}
</code>```

, or run the run function on one (or more) threads:

```<code>boost::thread t(boost::bind(&boost::asio::io_service::run, &myIOService));
</code>```

However, it is worth noting that run returns as soon as there is no work to do (so you can say goodbye to that thread).  As I found out here on Stackoverflow, the trick is to ensure it always has something to do.  The solution is in boost::asio::io_service::work:

```<code>boost::asio::io_service::work myWork(myIOService);   // just some abstract "work"
</code>```

The above line ensures your thread won't stop when nothing is going on.  I view is as a means to keep-alive :)

At some point, you're going to want to create a socket and connect it somewhere.  I created a generic Socket class (and derived a text-socket from that to create buffered input).  I also wanted an event-based system that worked very much like C#.  I've outlined this stuff for you, below:

First step, we need a generic way of passing arguments around, hence, EventArgs:

eventArgs.h

```<code> class EventArgs : boost::noncopyable
 {
 private:

 public:
  EventArgs();
  virtual ~EventArgs() = 0;
 }; // eo class EventArgs:
</code>```

Now, we need an event class which people can subscribe/unsubscribe to:

event.h

```<code>// STL
#include <functional>
#include <stack>

// Boost
#include <boost/bind.hpp>
#include <boost/thread/mutex.hpp>

 // class Event
 class Event : boost::noncopyable
 {
 public:
  typedef std::function<void(const EventArgs&)> DelegateType;
  typedef boost::shared_ptr<DelegateType> DelegateDecl;

 private:
  boost::mutex m_Mutex;
  typedef std::set<DelegateDecl> DelegateSet;
  typedef std::stack<DelegateDecl> DelegateStack;
  typedef DelegateSet::const_iterator DelegateSet_cit;
  DelegateSet m_Delegates;
  DelegateStack m_ToRemove;

 public:
  Event()
  {
  }; // eo ctor

  Event(Event&& _rhs) : m_Delegates(std::move(_rhs.m_Delegates))
  {
  }; // eo mtor

  ~Event()
  {
  }; // eo dtor

  // static methods
  static DelegateDecl bindDelegate(DelegateType _f)
  {
   DelegateDecl ret(new DelegateType(_f));
   return ret;
  }; // eo bindDelegate

  // methods
  void raise(const EventArgs& _args)
  {
   boost::mutex::scoped_lock lock(m_Mutex);

   // get rid of any we have to remove
   while(m_ToRemove.size())
   {
    m_Delegates.erase(m_Delegates.find(m_ToRemove.top()));
    m_ToRemove.pop();
   };

   if(m_Delegates.size())
   std::for_each(m_Delegates.begin(),
        m_Delegates.end(),
        [&_args](const DelegateDecl& _decl) { (*_decl)(_args); });
  }; // eo raise

  DelegateDecl addListener(DelegateDecl _decl)
  {
   boost::mutex::scoped_lock lock(m_Mutex);
   m_Delegates.insert(_decl);
   return _decl;
  }; // eo addListener

  DelegateDecl addListener(DelegateType _f)
  {
   DelegateDecl ret(bindDelegate(_f));
   return addListener(ret);
  }; // eo addListener

  void removeListener(const DelegateDecl _decl)
  {
   boost::mutex::scoped_lock lock(m_Mutex);
   DelegateSet_cit cit(m_Delegates.find(_decl));
   if(cit != m_Delegates.end())
    m_ToRemove.push(_decl);
  }; // eo removeListener

  // operators

  // Only use operator += if you don't which to manually detach using removeListener
  Event& operator += (DelegateType _f)
  {
   addListener(_f);
   return *this;
  }; // eo op +=

 }; // eo class Event
</code>```

Then, it was time to create a socket class.  Below is the header:

socket.h

(Some notes: ByteVector is typedef std::vector<unsigned char>)

```<code>#pragma once

#include "event.h"

// boost
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/buffer.hpp>
  // class Socket
  class MORSE_API Socket : boost::noncopyable
  {
  protected:
   typedef boost::shared_ptr<boost::asio::ip::tcp::socket> SocketPtr;

  private:
   ByteVector      m_Buffer;   // will be used to read in

   SocketPtr        m_SocketPtr;
   boost::asio::ip::tcp::endpoint      m_RemoteEndPoint;
   bool         m_bConnected;

   // reader
   void _handleConnect(const boost::system::error_code& _errorCode, boost::asio::ip::tcp::resolver_iterator _rit);
   void _handleRead(const boost::system::error_code& _errorCode, std::size_t read);
  protected:

   SocketPtr socket() { return m_SocketPtr; };
  public:
   Socket(ByteVector_sz _bufSize = 512);
   virtual ~Socket();

   // properties
   bool isConnected() const { return m_bConnected; };
   const boost::asio::ip::tcp::endpoint& remoteEndPoint() const {return m_RemoteEndPoint; };

   // methods
   void connect(boost::asio::ip::tcp::resolver_iterator _rit);
   void connect(const String& _host, const Port _port);
   void close();

   // Events
   Event onRead;
   Event onResolve;
   Event onConnect;
   Event onClose;
  }; // eo class Socket
</code>```

And, now the implementation.  You'll notice it calls another class to perform DNS resolution.  I will show that afterwards.  Also there are some EventArg-derivatives I have ommitted.  They are simply passed as EventArg parameters when socket events occur.

socket.cpp

```<code>#include "socket.h"

// boost
#include <boost/asio/placeholders.hpp>

namespace morse
{
 namespace net
 {
  // ctor
  Socket::Socket(ByteVector_sz _bufSize /* = 512 */) : m_bConnected(false)
  {
   m_Buffer.resize(_bufSize);
  }; // eo ctor

  // dtor
  Socket::~Socket()
  {
  }; // eo dtor

  // _handleRead
  void Socket::_handleRead(const boost::system::error_code& _errorCode,
            std::size_t _read)
  {
   if(!_errorCode)
   {
    if(_read)
    {
     onRead.raise(SocketReadEventArgs(*this, m_Buffer, _read));
     // read again
     m_SocketPtr->async_read_some(boost::asio::buffer(m_Buffer), boost::bind(&Socket::_handleRead, this, _1, _2));
    };
   }
   else
    close();
  }; // eo _handleRead

  // _handleConnect
  void Socket::_handleConnect(const boost::system::error_code& _errorCode,
         boost::asio::ip::tcp::resolver_iterator _rit)
  {
   m_bConnected = !_errorCode;
   bool _raise(false);
   if(!_errorCode)
   {
    m_RemoteEndPoint = *_rit;
    _raise = true;
    m_SocketPtr->async_read_some(boost::asio::buffer(m_Buffer), boost::bind(&Socket::_handleRead, this, _1, _2));
   }
   else if(++_rit != boost::asio::ip::tcp::resolver::iterator())
   {
    m_SocketPtr->close();
    m_SocketPtr->async_connect(*_rit, boost::bind(&Socket::_handleConnect, this, boost::asio::placeholders::error, _rit));
   }
   else
    _raise = true; // raise complete failure

   if(_raise)
    onConnect.raise(SocketConnectEventArgs(*this, _errorCode));

  }; // eo _handleConnect

  // connect
  void Socket::connect(boost::asio::ip::tcp::resolver_iterator _rit)
  {
   boost::asio::ip::tcp::endpoint ep(*_rit);
   m_SocketPtr.reset(new boost::asio::ip::tcp::socket(Root::instance().ioService()));
   m_SocketPtr->async_connect(ep, boost::bind(&Socket::_handleConnect, this, boost::asio::placeholders::error, _rit));
  };

  void Socket::connect(const String& _host, Port _port)
  {
   // Anon function for resolution of the host-name and asynchronous calling of the above
   auto anonResolve = [this](const boost::system::error_code& _errorCode,
           boost::asio::ip::tcp::resolver_iterator _epIt)
   {
    // raise event
    onResolve.raise(SocketResolveEventArgs(*this, !_errorCode ? (*_epIt).host_name() : String(""), _errorCode));

    // perform connect, calling back to anonymous function
    if(!_errorCode)
     this->connect(_epIt);
   };

   // Resolve the host calling back to anonymous function
   Root::instance().resolveHost(_host, _port, anonResolve);

  }; // eo connect

  void Socket::close()
  {
   if(m_bConnected)
   {
    onClose.raise(SocketCloseEventArgs(*this));
    m_SocketPtr->close();
    m_bConnected = false;
   };
  } // eo close
</code>```

As I said about DNS resolution, the line Root::instance().resolveHost(_host, _port, anonResolve); calls this to perform asynchronous DNS:

```<code>  // resolve a host asynchronously
  template<typename ResolveHandler>
  void resolveHost(const String& _host, Port _port, ResolveHandler _handler)
  {
   boost::asio::ip::tcp::endpoint ret;
   boost::asio::ip::tcp::resolver::query query(_host, boost::lexical_cast<std::string>(_port));
   m_Resolver.async_resolve(query, _handler);
  }; // eo resolveHost
</code>```

Finally, I need a text-based socket that raised an event every time I line was received (which is then processed).  I'll omit the header file this time and just show the implementation file.  Needless to say it declares an Event called onLine which it fires every time a line is received in it's entirety:

```<code>// boost
#include <boost/asio/buffer.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/placeholders.hpp>

namespace morse
{
 namespace net
 {
  String TextSocket::m_DefaultEOL("\r\n");

  // ctor
  TextSocket::TextSocket() : m_EOL(m_DefaultEOL)
  {
   onRead += boost::bind(&TextSocket::readHandler, this, _1);
  }; // eo ctor

  // dtor
  TextSocket::~TextSocket()
  {
  }; // eo dtor

  // readHandler
  void TextSocket::readHandler(const EventArgs& _args)
  {
   auto& args(static_cast<const SocketReadEventArgs&>(_args));
   m_LineBuffer.append(args.buffer().begin(), args.buffer().begin() + args.bytesRead());
   String::size_type pos;
   while((pos = m_LineBuffer.find(eol())) != String::npos)
   {
    onLine.raise(SocketLineEventArgs(*this, m_LineBuffer.substr(0, pos)));
    m_LineBuffer = m_LineBuffer.substr(pos + eol().length());
   };
  }; // eo readHandler

  // writeHandler
  void TextSocket::writeHandler(const boost::system::error_code& _errorCode, std::size_t _written)
  {
   if(!_errorCode)
   {
    m_Queue.pop_front();
    if(!m_Queue.empty()) // more to do?
     boost::asio::async_write(*socket().get(), boost::asio::buffer(m_Queue.front(), m_Queue.front().length()), boost::bind(&TextSocket::writeHandler, this, _1, _2));
   }
   else
    close();
  }; // eo writeHandler

  void TextSocket::sendLine(String _line)
  {
   Root::instance().ioService().post(boost::bind(&TextSocket::_sendLine, this, _line));
  }; // eo sendLine

  // _sendLine
  void TextSocket::_sendLine(String _line)
  {
   // copy'n'queue
   _line.append(m_EOL);
   m_Queue.push_back(_line);
   if(m_Queue.size() == 1) // previously an empty queue, must start write!
    boost::asio::async_write(*socket().get(), boost::asio::buffer(m_Queue.front(), m_Queue.front().length()), boost::bind(&TextSocket::writeHandler, this, _1, _2));
  }; // eo sendLine
</code>```

Some things to note about the class above...  it uses boost::asio::post to send lines.  This allows it to all occur on the threads that ASIO manages in a thread-safe way, and allows us to queue up lines to be sent as and when.  This makes it very scalable.

I am sure there are many more questions and maybe my code isn't helpful.  I spent several days piecing it all together and making sense of it, and I doubt it's actually any good.  hopefully some better minds will glance over it and go "HOLY CRAP, THIS

ContentLicense: CC BY-SA 2.5

Title: Network client simulator design

Body:
I'm halfway through a network client of my own at the moment, so perhaps I can impart some advice and some resources to look at.  There are many more experienced in this area, and hopefully they'll chime in :)

Firstly, you're about boost.  Once you get used to how it all hangs together, boost::asio is a great toolkit for writing network-code.  Essentially, you create an io_service and call run to execute until all work is complete, or runOne to perform a single IO action.  On their own, this isn't that helpful.  The power comes from when you either run runOne in it's own loop:

boost::asio::io_service myIOService;
while(true)
{
    myIOService.runOne();
}

, or run the run function on one (or more) threads:

boost::thread t(boost::bind(&boost::asio::io_service::run, &myIOService));

However, it is worth noting that run returns as soon as there is no work to do (so you can say goodbye to that thread).  As I found out here on Stackoverflow, the trick is to ensure it always has something to do.  The solution is in boost::asio::io_service::work:

boost::asio::io_service::work myWork(myIOService);   // just some abstract "work"

The above line ensures your thread won't stop when nothing is going on.  I view is as a means to keep-alive :)

At some point, you're going to want to create a socket and connect it somewhere.  I created a generic Socket class (and derived a text-socket from that to create buffered input).  I also wanted an event-based system that worked very much like C#.  I've outlined this stuff for you, below:

First step, we need a generic way of passing arguments around, hence, EventArgs:

eventArgs.h

 class EventArgs : boost::noncopyable
 {
 private:

 public:
  EventArgs();
  virtual ~EventArgs() = 0;
 }; // eo class EventArgs:

Now, we need an event class which people can subscribe/unsubscribe to:

event.h

// STL
#include <functional>
#include <stack>

// Boost
#include <boost/bind.hpp>
#include <boost/thread/mutex.hpp>

 // class Event
 class Event : boost::noncopyable
 {
 public:
  typedef std::function<void(const EventArgs&)> DelegateType;
  typedef boost::shared_ptr<DelegateType> DelegateDecl;

 private:
  boost::mutex m_Mutex;
  typedef std::set<DelegateDecl> DelegateSet;
  typedef std::stack<DelegateDecl> DelegateStack;
  typedef DelegateSet::const_iterator DelegateSet_cit;
  DelegateSet m_Delegates;
  DelegateStack m_ToRemove;

 public:
  Event()
  {
  }; // eo ctor

  Event(Event&& _rhs) : m_Delegates(std::move(_rhs.m_Delegates))
  {
  }; // eo mtor

  ~Event()
  {
  }; // eo dtor

  // static methods
  static DelegateDecl bindDelegate(DelegateType _f)
  {
   DelegateDecl ret(new DelegateType(_f));
   return ret;
  }; // eo bindDelegate

  // methods
  void raise(const EventArgs& _args)
  {
   boost::mutex::scoped_lock lock(m_Mutex);

   // get rid of any we have to remove
   while(m_ToRemove.size())
   {
    m_Delegates.erase(m_Delegates.find(m_ToRemove.top()));
    m_ToRemove.pop();
   };

   if(m_Delegates.size())
   std::for_each(m_Delegates.begin(),
        m_Delegates.end(),
        [&_args](const DelegateDecl& _decl) { (*_decl)(_args); });
  }; // eo raise

  DelegateDecl addListener(DelegateDecl _decl)
  {
   boost::mutex::scoped_lock lock(m_Mutex);
   m_Delegates.insert(_decl);
   return _decl;
  }; // eo addListener

  DelegateDecl addListener(DelegateType _f)
  {
   DelegateDecl ret(bindDelegate(_f));
   return addListener(ret);
  }; // eo addListener

  void removeListener(const DelegateDecl _decl)
  {
   boost::mutex::scoped_lock lock(m_Mutex);
   DelegateSet_cit cit(m_Delegates.find(_decl));
   if(cit != m_Delegates.end())
    m_ToRemove.push(_decl);
  }; // eo removeListener

  // operators

  // Only use operator += if you don't which to manually detach using removeListener
  Event& operator += (DelegateType _f)
  {
   addListener(_f);
   return *this;
  }; // eo op +=

 }; // eo class Event

Then, it was time to create a socket class.  Below is the header:

socket.h

(Some notes: ByteVector is typedef std::vector<unsigned char>)

#pragma once

#include "event.h"

// boost
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/buffer.hpp>
  // class Socket
  class MORSE_API Socket : boost::noncopyable
  {
  protected:
   typedef boost::shared_ptr<boost::asio::ip::tcp::socket> SocketPtr;

  private:
   ByteVector      m_Buffer;   // will be used to read in

   SocketPtr        m_SocketPtr;
   boost::asio::ip::tcp::endpoint      m_RemoteEndPoint;
   bool         m_bConnected;

   // reader
   void _handleConnect(const boost::system::error_code& _errorCode, boost::asio::ip::tcp::resolver_iterator _rit);
   void _handleRead(const boost::system::error_code& _errorCode, std::size_t read);
  protected:

   SocketPtr socket() { return m_SocketPtr; };
  public:
   Socket(ByteVector_sz _bufSize = 512);
   virtual ~Socket();

   // properties
   bool isConnected() const { return m_bConnected; };
   const boost::asio::ip::tcp::endpoint& remoteEndPoint() const {return m_RemoteEndPoint; };

   // methods
   void connect(boost::asio::ip::tcp::resolver_iterator _rit);
   void connect(const String& _host, const Port _port);
   void close();

   // Events
   Event onRead;
   Event onResolve;
   Event onConnect;
   Event onClose;
  }; // eo class Socket

And, now the implementation.  You'll notice it calls another class to perform DNS resolution.  I will show that afterwards.  Also there are some EventArg-derivatives I have ommitted.  They are simply passed as EventArg parameters when socket events occur.

socket.cpp

#include "socket.h"

// boost
#include <boost/asio/placeholders.hpp>

namespace morse
{
 namespace net
 {
  // ctor
  Socket::Socket(ByteVector_sz _bufSize /* = 512 */) : m_bConnected(false)
  {
   m_Buffer.resize(_bufSize);
  }; // eo ctor

  // dtor
  Socket::~Socket()
  {
  }; // eo dtor

  // _handleRead
  void Socket::_handleRead(const boost::system::error_code& _errorCode,
            std::size_t _read)
  {
   if(!_errorCode)
   {
    if(_read)
    {
     onRead.raise(SocketReadEventArgs(*this, m_Buffer, _read));
     // read again
     m_SocketPtr->async_read_some(boost::asio::buffer(m_Buffer), boost::bind(&Socket::_handleRead, this, _1, _2));
    };
   }
   else
    close();
  }; // eo _handleRead

  // _handleConnect
  void Socket::_handleConnect(const boost::system::error_code& _errorCode,
         boost::asio::ip::tcp::resolver_iterator _rit)
  {
   m_bConnected = !_errorCode;
   bool _raise(false);
   if(!_errorCode)
   {
    m_RemoteEndPoint = *_rit;
    _raise = true;
    m_SocketPtr->async_read_some(boost::asio::buffer(m_Buffer), boost::bind(&Socket::_handleRead, this, _1, _2));
   }
   else if(++_rit != boost::asio::ip::tcp::resolver::iterator())
   {
    m_SocketPtr->close();
    m_SocketPtr->async_connect(*_rit, boost::bind(&Socket::_handleConnect, this, boost::asio::placeholders::error, _rit));
   }
   else
    _raise = true; // raise complete failure

   if(_raise)
    onConnect.raise(SocketConnectEventArgs(*this, _errorCode));

  }; // eo _handleConnect

  // connect
  void Socket::connect(boost::asio::ip::tcp::resolver_iterator _rit)
  {
   boost::asio::ip::tcp::endpoint ep(*_rit);
   m_SocketPtr.reset(new boost::asio::ip::tcp::socket(Root::instance().ioService()));
   m_SocketPtr->async_connect(ep, boost::bind(&Socket::_handleConnect, this, boost::asio::placeholders::error, _rit));
  };

  void Socket::connect(const String& _host, Port _port)
  {
   // Anon function for resolution of the host-name and asynchronous calling of the above
   auto anonResolve = [this](const boost::system::error_code& _errorCode,
           boost::asio::ip::tcp::resolver_iterator _epIt)
   {
    // raise event
    onResolve.raise(SocketResolveEventArgs(*this, !_errorCode ? (*_epIt).host_name() : String(""), _errorCode));

    // perform connect, calling back to anonymous function
    if(!_errorCode)
     this->connect(_epIt);
   };

   // Resolve the host calling back to anonymous function
   Root::instance().resolveHost(_host, _port, anonResolve);

  }; // eo connect

  void Socket::close()
  {
   if(m_bConnected)
   {
    onClose.raise(SocketCloseEventArgs(*this));
    m_SocketPtr->close();
    m_bConnected = false;
   };
  } // eo close

As I said about DNS resolution, the line Root::instance().resolveHost(_host, _port, anonResolve); calls this to perform asynchronous DNS:

  // resolve a host asynchronously
  template<typename ResolveHandler>
  void resolveHost(const String& _host, Port _port, ResolveHandler _handler)
  {
   boost::asio::ip::tcp::endpoint ret;
   boost::asio::ip::tcp::resolver::query query(_host, boost::lexical_cast<std::string>(_port));
   m_Resolver.async_resolve(query, _handler);
  }; // eo resolveHost

Finally, I need a text-based socket that raised an event every time I line was received (which is then processed).  I'll omit the header file this time and just show the implementation file.  Needless to say it declares an Event called onLine which it fires every time a line is received in it's entirety:

// boost
#include <boost/asio/buffer.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/placeholders.hpp>

namespace morse
{
 namespace net
 {
  String TextSocket::m_DefaultEOL("\r\n");

  // ctor
  TextSocket::TextSocket() : m_EOL(m_DefaultEOL)
  {
   onRead += boost::bind(&TextSocket::readHandler, this, _1);
  }; // eo ctor

  // dtor
  TextSocket::~TextSocket()
  {
  }; // eo dtor

  // readHandler
  void TextSocket::readHandler(const EventArgs& _args)
  {
   auto& args(static_cast<const SocketReadEventArgs&>(_args));
   m_LineBuffer.append(args.buffer().begin(), args.buffer().begin() + args.bytesRead());
   String::size_type pos;
   while((pos = m_LineBuffer.find(eol())) != String::npos)
   {
    onLine.raise(SocketLineEventArgs(*this, m_LineBuffer.substr(0, pos)));
    m_LineBuffer = m_LineBuffer.substr(pos + eol().length());
   };
  }; // eo readHandler

  // writeHandler
  void TextSocket::writeHandler(const boost::system::error_code& _errorCode, std::size_t _written)
  {
   if(!_errorCode)
   {
    m_Queue.pop_front();
    if(!m_Queue.empty()) // more to do?
     boost::asio::async_write(*socket().get(), boost::asio::buffer(m_Queue.front(), m_Queue.front().length()), boost::bind(&TextSocket::writeHandler, this, _1, _2));
   }
   else
    close();
  }; // eo writeHandler

  void TextSocket::sendLine(String _line)
  {
   Root::instance().ioService().post(boost::bind(&TextSocket::_sendLine, this, _line));
  }; // eo sendLine

  // _sendLine
  void TextSocket::_sendLine(String _line)
  {
   // copy'n'queue
   _line.append(m_EOL);
   m_Queue.push_back(_line);
   if(m_Queue.size() == 1) // previously an empty queue, must start write!
    boost::asio::async_write(*socket().get(), boost::asio::buffer(m_Queue.front(), m_Queue.front().length()), boost::bind(&TextSocket::writeHandler, this, _1, _2));
  }; // eo sendLine

Some things to note about the class above...  it uses boost::asio::post to send lines.  This allows it to all occur on the threads that ASIO manages in a thread-safe way, and allows us to queue up lines to be sent as and when.  This makes it very scalable.

I am sure there are many more questions and maybe my code isn't helpful.  I spent several days piecing it all together and making sense of it, and I doubt it's actually any good.  hopefully some better minds will glance over it and go "HOLY CRAP, THIS


问:
Argument capturing on the insides of closures in Spock
I am trying to test a method that does an invocation with a closure, something like this:

```<code>def foo(Long param) {
    AnObject.doSomething {
       bar(param)
    }
}
</code>```

And I want to test that doSomething is called with a closure that calls bar with the expected value inside.

I'm able to test properly the doSomething invocation by creating a spy and doing

```<code>when:
    service.foo(1L)
then:
    1 * AnObject.doSomething{_}
</code>```

However, I cannot seem to find a way to perform assertions on the contents of the closure.

What's the appropriate way to assert that inside the closure bar gets called with 1L?

答:
Without seeing more of your code, I think you would need to spy on the class providing the bar method. This is a bit contrived because the test is supplying the closure, but I think it is something like this:</p>

```<code>import spock.lang.Specification

class Bar {
    void bar(def param) {
        println param
    }
}

class DoSomethingTestSpec extends Specification {

    class AnObject {

        void doSomething(Closure c) {

            def param = 1L

            c.call(param)
        }
    }

    def "test AnObject doSomething calls the closure"() {

        given:
        def closure = { def p ->
            Bar.bar(p)
        }

        and:
        GroovySpy(Bar, global:true)

        and:
        AnObject anObject = new AnObject()

        when:
        anObject.doSomething(closure)

        then:
        1 * Bar.bar(_) >> { args ->
            assert args[0] == 1L
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to test a method that does an invocation with a closure, something like this:

def foo(Long param) {
    AnObject.doSomething {
       bar(param)
    }
}

And I want to test that doSomething is called with a closure that calls bar with the expected value inside.

I'm able to test properly the doSomething invocation by creating a spy and doing

when:
    service.foo(1L)
then:
    1 * AnObject.doSomething{_}

However, I cannot seem to find a way to perform assertions on the contents of the closure.

What's the appropriate way to assert that inside the closure bar gets called with 1L?

Body:
Without seeing more of your code, I think you would need to spy on the class providing the bar method. This is a bit contrived because the test is supplying the closure, but I think it is something like this:

import spock.lang.Specification

class Bar {
    void bar(def param) {
        println param
    }
}

class DoSomethingTestSpec extends Specification {

    class AnObject {

        void doSomething(Closure c) {

            def param = 1L

            c.call(param)
        }
    }

    def "test AnObject doSomething calls the closure"() {

        given:
        def closure = { def p ->
            Bar.bar(p)
        }

        and:
        GroovySpy(Bar, global:true)

        and:
        AnObject anObject = new AnObject()

        when:
        anObject.doSomething(closure)

        then:
        1 * Bar.bar(_) >> { args ->
            assert args[0] == 1L
        }
    }
}


问:
Magento 2.2 composer installation with ubuntu 16
So i run composer in magento root folder after few minutes of installation it ends with message

Is all of this packages are required to use magento and why it doesnt ask for keys.

答:
These packages are merely suggested by the package creators. The creators can specify the packages it suggests and the text that is shown.

Example:

```<code>{
    "suggest": {
        "monolog/monolog": "Allows more advanced logging of the application flow",
        "ext-xml": "Needed to support XML format in class Foo"
    }
}
</code>```

These packages are not required to run Magento. Looks like your composer install was successful.

Body:
These packages are merely suggested by the package creators. The creators can specify the packages it suggests and the text that is shown.

Example:

{
    "suggest": {
        "monolog/monolog": "Allows more advanced logging of the application flow",
        "ext-xml": "Needed to support XML format in class Foo"
    }
}

These packages are not required to run Magento. Looks like your composer install was successful.


问:
I am loading image to tab3 but when sliding my tab recycle view items increased when I come back to first tab
I have also try to change setHasFixsize(true) but it is not working
problem is when I am com to my own tab then item of tab is increase double times
triple times etc
There is activity that content fragment mtabfragment I have create three fragment java file to three tab layout and connect with these three activity

```<code>`public class NewsFeeds extends Fragment {

DatabaseReference databaseReference;
private LinearLayoutManager layoutManager;

RecyclerView recyclerView;

RecyclerView.Adapter adapter ;

ProgressDialog progressDialog;

List<ImageUploadInfo> list = new ArrayList<>();

Context context,contextpuja ;
GridView gridViewPuja,gridViewAll,gridViewC;
View view;

public NewsFeeds() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    context = getActivity();

    view = inflater.inflate(R.layout.fragment_news_feeds2,container, false);

    return view;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    final FragmentActivity fragmentActivity = getActivity();
    layoutManager = new LinearLayoutManager(fragmentActivity);

    recyclerView =  view.findViewById(R.id.recyclerView);

    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    progressDialog = new ProgressDialog(getActivity());

    progressDialog.setMessage("Loading Images From Firebase.");

     progressDialog.show();

    databaseReference = FirebaseDatabase.getInstance().getReference(Main2Activity.FB_Database_Path);

    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {

            for (DataSnapshot postSnapshot : snapshot.getChildren()) {

                ImageUploadInfo imageUploadInfo = postSnapshot.getValue(ImageUploadInfo.class);

                list.add(imageUploadInfo);
            }

            adapter = new RecyclerViewAdapter(getContext(), list);

            recyclerView.setAdapter(adapter);
            recyclerView.setHasFixedSize(true);

            progressDialog.dismiss();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

                          progressDialog.dismiss();

        }
    });

}
</code>```

}

答:
You have initialized your list at the start. So after every api call new items gets added to it. To avoid that, you add this line
list.clear();
before this line
adapter = new RecyclerViewAdapter(getContext(), list);
or Do not initialize your list before. put new ArrayList(); inside onDataChange method.

Body:
I have also try to change setHasFixsize(true) but it is not working
problem is when I am com to my own tab then item of tab is increase double times
triple times etc
There is activity that content fragment mtabfragment I have create three fragment java file to three tab layout and connect with these three activity

`public class NewsFeeds extends Fragment {

DatabaseReference databaseReference;
private LinearLayoutManager layoutManager;

RecyclerView recyclerView;

RecyclerView.Adapter adapter ;

ProgressDialog progressDialog;

List<ImageUploadInfo> list = new ArrayList<>();

Context context,contextpuja ;
GridView gridViewPuja,gridViewAll,gridViewC;
View view;

public NewsFeeds() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    context = getActivity();

    view = inflater.inflate(R.layout.fragment_news_feeds2,container, false);

    return view;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    final FragmentActivity fragmentActivity = getActivity();
    layoutManager = new LinearLayoutManager(fragmentActivity);

    recyclerView =  view.findViewById(R.id.recyclerView);

    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    progressDialog = new ProgressDialog(getActivity());

    progressDialog.setMessage("Loading Images From Firebase.");

     progressDialog.show();

    databaseReference = FirebaseDatabase.getInstance().getReference(Main2Activity.FB_Database_Path);

    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {

            for (DataSnapshot postSnapshot : snapshot.getChildren()) {

                ImageUploadInfo imageUploadInfo = postSnapshot.getValue(ImageUploadInfo.class);

                list.add(imageUploadInfo);
            }

            adapter = new RecyclerViewAdapter(getContext(), list);

            recyclerView.setAdapter(adapter);
            recyclerView.setHasFixedSize(true);

            progressDialog.dismiss();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

                          progressDialog.dismiss();

        }
    });

}

}


问:
Kotlin explain me about Backing Fields
I have been looking at Kotlin official tutorial. I came across the topic called Backing Fields

It says,

Classes in Kotlin cannot have fields. However, sometimes it is necessary to have a backing field when using custom accessors. For these purposes, Kotlin provides an automatic backing field which can be accessed using the field identifier:

```<code>var counter = 0 // the initializer value is written directly to the backing field
    set(value) {
        if (value >= 0) field = value
    }
</code>```

I got the above from this official link

My question is, is the "field" pointing to counter variable ?

Can someone please provide me an example for the backing field or describe me in an understanding word ?

答:
Consider this class

```<code>class SomeClass {
    var counter: Int = 0
        set(value) {
            if (value >= 0) field = value
        }
}
</code>```

In Android Studio go to Main menu -> Tools -> Kotlin -> Show Kotlin Bytecode and click Decompile in the Kotlin bytecode panel.

What you see is the equivalent code in Java.

```<code>public final class SomeClass {
   private int counter;

   public final int getCounter() {
      return this.counter;
   }

   public final void setCounter(int value) {
      if(value >= 0) {
         this.counter = value;
      }
   }
}
</code>```

Title: Kotlin explain me about Backing Fields

Body:
I have been looking at Kotlin official tutorial. I came across the topic called Backing Fields

It says,

Classes in Kotlin cannot have fields. However, sometimes it is necessary to have a backing field when using custom accessors. For these purposes, Kotlin provides an automatic backing field which can be accessed using the field identifier:

var counter = 0 // the initializer value is written directly to the backing field
    set(value) {
        if (value >= 0) field = value
    }

I got the above from this official link

My question is, is the "field" pointing to counter variable ?

Can someone please provide me an example for the backing field or describe me in an understanding word ?

Body:
Consider this class

class SomeClass {
    var counter: Int = 0
        set(value) {
            if (value >= 0) field = value
        }
}

In Android Studio go to Main menu -> Tools -> Kotlin -> Show Kotlin Bytecode and click Decompile in the Kotlin bytecode panel.

What you see is the equivalent code in Java.

public final class SomeClass {
   private int counter;

   public final int getCounter() {
      return this.counter;
   }

   public final void setCounter(int value) {
      if(value >= 0) {
         this.counter = value;
      }
   }
}


问:
How to disambiguate a plpgsql variable name in a ON CONFLICT clause?
Given this table:

```<code>create table test (
    name text primary key
);
</code>```

I need to write a plpgsql function with a variable name that collides with the primary key name, which I must use in a on conflict clause:

```<code>create or replace function func(
    name text                               -- this variable name...
) returns void language plpgsql as
$$
begin
    insert into test (name) values (name)
    on conflict (name) do update            -- ...conflicts with this line
    set name = func.name;
end;
$$;
</code>```

This compiles, but then throws an ambiguous column reference:

```<code>select * from func('one');
ERROR:  column reference "name" is ambiguous
LINE 2:     on conflict (name) do update
                        ^
DETAIL:  It could refer to either a PL/pgSQL variable or a table column.
QUERY:  insert into test (name) values (name)
    on conflict (name) do update
    set name = func.name
CONTEXT:  PL/pgSQL function func(text) line 3 at SQL statement
</code>```

I tried specifying the full column name as on conflict (test.name) which does not compile, or ((test.name)) which compiles:

```<code>create or replace function func(
    name text
) returns void language plpgsql as
$$
begin
    insert into test (name) values (name)
    on conflict ((test.name)) do            -- this fails too
    update set name = func.name;
end;
$$;
</code>```

But it fails as well:

```<code>select * from func('two');
ERROR:  invalid reference to FROM-clause entry for table "test"
LINE 2:     on conflict ((test.name)) do
                          ^
HINT:  There is an entry for table "test", but it cannot be referenced from this part of the query.
QUERY:  insert into test (name) values (name)
    on conflict ((test.name)) do
    update set name = func.name
CONTEXT:  PL/pgSQL function func(text) line 3 at SQL statement
</code>```

Is there a solution?

Edit: I found a workaround:

```<code>on conflict on constraint test_pkey do update
</code>```

where test_pkey is the table name plus _pkey. I don't know how reliable this is though. I'd still like to specify the column name instead.

答:
The ON CONFLICT... syntax (as documented here) uses a unique constraint to determine if the row conflicts. You can specify this unique constraint either by listing the columns it contains (at which point Postgres "infers" the correct index to use) or by naming the constraint directly.

In your case, the unique constraint being used is the primary key constraint implicitly created during your CREATE TABLE statement. This will have a name given to it by the DBMS, unless you specify one directly; so you will need to either look up the name the DBMS has given it (and be aware that this may change if you recreate the schema later), or name it explicitly when you create the table using the syntax CONSTRAINT pk_some_name PRIMARY KEY.

You would then specify the clause as ON CONFLICT ON CONSTRAINT pk_some_name DO ... (note no brackets around the constraint name).

(Alternatively, of course, you could change your function to use an unambiguous parameter name; personally, I think it's good practice to use a prefix like p_ or in_ rather than handling conflicts on a case-by-case basis.)

Body:
Given this table:

create table test (
    name text primary key
);

I need to write a plpgsql function with a variable name that collides with the primary key name, which I must use in a on conflict clause:

create or replace function func(
    name text                               -- this variable name...
) returns void language plpgsql as
$$
begin
    insert into test (name) values (name)
    on conflict (name) do update            -- ...conflicts with this line
    set name = func.name;
end;
$$;

This compiles, but then throws an ambiguous column reference:

select * from func('one');
ERROR:  column reference "name" is ambiguous
LINE 2:     on conflict (name) do update
                        ^
DETAIL:  It could refer to either a PL/pgSQL variable or a table column.
QUERY:  insert into test (name) values (name)
    on conflict (name) do update
    set name = func.name
CONTEXT:  PL/pgSQL function func(text) line 3 at SQL statement

I tried specifying the full column name as on conflict (test.name) which does not compile, or ((test.name)) which compiles:

create or replace function func(
    name text
) returns void language plpgsql as
$$
begin
    insert into test (name) values (name)
    on conflict ((test.name)) do            -- this fails too
    update set name = func.name;
end;
$$;

But it fails as well:

select * from func('two');
ERROR:  invalid reference to FROM-clause entry for table "test"
LINE 2:     on conflict ((test.name)) do
                          ^
HINT:  There is an entry for table "test", but it cannot be referenced from this part of the query.
QUERY:  insert into test (name) values (name)
    on conflict ((test.name)) do
    update set name = func.name
CONTEXT:  PL/pgSQL function func(text) line 3 at SQL statement

Is there a solution?

Edit: I found a workaround:

on conflict on constraint test_pkey do update

where test_pkey is the table name plus _pkey. I don't know how reliable this is though. I'd still like to specify the column name instead.


问:
Template equivalence or template functional equivalence?
In the C++ standard [temp.over.link], it is explained that the determination of function template equivalence should not involve "heroic efforts" of the compiler.

As an example, the C++ standard propose this:

```<code>// guaranteed to be the same
template <int I> void f(A<I>, A<I+10>);
template <int I> void f(A<I>, A<I+10>);
// guaranteed to be different
template <int I> void f(A<I>, A<I+10>);
template <int I> void f(A<I>, A<I+11>);
// ill-formed, no diagnostic required
template <int I> void f(A<I>, A<I+10>);
template <int I> void f(A<I>, A<I+1+2+3+4>);
</code>```

Is this rule also applies to cases involving meta programming, as in the example below?

```<code>template<class T>
struct t_{
   using type = T;
   };
//ill-formed or different?
template<class T> T f(T);
template<class T> typename t_<T>::type f(T);
</code>```

答:
Let's start with the simple case:

```<code>template <typename T> using id = T;

template<class T> T f(T);
template<class T> id<T> f(T);
</code>```

This to me is clearly ill-formed, no diagnostic required, per the relevant rule. The two declarations are functionally equivalent, but not in a way that's simply renaming template parameters (and there aren't any dependent names to consider).

With the more complicated case:

```<code>template <typename T> struct id_t { using type = T; };
template <typename T> using id = typename id_t<T>::type;

template<class T> T f(T);
template<class T> id<T> f(T);
</code>```

I think this is probably not ill-formed, because they aren't truly functionally equivalent. There could be specializations of id_t such that these two declarations are actually different - so these are actually different declarations.

Body:
In the C++ standard [temp.over.link], it is explained that the determination of function template equivalence should not involve "heroic efforts" of the compiler.

As an example, the C++ standard propose this:

// guaranteed to be the same
template <int I> void f(A, A);
template <int I> void f(A, A);
// guaranteed to be different
template <int I> void f(A, A);
template <int I> void f(A, A);
// ill-formed, no diagnostic required
template <int I> void f(A, A);
template <int I> void f(A, A);

Is this rule also applies to cases involving meta programming, as in the example below?

template<class T>
struct t_{
   using type = T;
   };
//ill-formed or different?
template<class T> T f(T);
template<class T> typename t_<T>::type f(T);

Body:
Let's start with the simple case:

template <typename T> using id = T;

template<class T> T f(T);
template<class T> id<T> f(T);

This to me is clearly ill-formed, no diagnostic required, per the relevant rule. The two declarations are functionally equivalent, but not in a way that's simply renaming template parameters (and there aren't any dependent names to consider).

With the more complicated case:

template <typename T> struct id_t { using type = T; };
template <typename T> using id = typename id_t<T>::type;

template<class T> T f(T);
template<class T> id<T> f(T);

I think this is probably not ill-formed, because they aren't truly functionally equivalent. There could be specializations of id_t such that these two declarations are actually different - so these are actually different declarations.


问:
Cannot resolve method setText(java.lang.String) in Fragment
I am using the Pedometer to count the steps since the last reboot of a device.

I have created a textView which I want to set the text of to be the number of steps when the sensor is being used. (My TextView is called count)

My code for doing this is:

```<code>@Override
public void onSensorChanged(SensorEvent event) {
    if (activityRunning) {
        count.setText(String.valueOf(event.values[0]));
    }
</code>```

I am getting an error here Cannot resolve method setText(java.lang.String)

I can post the rest of the class if it would help to fix the problem

Thanks

This is the rest of the class:

```<code>public class Tab3 extends Fragment implements SensorEventListener {

private SensorManager sensorManager;
private TextView textView;
boolean activityRunning;
private Button buttonReturn;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.tab3, container, false);

    TextView count = (TextView) getActivity().findViewById(R.id.count);

    sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);

    getActivity().getSystemService(Context.SENSOR_SERVICE);

    return rootView;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

@Override
public void onResume() {
    super.onResume();
    activityRunning = true;
    Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
    if (countSensor != null) {
        sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
    } else {
        Toast.makeText(getActivity(), "Count sensor not available!", Toast.LENGTH_LONG).show();
    }

}

@Override
public void onPause() {
    super.onPause();
    activityRunning = false;
}

@Override
public void onSensorChanged(SensorEvent event) {
    if (activityRunning) {
        count.setText(String.valueOf(event.values[0]));
    }

}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}
}
</code>```

This is the XML file associated with this class:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.application.placepicker.TabbedActivity$PlaceholderFragment">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_marginTop="114dp"
    android:gravity="center"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true">

    <TextView
        android:id="@+id/textLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Step counter"
        android:textSize="40sp"
        android:textColor="@color/colorAccent"
        android:fontFamily="sans-serif"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="33dp"
        android:layout_gravity="center_horizontal"
        android:textSize="26dp"
        android:text="Steps walked so far today:"
        android:textColor="@color/colorAccent" />

    <TextView
        android:id="@+id/count"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_marginLeft="50dp"
        android:text="---"
        android:textColor="@color/colorAccent"
        android:textSize="36dp" />

</LinearLayout>
</code>```

答:
How did you define your "count"?

If we suppose that you has defined the TextView correctly, you will get error in null object,
so it is better to change your code to below:

```<code>   count.setText(""+event.values[0]);
</code>```

Body:
I am using the Pedometer to count the steps since the last reboot of a device.

I have created a textView which I want to set the text of to be the number of steps when the sensor is being used. (My TextView is called count)

My code for doing this is:

@Override
public void onSensorChanged(SensorEvent event) {
    if (activityRunning) {
        count.setText(String.valueOf(event.values[0]));
    }

I am getting an error here Cannot resolve method setText(java.lang.String)

I can post the rest of the class if it would help to fix the problem

Thanks

This is the rest of the class:

public class Tab3 extends Fragment implements SensorEventListener {

private SensorManager sensorManager;
private TextView textView;
boolean activityRunning;
private Button buttonReturn;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.tab3, container, false);

    TextView count = (TextView) getActivity().findViewById(R.id.count);

    sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);

    getActivity().getSystemService(Context.SENSOR_SERVICE);

    return rootView;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

@Override
public void onResume() {
    super.onResume();
    activityRunning = true;
    Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
    if (countSensor != null) {
        sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
    } else {
        Toast.makeText(getActivity(), "Count sensor not available!", Toast.LENGTH_LONG).show();
    }

}

@Override
public void onPause() {
    super.onPause();
    activityRunning = false;
}

@Override
public void onSensorChanged(SensorEvent event) {
    if (activityRunning) {
        count.setText(String.valueOf(event.values[0]));
    }

}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}
}

This is the XML file associated with this class:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.application.placepicker.TabbedActivity$PlaceholderFragment">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_marginTop="114dp"
    android:gravity="center"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true">

    <TextView
        android:id="@+id/textLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Step counter"
        android:textSize="40sp"
        android:textColor="@color/colorAccent"
        android:fontFamily="sans-serif"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="33dp"
        android:layout_gravity="center_horizontal"
        android:textSize="26dp"
        android:text="Steps walked so far today:"
        android:textColor="@color/colorAccent" />

    <TextView
        android:id="@+id/count"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_marginLeft="50dp"
        android:text="---"
        android:textColor="@color/colorAccent"
        android:textSize="36dp" />

</LinearLayout>

Body:
How did you define your "count"?

If we suppose that you has defined the TextView correctly, you will get error in null object,
so it is better to change your code to below:

   count.setText(""+event.values[0]);


问:
Laravel Eloquent hasMany filtered by parent table
In my system there are users, each of which has holiday allowances each year.

There are 3 tables (simplified):

users

- id

- name

user_leave_allowances

- id

- user_id

- from

- to

- allowance

user_leave

- id

- user_id

- from

- to

- days

In the UserLeaveAllowance model I have set up the following relationship:

```<code>public function leave(){
    return $this->hasMany('App\UserLeave','user_id','user_id');
}
</code>```

And retrieving the leave allowance by the following:

```<code>$leaveAllowance = UserLeaveAllowance::with(['leave'])
->where('user_id',$id)
->get()
</code>```

This pulls in the full list of leave allowances (user_leave_allowances) for that user along with all the leave they have currently requested (user_leave).

However, the allowances will be for different periods of time, e.g. 1/1/2017 - 31/12/2017 and leave will be taken out of these periods. So for each leave allowance period I want just the leave that falls within those two dates (from & to), at the moment it just pulls through all the leave for that user into each leave allowance.

I have tried many different ways around it, using the where conditions on the hasMany as such...

```<code>public function used(){
    return $this->hasMany('App\UserLeave','user_id','user_id')
->where('from', '>=', 'user_leave_allowances.from')
->where('to', '<=', 'user_leave_allowances.to');
}
</code>```

and

```<code>public function used(){
    return $this->hasMany('App\UserLeave','user_id','user_id')
->whereRaw('user_leave.from >= user_leave_allowances.from')
->whereRaw('user_leave.to <= user_leave_allowances.to');
}
</code>```

But I just can't figure out a way to get this to work. I'm fairly new to Laravel and trying to get to grips with Eloqent and relationships, I'm sure the answer isn't too far away.

答:
Here's my suggestion:

users
- id
- name

user_leave_allowances
- id
- user_id
- from
- to

user_leave
- id
- user_leave_allowances_id
- from
- to

In short relate your leave with your leave allowances rather than the user directly because in essence a leave request is taken out of the allowance not out of the user directly.

```<code>class User extends Model {
     public leaveAllowance() {
         return $this->hasMany(UserLeaveAllowance::class);
     }
}

class UserLeaveAllowance {
      public user() { return $this->belongsTo(User::class); }
      public leaveRequests() {
        return $this->hasMany(UserLeave::class);
      }
}

class UserLeave {
      public allowancePeriod() {
        return $this->belongsTo(UserLeaveAllowance::class);
      }
}
</code>```

Now you can do things like:

```<code>UserLeaveAllowance::whereHas("user", function ($q) {
        return $q->where("id", <user id>); //Allowances for this user
})->leaveRequests()
->selectRaw("SUM(TIMESTAMPDIFF(DAY, to, from)) as days")
->value("days");
</code>```

Body:
In my system there are users, each of which has holiday allowances each year.

There are 3 tables (simplified):

users

- id

- name

user_leave_allowances

- id

- user_id

- from

- to

- allowance

user_leave

- id

- user_id

- from

- to

- days

In the UserLeaveAllowance model I have set up the following relationship:

public function leave(){
    return $this->hasMany('App\UserLeave','user_id','user_id');
}

And retrieving the leave allowance by the following:

$leaveAllowance = UserLeaveAllowance::with(['leave'])
->where('user_id',$id)
->get()

This pulls in the full list of leave allowances (user_leave_allowances) for that user along with all the leave they have currently requested (user_leave).

However, the allowances will be for different periods of time, e.g. 1/1/2017 - 31/12/2017 and leave will be taken out of these periods. So for each leave allowance period I want just the leave that falls within those two dates (from & to), at the moment it just pulls through all the leave for that user into each leave allowance.

I have tried many different ways around it, using the where conditions on the hasMany as such...

public function used(){
    return $this->hasMany('App\UserLeave','user_id','user_id')
->where('from', '>=', 'user_leave_allowances.from')
->where('to', '<=', 'user_leave_allowances.to');
}

and

public function used(){
    return $this->hasMany('App\UserLeave','user_id','user_id')
->whereRaw('user_leave.from >= user_leave_allowances.from')
->whereRaw('user_leave.to <= user_leave_allowances.to');
}

But I just can't figure out a way to get this to work. I'm fairly new to Laravel and trying to get to grips with Eloqent and relationships, I'm sure the answer isn't too far away.

Body:
Here's my suggestion:

users
- id
- name

user_leave_allowances
- id
- user_id
- from
- to

user_leave
- id
- user_leave_allowances_id
- from
- to

In short relate your leave with your leave allowances rather than the user directly because in essence a leave request is taken out of the allowance not out of the user directly.

class User extends Model {
     public leaveAllowance() {
         return $this->hasMany(UserLeaveAllowance::class);
     }
}

class UserLeaveAllowance {
      public user() { return $this->belongsTo(User::class); }
      public leaveRequests() {
        return $this->hasMany(UserLeave::class);
      }
}

class UserLeave {
      public allowancePeriod() {
        return $this->belongsTo(UserLeaveAllowance::class);
      }
}

Now you can do things like:

UserLeaveAllowance::whereHas("user", function ($q) {
        return $q->where("id", <user id>); //Allowances for this user
})->leaveRequests()
->selectRaw("SUM(TIMESTAMPDIFF(DAY, to, from)) as days")
->value("days");


问:
Adding Photos to Array and Displaying to UICollection View error
QUESTION

This code works to set an image to an array but comes up with the following error - 2017-12-06 12:31:21.264812+0000 SmartReceipts[880:172369] [discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}

I need to know what this means and if there is a possible fix around it?

```<code>import UIKit

class GalleryController: UICollectionViewController,
                         UIImagePickerControllerDelegate,
                         UINavigationControllerDelegate {

    var Receipts = [UIImage?]()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView?.reloadData()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        //self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        self.dismiss(animated: true, completion: nil)
        print(info);
        let newReceipts = info[UIImagePickerControllerEditedImage] as? UIImage
        self.Receipts.append(newReceipts)

        print("Array Contains \(self.Receipts.count) Receipts")
        print(self.Receipts)
        self.collectionView?.reloadData()

        print("completedIfStatement")
        }

    @IBAction func getReceipts(_ sender: Any) {
        print("PlusButtonPressed")

        let optionMenu = UIAlertController(title: nil, message: "Choose Option", preferredStyle: .actionSheet)

        // 2
        let albumAction = UIAlertAction(title: "Album", style: .default, handler: {
            (alert: UIAlertAction!) -> Void in
            print("PhotosOption")
            self.getFromReceipts()
        })
        let cameraAction = UIAlertAction(title: "Camera", style: .default, handler: {
            (alert: UIAlertAction!) -> Void in
            print("CameraOption")
            self.getFromCamera()
        })

        //
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
            (alert: UIAlertAction!) -> Void in
            print("Cancel")
        })

        // 4
        optionMenu.addAction(albumAction)
        optionMenu.addAction(cameraAction)
        optionMenu.addAction(cancelAction)

        // 5
        self.present(optionMenu, animated: true, completion: nil)

    }

    func getFromReceipts() {

        print("GetFromReceipts")
        let cameraPicker = UIImagePickerController()
        cameraPicker.delegate = self
        cameraPicker.sourceType = .photoLibrary

        self.present(cameraPicker, animated: true, completion: nil )

    }

    func getFromCamera() {
        print("GetFromCamera")
        let cameraPicker = UIImagePickerController()
        cameraPicker.delegate = self
        cameraPicker.sourceType = .camera

        self.present(cameraPicker, animated: true, completion: nil )

    }

    //Number of Views
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.Receipts.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtindexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Receipts, for: indexPath as IndexPath) as? PhotoCell

        cell?.imageView.image = self.Receipts[indexPath.row]
        return cell!

    }

}
</code>```

答:
I guess you'r not requesting Photo/Camera authorizations.
You have to add the below keys to Info.plist.

Camera permission :

```<code><key>NSCameraUsageDescription</key>
<string> ${PRODUCT_NAME} Camera Usage< </string>
</code>```

For Photo Library, you will want this one to allow app user to browse the photo library.

```<code><key>NSPhotoLibraryUsageDescription</key>
<string>${PRODUCT_NAME} Photo Usage</string>
</code>```

And in you'r source code, to ask permission for the photo/camera you need to add this code (Swift 3):

```<code>PHPhotoLibrary.requestAuthorization({
       (newStatus) in
         if newStatus ==  PHAuthorizationStatus.authorized {
          /* do stuff here */
    }
})
</code>```

Body:
QUESTION

This code works to set an image to an array but comes up with the following error - 2017-12-06 12:31:21.264812+0000 SmartReceipts[880:172369] [discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}

I need to know what this means and if there is a possible fix around it?

import UIKit

class GalleryController: UICollectionViewController,
                         UIImagePickerControllerDelegate,
                         UINavigationControllerDelegate {

    var Receipts = [UIImage?]()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView?.reloadData()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        //self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        self.dismiss(animated: true, completion: nil)
        print(info);
        let newReceipts = info[UIImagePickerControllerEditedImage] as? UIImage
        self.Receipts.append(newReceipts)

        print("Array Contains \(self.Receipts.count) Receipts")
        print(self.Receipts)
        self.collectionView?.reloadData()

        print("completedIfStatement")
        }

    @IBAction func getReceipts(_ sender: Any) {
        print("PlusButtonPressed")

        let optionMenu = UIAlertController(title: nil, message: "Choose Option", preferredStyle: .actionSheet)

        // 2
        let albumAction = UIAlertAction(title: "Album", style: .default, handler: {
            (alert: UIAlertAction!) -> Void in
            print("PhotosOption")
            self.getFromReceipts()
        })
        let cameraAction = UIAlertAction(title: "Camera", style: .default, handler: {
            (alert: UIAlertAction!) -> Void in
            print("CameraOption")
            self.getFromCamera()
        })

        //
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
            (alert: UIAlertAction!) -> Void in
            print("Cancel")
        })

        // 4
        optionMenu.addAction(albumAction)
        optionMenu.addAction(cameraAction)
        optionMenu.addAction(cancelAction)

        // 5
        self.present(optionMenu, animated: true, completion: nil)

    }

    func getFromReceipts() {

        print("GetFromReceipts")
        let cameraPicker = UIImagePickerController()
        cameraPicker.delegate = self
        cameraPicker.sourceType = .photoLibrary

        self.present(cameraPicker, animated: true, completion: nil )

    }

    func getFromCamera() {
        print("GetFromCamera")
        let cameraPicker = UIImagePickerController()
        cameraPicker.delegate = self
        cameraPicker.sourceType = .camera

        self.present(cameraPicker, animated: true, completion: nil )

    }

    //Number of Views
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.Receipts.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtindexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Receipts, for: indexPath as IndexPath) as? PhotoCell

        cell?.imageView.image = self.Receipts[indexPath.row]
        return cell!

    }

}

Body:
I guess you'r not requesting Photo/Camera authorizations.
You have to add the below keys to Info.plist.

Camera permission :

<key>NSCameraUsageDescription</key>
<string> ${PRODUCT_NAME} Camera Usage< </string>

For Photo Library, you will want this one to allow app user to browse the photo library.

<key>NSPhotoLibraryUsageDescription</key>
<string>${PRODUCT_NAME} Photo Usage</string>

And in you'r source code, to ask permission for the photo/camera you need to add this code (Swift 3):

PHPhotoLibrary.requestAuthorization({
       (newStatus) in
         if newStatus ==  PHAuthorizationStatus.authorized {
          /* do stuff here */
    }
})


问:
When to use ViewModel or Partial View
Should I use view model or partial view? Or when is it advantageous to use one over the other? In my particular case I am going to be submitting data to the server or using an http post.</p>

答:
These are different things. View Model is something similar to a parameter to some function. And Partial View is something like a body of a function called from other function. So you can pass some view model to a partial view while creating a request result at a response to submitting data to your server on http post.

You might find helpful this tutorial to better understand this - https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/adding-a-view

ContentLicense: CC BY-SA 4.0

Title: When to use ViewModel or Partial View


问:
C99 boolean data type?
What's the C99 boolean data type and how to use it?</p>

答:
Please do check out the answer here on this related thread found on DaniWeb.

extracted and quoted here for convenient reference:-

usage of new keywords in c99

_Bool: C99's boolean type. Using _Bool directly is only recommended if you're
  maintaining legacy code that already
  defines macros for bool, true, or
  false. Otherwise, those macros are
  standardized in the <stdbool.h>
  header. Include that header and you
  can use bool just like you would in
  C++.

```<code>#include <stdio.h>
#include <stdbool.h>

int main ( void )
{
  bool b = true;

  if ( b )
    printf ( "Yes\n" );
  else
    printf ( "No\n" );

  return 0;
}
</code>```

Title: C99 boolean data type?

Body:
Please do check out the answer here on this related thread found on DaniWeb.

extracted and quoted here for convenient reference:-

usage of new keywords in c99

_Bool: C99's boolean type. Using _Bool directly is only recommended if you're
  maintaining legacy code that already
  defines macros for bool, true, or
  false. Otherwise, those macros are
  standardized in the <stdbool.h>
  header. Include that header and you
  can use bool just like you would in
  C++.

#include <stdio.h>
#include <stdbool.h>

int main ( void )
{
  bool b = true;

  if ( b )
    printf ( "Yes\n" );
  else
    printf ( "No\n" );

  return 0;
}


问:
Looping in a spiral
A friend was in need of an algorithm that would let him loop through the elements of an NxM matrix (N and M are odd). I came up with a solution, but I wanted to see if my fellow SO'ers could come up with a better solution.

I'm posting my solution as an answer to this question.

Example Output:

For a 3x3 matrix, the output should be:

(0, 0)
(1, 0)
(1, 1)
(0, 1)
(-1, 1)
(-1, 0)
(-1, -1)
(0, -1)
(1, -1)

Furthermore, the algorithm should support non-square matrices, so for example for a 5x3 matrix, the output should be:

(0, 0)
(1, 0)
(1, 1)
(0, 1)
(-1, 1)
(-1, 0)
(-1, -1)
(0, -1)
(1, -1)
(2, -1)
(2, 0)
(2, 1)
(-2, 1)
(-2, 0)
(-2, -1)

答:
Here's an answer in Julia: my approach is to assign the points in concentric squares ('spirals') around the origin (0,0), where each square has side length m = 2n + 1, to produce an ordered dictionary with location numbers (starting from 1 for the origin) as keys and the corresponding coordinate as value.

Since the maximum location per spiral is at (n,-n), the rest of the points can be found by simply working backward from this point, i.e. from the bottom right corner by m-1 units, then repeating for the perpendicular 3 segments of m-1 units.

This process is written in reverse order below, corresponding to how the spiral proceeds rather than this reverse counting process, i.e. the ra [right ascending] segment is decremented by 3(m+1), then la [left ascending] by 2(m+1), and so on - hopefully this is self-explanatory.

import DataStructures: OrderedDict, merge

function spiral(loc::Int)
    s = sqrt(loc-1) |> floor |> Int
    if s % 2 == 0
        s -= 1
    end
    s = (s+1)/2 |> Int
    return s
end

function perimeter(n::Int)
    n > 0 || return OrderedDict([1,[0,0]])
    m = 2n + 1 # width/height of the spiral [square] indexed by n
    # loc_max = m^2
    # loc_min = (2n-1)^2 + 1
    ra = [[m^2-(y+3m-3), [n,n-y]] for y in (m-2):-1:0]
    la = [[m^2-(y+2m-2), [y-n,n]] for y in (m-2):-1:0]
    ld = [[m^2-(y+m-1), [-n,y-n]] for y in (m-2):-1:0]
    rd = [[m^2-y, [n-y,-n]] for y in (m-2):-1:0]
    return OrderedDict(vcat(ra,la,ld,rd))
end

function walk(n)
    cds = OrderedDict(1 => [0,0])
    n > 0 || return cds
    for i in 1:n
        cds = merge(cds, perimeter(i))
    end
    return cds
end
```

<p>So for your first example, plugging <code>m = 3</code> into the equation to find n gives <code>n = (5-1)/2 = 2</code>, and <code>walk(2)</code> gives an ordered dictionary of locations to coordinates, which you can turn into just an array of coordinates by accessing the dictionary's <code>vals</code> field:</p>

<pre class="lang-julia prettyprint-override"><code>walk(2)
DataStructures.OrderedDict{Any,Any} with 25 entries:
  1  => [0,0]
  2  => [1,0]
  3  => [1,1]
  4  => [0,1]
  ⋮  => ⋮

[(co[1],co[2]) for co in walk(2).vals]
25-element Array{Tuple{Int64,Int64},1}:
 (0,0)
 (1,0)
 ⋮
 (1,-2)
 (2,-2)
</code>```

Note that for some functions [e.g. norm] it can be preferable to leave the coordinates in arrays rather than Tuple{Int,Int}, but here I change them into tuples—(x,y)—as requested, using list comprehension.

The context for "supporting" a non-square matrix isn't specified (note that this solution still calculates the off-grid values), but if you want to filter to only the range x by y (here for x=5,y=3) after calculating the full spiral then intersect this matrix against the values from walk.

grid = [[x,y] for x in -2:2, y in -1:1]
5×3 Array{Array{Int64,1},2}:
 [-2,-1]  [-2,0]  [-2,1]
   ⋮       ⋮       ⋮
 [2,-1]   [2,0]   [2,1]

[(co[1],co[2]) for co in intersect(walk(2).vals, grid)]
15-element Array{Tuple{Int64,Int64},1}:
 (0,0)
 (1,0)
 ⋮
 (-2,0)
 (-2,-1)
```

OwnerDisplayName: Can Berk Güder

Title: Looping in a spiral

Body:
Here's an answer in Julia: my approach is to assign the points in concentric squares ('spirals') around the origin (0,0), where each square has side length m = 2n + 1, to produce an ordered dictionary with location numbers (starting from 1 for the origin) as keys and the corresponding coordinate as value.

Since the maximum location per spiral is at (n,-n), the rest of the points can be found by simply working backward from this point, i.e. from the bottom right corner by m-1 units, then repeating for the perpendicular 3 segments of m-1 units.

This process is written in reverse order below, corresponding to how the spiral proceeds rather than this reverse counting process, i.e. the ra [right ascending] segment is decremented by 3(m+1), then la [left ascending] by 2(m+1), and so on - hopefully this is self-explanatory.

import DataStructures: OrderedDict, merge

function spiral(loc::Int)
    s = sqrt(loc-1) |> floor |> Int
    if s % 2 == 0
        s -= 1
    end
    s = (s+1)/2 |> Int
    return s
end

function perimeter(n::Int)
    n > 0 || return OrderedDict([1,[0,0]])
    m = 2n + 1 # width/height of the spiral [square] indexed by n
    # loc_max = m^2
    # loc_min = (2n-1)^2 + 1
    ra = [[m^2-(y+3m-3), [n,n-y]] for y in (m-2):-1:0]
    la = [[m^2-(y+2m-2), [y-n,n]] for y in (m-2):-1:0]
    ld = [[m^2-(y+m-1), [-n,y-n]] for y in (m-2):-1:0]
    rd = [[m^2-y, [n-y,-n]] for y in (m-2):-1:0]
    return OrderedDict(vcat(ra,la,ld,rd))
end

function walk(n)
    cds = OrderedDict(1 => [0,0])
    n > 0 || return cds
    for i in 1:n
        cds = merge(cds, perimeter(i))
    end
    return cds
end

So for your first example, plugging m = 3 into the equation to find n gives n = (5-1)/2 = 2, and walk(2) gives an ordered dictionary of locations to coordinates, which you can turn into just an array of coordinates by accessing the dictionary's vals field:

walk(2)
DataStructures.OrderedDict{Any,Any} with 25 entries:
  1  => [0,0]
  2  => [1,0]
  3  => [1,1]
  4  => [0,1]
  ⋮  => ⋮

[(co[1],co[2]) for co in walk(2).vals]
25-element Array{Tuple{Int64,Int64},1}:
 (0,0)
 (1,0)
 ⋮
 (1,-2)
 (2,-2)

Note that for some functions [e.g. norm] it can be preferable to leave the coordinates in arrays rather than Tuple{Int,Int}, but here I change them into tuples—(x,y)—as requested, using list comprehension.

The context for "supporting" a non-square matrix isn't specified (note that this solution still calculates the off-grid values), but if you want to filter to only the range x by y (here for x=5,y=3) after calculating the full spiral then intersect this matrix against the values from walk.

grid = [[x,y] for x in -2:2, y in -1:1]
5×3 Array{Array{Int64,1},2}:
 [-2,-1]  [-2,0]  [-2,1]
   ⋮       ⋮       ⋮
 [2,-1]   [2,0]   [2,1]

[(co[1],co[2]) for co in intersect(walk(2).vals, grid)]
15-element Array{Tuple{Int64,Int64},1}:
 (0,0)
 (1,0)
 ⋮
 (-2,0)
 (-2,-1)


问:
Hover effect with drop down menu doesn't cover desired elements

I'm trying to make a simple drop down side menu by making use of sibling elements and applying the hide/show effect on hover by the adjacent selector (+). It works almost flawlessly except for one annoying detail: the hover is supposed to be applied to both siblings, but there seems to be an empty void between them so that when the cursor leaves the first element it hides the other sibling back because it's not hovering any of them anymore.

JSFiddle example

HTML:

```<code><div class="dropdown">
  <h1>Title 1</h1>
  <a>Item 1</a>
  <h1>Title 2</h1>
  <p>Item 2</p>
  <h1>Title 3</h1>
  <ul>
    <li>Item 3.1</li>
    <li>Item 3.2</li>
    <li>Item 3.3</li>
  </ul>
</div>
</code>```

CSS:

```<code>.dropdown {
    text-align: left;
    color: #00F;
    background-color: transparent;
}
h1 {
    display: inline-block;
    border-top: 1px solid #000;
    width: 290px !important;
    color: #F00;
    font-weight: 500;
    border-left: 0;
    padding-left: 0;
    margin-left: 0;
    padding-top: 13px;
    line-height: 30px !important;
}
h1 a,
h1 a:visited {
    color: #FFFDFD;
}
h1:nth-of-type(1) + * {
    display: block;
}
h1 + * {
    display: none;
}
h1:hover + *,
h1 + *:hover {
    display: block;
}
</code>```

I know I could just wrap them into a parent-child relationship, but within the scope I'm working on this is not possible. Another workaround could be that instead of setting display:none to hide and then display:block to show them on hover, I could set a max-height to 0 and then set something like max-height to whatever size and in order to escape the void between the siblings, I just needed to set a transition effect of .5s or even 1s long so that the user has enough time to put his cursor on the second sibling before it hides back, but the main problem with it is that chances are that there might be a table as one of the hidden elements and as we know it's not possible to set height to a table so it would never be hidden.

答:
https://jsfiddle.net/Liamm12/78dyfjw4/1/

Hello there!
I just changed the

```<code>h1:nth-of-type(1) + * {
    display: block;
}
</code>```

To

```<code>h1:nth-of-type(0) + * {
    display: block;
}
</code>```

here's the full code

HTML:

```<code><div class="dropdown">
  <h1>Title 1</h1>
  <ul>
    <li>Item 1.1</li>
    <li>Item 2.2</li>
    <li>Item 3.3</li>
  </ul>
  <h1>Title 2</h1>
  <ul>
    <li>Item 2.1</li>
    <li>Item 2.2</li>
    <li>Item 2.3</li>
  </ul>
  <h1>Title 3</h1>
  <ul>
    <li>Item 3.1</li>
    <li>Item 3.2</li>
    <li>Item 3.3</li>
  </ul>
</div>
</code>```

CSS:

```<code>.dropdown {
    text-align: left;
    color: #00F;
    background-color: transparent;
}
h1 {
    display: inline-block;
    border-top: 1px solid #000;
    width: 290px !important;
    color: #F00;
    font-weight: 500;
    border-left: 0;
    padding-left: 0;
    margin-left: 0;
    padding-top: 13px;
    line-height: 30px !important;
}
h1 a,
h1 a:visited {
    color: #FFFDFD;
}
h1:nth-of-type(0) + * {
    display: block;
}
h1 + * {
    display: none;
}
h1:hover + *,
h1 + *:hover {
    display: block;
}
</code>```

Body:
I'm trying to make a simple drop down side menu by making use of sibling elements and applying the hide/show effect on hover by the adjacent selector (+). It works almost flawlessly except for one annoying detail: the hover is supposed to be applied to both siblings, but there seems to be an empty void between them so that when the cursor leaves the first element it hides the other sibling back because it's not hovering any of them anymore.

JSFiddle example

HTML:

Title 1

  Item 1

Title 2

Item 2

Title 3

Item 3.1

Item 3.2

Item 3.3

CSS:

.dropdown {
    text-align: left;
    color: #00F;
    background-color: transparent;
}
h1 {
    display: inline-block;
    border-top: 1px solid #000;
    width: 290px !important;
    color: #F00;
    font-weight: 500;
    border-left: 0;
    padding-left: 0;
    margin-left: 0;
    padding-top: 13px;
    line-height: 30px !important;
}
h1 a,
h1 a:visited {
    color: #FFFDFD;
}
h1:nth-of-type(1) + * {
    display: block;
}
h1 + * {
    display: none;
}
h1:hover + *,
h1 + *:hover {
    display: block;
}

I know I could just wrap them into a parent-child relationship, but within the scope I'm working on this is not possible. Another workaround could be that instead of setting display:none to hide and then display:block to show them on hover, I could set a max-height to 0 and then set something like max-height to whatever size and in order to escape the void between the siblings, I just needed to set a transition effect of .5s or even 1s long so that the user has enough time to put his cursor on the second sibling before it hides back, but the main problem with it is that chances are that there might be a table as one of the hidden elements and as we know it's not possible to set height to a table so it would never be hidden.

Body:
https://jsfiddle.net/Liamm12/78dyfjw4/1/

Hello there!
I just changed the

h1:nth-of-type(1) + * {
    display: block;
}

To

h1:nth-of-type(0) + * {
    display: block;
}

here's the full code

HTML:

<div class="dropdown">
  <h1>Title 1</h1>
  <ul>
    <li>Item 1.1</li>
    <li>Item 2.2</li>
    <li>Item 3.3</li>
  </ul>
  <h1>Title 2</h1>
  <ul>
    <li>Item 2.1</li>
    <li>Item 2.2</li>
    <li>Item 2.3</li>
  </ul>
  <h1>Title 3</h1>
  <ul>
    <li>Item 3.1</li>
    <li>Item 3.2</li>
    <li>Item 3.3</li>
  </ul>
</div>

CSS:

.dropdown {
    text-align: left;
    color: #00F;
    background-color: transparent;
}
h1 {
    display: inline-block;
    border-top: 1px solid #000;
    width: 290px !important;
    color: #F00;
    font-weight: 500;
    border-left: 0;
    padding-left: 0;
    margin-left: 0;
    padding-top: 13px;
    line-height: 30px !important;
}
h1 a,
h1 a:visited {
    color: #FFFDFD;
}
h1:nth-of-type(0) + * {
    display: block;
}
h1 + * {
    display: none;
}
h1:hover + *,
h1 + *:hover {
    display: block;
}