text:
/////////////////////////////////////////////////////////////////////////////
// Name:        socket.h
// Purpose:     interface of wxIP*address, wxSocket* classes
// Author:      wxWidgets team
// Licence:     wxWindows licence
/////////////////////////////////////////////////////////////////////////////

/**
    The type of the native socket.

    Notice that the definition below is simplified and this type is not always
    int, e.g. it is a 64 bit integer type under Win64.

    @since 2.9.5
  */
typedef int wxSOCKET_T;
/**
    @class wxIPaddress

    wxIPaddress is an abstract base class for all internet protocol address
    objects. Currently, only wxIPV4address is implemented. An experimental
    implementation for IPV6, wxIPV6address, is being developed.

    @library{wxnet}
    @category{net}
*/
class wxIPaddress : public wxSockAddress
{
public:
    /**
        Internally, this is the same as setting the IP address to @b INADDR_ANY.

        On IPV4 implementations, 0.0.0.0

        On IPV6 implementations, ::

        @return @true on success, @false if something went wrong.
    */
  bool AnyAddress();
    /**
        Internally, this is the same as setting the IP address to @b INADDR_BROADCAST.

        On IPV4 implementations, 255.255.255.255

        @return @true on success, @false if something went wrong.
    */
  virtual bool BroadcastAddress() = 0;
    /**
        Set the address to hostname, which can be a host name or an IP-style address
        in a format dependent on implementation.

        @return @true on success, @false if something goes wrong (invalid
                hostname or invalid IP address).
    */
  bool Hostname(const wxString& hostname);
    /**
        Returns the hostname which matches the IP address.
    */
  wxString Hostname() const;
    /**
        Returns a wxString containing the IP address.
    */
  virtual wxString IPAddress() const = 0;
    /**
        Determines if current address is set to localhost.

        @return @true if address is localhost, @false if internet address.
    */
  virtual bool IsLocalHost() const = 0;
    /**
        Set address to localhost.

        On IPV4 implementations, 127.0.0.1

        On IPV6 implementations, ::1

        @return @true on success, @false if something went wrong.
    */
  bool LocalHost();
    /**
        Set the port to that corresponding to the specified service.

        @return @true on success, @false if something goes wrong (invalid @a service).
    */
  bool Service(const wxString& service);
    /**
        Set the port to that corresponding to the specified service.

        @return @true on success, @false if something goes wrong (invalid @a service).
    */
  bool Service(unsigned short service);
    /**
        Returns the current service.
    */
  unsigned short Service() const;
};
/**
    @class wxIPV4address

    A class for working with IPv4 network addresses.

    @library{wxnet}
    @category{net}
*/
class wxIPV4address : public wxIPaddress
{
public:
    /**
        Set address to any of the addresses of the current machine.

        Whenever possible, use this function instead of LocalHost(),
        as this correctly handles multi-homed hosts and avoids other small
        problems. Internally, this is the same as setting the IP address
        to @b INADDR_ANY.

        @return @true on success, @false if something went wrong.
    */
  bool AnyAddress();
    /**
        Set the address to hostname, which can be a host name or an IP-style address
        in dot notation(<tt>a.b.c.d</tt>).

        @return @true on success, @false if something goes wrong (invalid
                hostname or invalid IP address).
    */
  bool Hostname(const wxString& hostname);
    /**
        Returns the hostname which matches the IP address.
    */
  virtual wxString Hostname() const;
    /**
        Returns a wxString containing the IP address in dot quad (127.0.0.1) format.
    */
  virtual wxString IPAddress() const;
    /**
        Set address to localhost (127.0.0.1).

        Whenever possible, use AnyAddress() instead of this one, as that one will
        correctly handle multi-homed hosts and avoid other small problems.

        @return @true on success, @false if something went wrong.
    */
  bool LocalHost();
    /**
        Set the port to that corresponding to the specified @a service.

        @return @true on success, @false if something goes wrong (invalid @a service).
    */
  bool Service(const wxString& service);
    /**
        Set the port to that corresponding to the specified @a service.

        @return @true on success, @false if something goes wrong (invalid @a service).
    */
  bool Service(unsigned short service);
    /**
        Returns the current service.
    */
  unsigned short Service() const;
};
/**
    @class wxSocketServer

    @todo describe me.

    @library{wxnet}
    @category{net}
*/
class wxSocketServer : public wxSocketBase
{
public:
    /**
        Constructs a new server and tries to bind to the specified @e address.

        Before trying to accept new connections, remember to test whether it succeeded
        with wxSocketBase:IsOk().

        @param address
            Specifies the local address for the server (e.g. port number).
        @param flags
            Socket flags (See wxSocketBase::SetFlags()).
    */
  wxSocketServer(const wxSockAddress& address, wxSocketFlags flags = wxSOCKET_NONE);
    /**
        Destructor (it doesn't close the accepted connections).
    */
  virtual ~wxSocketServer();
    /**
        Accepts an incoming connection request, and creates a new wxSocketBase
        object which represents the server-side of the connection.

        If @a wait is @true and there are no pending connections to be
        accepted, it will wait for the next incoming connection to
        arrive.

        @warning This method will block the GUI.

        If @a wait is @false, it will try to accept a pending connection
        if there is one, but it will always return immediately without blocking
        the GUI. If you want to use Accept() in this way, you can either check for
        incoming connections with WaitForAccept() or catch @b wxSOCKET_CONNECTION events,
        then call Accept() once you know that there is an incoming connection waiting
        to be accepted.

        @return Returns an opened socket connection, or @NULL if an error
                occurred or if the wait parameter was @false and there
                were no pending connections.

        @see WaitForAccept(), wxSocketBase::SetNotify(),
             wxSocketBase::Notify(), AcceptWith()
    */
  wxSocketBase* Accept(bool wait = true);
    /**
        Accept an incoming connection using the specified socket object.

        @param socket
            Socket to be initialized
        @param wait
            See Accept() for more info.

        @return Returns @true on success, or @false if an error occurred or
                if the wait parameter was @false and there were no pending
                connections.

        @see WaitForAccept(), wxSocketBase::SetNotify(),
             wxSocketBase::Notify(), Accept()
    */
  bool AcceptWith(wxSocketBase& socket, bool wait = true);
    /**
        Wait for an incoming connection.

        Use it if you want to call Accept() or AcceptWith() with @e wait set
        to @false, to detect when an incoming connection is waiting to be accepted.

        @param seconds
            Number of seconds to wait. If -1, it will wait for the default
            timeout, as set with wxSocketBase::SetTimeout().
        @param millisecond
            Number of milliseconds to wait.

        @return @true if an incoming connection arrived, @false if the timeout
                elapsed.

        @see Accept(), AcceptWith(), wxSocketBase::InterruptWait()
    */
  bool WaitForAccept(long seconds = -1, long millisecond = 0);
};
/**
    @class wxSocketClient

    @todo describe me.

    @library{wxnet}
    @category{net}
*/
class wxSocketClient : public wxSocketBase
{
public:
    /**
        Constructor.

        @param flags
            Socket flags (See wxSocketBase::SetFlags())
    */
  wxSocketClient(wxSocketFlags flags = wxSOCKET_NONE);
    /**
        Destructor. Please see wxSocketBase::Destroy().
    */
  virtual ~wxSocketClient();
    /**
        Connects to a server using the specified address.

        If @a wait is @true, Connect() will wait until the connection
        completes.

        @warning This method will block the GUI.

        If @a wait is @false, Connect() will try to establish the connection
        and return immediately, without blocking the GUI. When used this way,
        even if Connect() returns @false, the connection request can be
        completed later. To detect this, use WaitOnConnect(), or catch
        @b wxSOCKET_CONNECTION events (for successful establishment) and
        @b wxSOCKET_LOST events (for connection failure).

        @param address
            Address of the server.
        @param wait
            If @true, waits for the connection to complete.

        @return @true if the connection is established and no error occurs.
                If @a wait was true, and Connect() returns @false, an error
                occurred and the connection failed.
                If @a wait was @false, and Connect() returns @false, you should
                still be prepared to handle the completion of this connection request,
                either with WaitOnConnect() or by watching wxSOCKET_CONNECTION
                and wxSOCKET_LOST events.

        @see WaitOnConnect(), wxSocketBase::SetNotify(), wxSocketBase::Notify()
    */
  virtual bool Connect(const wxSockAddress& address, bool wait = true);
    /**
        Connects to a server using the specified address.

        If @a wait is @true, Connect() will wait until the connection
        completes. @b Warning: This will block the GUI.

        If @a wait is @false, Connect() will try to establish the connection
        and return immediately, without blocking the GUI. When used this way,
        even if Connect() returns @false, the connection request can be
        completed later. To detect this, use WaitOnConnect(), or catch
        @b wxSOCKET_CONNECTION events (for successful establishment) and
        @b wxSOCKET_LOST events (for connection failure).

        @param address
            Address of the server.
        @param local
            Bind to the specified local address and port before connecting.
            The local address and port can also be set using SetLocal(),
            and then using the 2-parameter Connect() method.
        @param wait
            If @true, waits for the connection to complete.

        @return @true if the connection is established and no error occurs.
                If @a wait was true, and Connect() returns @false, an error
                occurred and the connection failed.
                If @a wait was @false, and Connect() returns @false, you should
                still be prepared to handle the completion of this connection request,
                either with WaitOnConnect() or by watching wxSOCKET_CONNECTION
                and wxSOCKET_LOST events.

        @see WaitOnConnect(), wxSocketBase::SetNotify(), wxSocketBase::Notify()
    */
  bool Connect(const wxSockAddress& address, const wxSockAddress& local, bool wait = true);
    /**
        Wait until a connection request completes, or until the specified timeout
        elapses. Use this function after issuing a call to Connect() with
        @e wait set to @false.

        @param seconds
            Number of seconds to wait.
            If -1, it will wait for the default timeout, as set with wxSocketBase::SetTimeout().
        @param milliseconds
            Number of milliseconds to wait.

        @return
            WaitOnConnect() returns @true if the connection request completes.
            This does not necessarily mean that the connection was
            successfully established; it might also happen that the
            connection was refused by the peer. Use wxSocketBase::IsConnected()
            to distinguish between these two situations.
            @n @n If the timeout elapses, WaitOnConnect() returns @false.
            @n @n These semantics allow code like this:
            @code
            // Issue the connection request
            client->Connect(addr, false);

            // Wait until the request completes or until we decide to give up
            bool waitmore = true;
            while ( !client->WaitOnConnect(seconds, millis) && waitmore )
            {
                // possibly give some feedback to the user,
                // and update waitmore as needed.
            }
            bool success = client->IsConnected();
            @endcode
    */
  bool WaitOnConnect(long seconds = -1, long milliseconds = 0);
};
/**
    @class wxSockAddress

    You are unlikely to need to use this class: only wxSocketBase uses it.

    @library{wxnet}
    @category{net}

    @see wxSocketBase, wxIPaddress, wxIPV4address
*/
class wxSockAddress : public wxObject
{
public:
    /**
        Default constructor.
    */
  wxSockAddress();
    /**
        Default destructor.
    */
  virtual ~wxSockAddress();
    /**
        Delete all information about the address.
    */
  virtual void Clear();
    /**
        Returns the length of the socket address.
    */
  int SockAddrLen();
    /**
        Returns the pointer to the low-level representation of the address.

        This can be used to pass socket address information to a 3rd party
        library.

        @return
            Pointer to a sockaddr-derived struct.
    */
  const sockaddr* GetAddressData() const;
    /**
        Returns the length of the buffer retrieved by GetAddressData().

        @return
            The size of the sockaddr-derived struct corresponding to this
            address.
    */
  int GetAddressDataLen() const;
};
/**
    @class wxSocketEvent

    This event class contains information about socket events.
    This kind of events are sent to the event handler specified with
    wxSocketBase::SetEventHandler.

    @beginEventTable{wxSocketEvent}
    @event{EVT_SOCKET(id, func)}
        Process a socket event, supplying the member function.
    @endEventTable

    @library{wxnet}
    @category{net}

    @see wxSocketBase, wxSocketClient, wxSocketServer
*/
class wxSocketEvent : public wxEvent
{
public:
    /**
        Constructor.
    */
  wxSocketEvent(int id = 0);
    /**
        Gets the client data of the socket which generated this event, as
        set with wxSocketBase::SetClientData().
    */
  void* GetClientData() const;
    /**
        Returns the socket object to which this event refers to.
        This makes it possible to use the same event handler for different sockets.
    */
  wxSocketBase* GetSocket() const;
    /**
        Returns the socket event type.
    */
  wxSocketNotify GetSocketEvent() const;
};
/**
    wxSocket error return values.
*/
enum wxSocketError {
    wxSOCKET_NOERROR,       ///< No error happened.
    wxSOCKET_INVOP,         ///< Invalid operation.
    wxSOCKET_IOERR,         ///< Input/Output error.
    wxSOCKET_INVADDR,       ///< Invalid address passed to wxSocket.
    wxSOCKET_INVSOCK,       ///< Invalid socket (uninitialized).
    wxSOCKET_NOHOST,        ///< No corresponding host.
    wxSOCKET_INVPORT,       ///< Invalid port.
    wxSOCKET_WOULDBLOCK,    ///< The socket is non-blocking and the operation would block.
    wxSOCKET_TIMEDOUT,      ///< The timeout for this operation expired.
    wxSOCKET_MEMERR         ///< Memory exhausted.
};
/**
    @anchor wxSocketEventFlags

    wxSocket Event Flags.

    A brief note on how to use these events:

    The @b wxSOCKET_INPUT event will be issued whenever there is data available
    for reading. This will be the case if the input queue was empty and new data
    arrives, or if the application has read some data yet there is still more data
    available. This means that the application does not need to read all available
    data in response to a @b wxSOCKET_INPUT event, as more events will be produced
    as necessary.

    The @b wxSOCKET_OUTPUT event is issued when a socket is first connected with
    Connect() or accepted with Accept(). After that, new events will be generated
    only after an output operation fails with @b wxSOCKET_WOULDBLOCK and buffer space
    becomes available again. This means that the application should assume that it can
    write data to the socket until an @b wxSOCKET_WOULDBLOCK error occurs; after this,
    whenever the socket becomes writable again the application will be notified with
    another @b wxSOCKET_OUTPUT event.

    The @b wxSOCKET_CONNECTION event is issued when a delayed connection request completes
    successfully (client) or when a new connection arrives at the incoming queue (server).

    The @b wxSOCKET_LOST event is issued when a close indication is received for the socket.
    This means that the connection broke down or that it was closed by the peer. Also, this
    event will be issued if a connection request fails.
*/
enum wxSocketEventFlags {
    wxSOCKET_INPUT,         ///< There is data available for reading.
    wxSOCKET_OUTPUT,        ///< The socket is ready to be written to.
    wxSOCKET_CONNECTION,    ///< Incoming connection request (server), or
                            ///< successful connection establishment (client).
    wxSOCKET_LOST           ///< The connection has been closed.
};
/**
    @anchor wxSocketFlags

    wxSocket Flags.

    A brief overview on how to use these flags follows.

    If no flag is specified (this is the same as @b wxSOCKET_NONE),
    IO calls will return after some data has been read or written, even
    when the transfer might not be complete. This is the same as issuing
    exactly one blocking low-level call to @b recv() or @b send(). Note
    that @e blocking here refers to when the function returns, not
    to whether the GUI blocks during this time.

    If @b wxSOCKET_NOWAIT is specified, IO calls will return immediately.
    Read operations will retrieve only available data. Write operations will
    write as much data as possible, depending on how much space is available
    in the output buffer. This is the same as issuing exactly one nonblocking
    low-level call to @b recv() or @b send(). Note that @e nonblocking here
    refers to when the function returns, not to whether the GUI blocks during
    this time.  Also note that this flag impacts both Read and Write
    operations.  If it is desired to control Read independently of Write, for
    example you want no wait on Read(), but you do want to wait on Write(), then
    use wxSOCKET_NOWAIT_READ and wxSOCKET_NOWAIT_WRITE.

    If @b wxSOCKET_NOWAIT_READ (this flag is new since wxWidgets 2.9.5) is
    specified, Read operations will return immediately. Read operations will
    retrieve only available data. This is the same as issuing exactly one
    nonblocking low-level call to @b recv(). Note that @e nonblocking here
    refers to when the function returns, not to whether the GUI blocks during
    this time.  This flag should not be enabled if ReadMsg() is going to be
    used (it will be ignored), if you do then thread-safety may be at risk.
    Note that wxSOCKET_NOWAIT_READ impacts only Read operations and does not
    impact Write operations, allowing Read and Write operations to be set
    differently.

    If @b wxSOCKET_NOWAIT_WRITE (this flag is new since wxWidgets 2.9.5) is
    specified, Write operations will return immediately. Write operations will
    write as much data as possible, depending on how much space is available in
    the output buffer. This is the same as issuing exactly one nonblocking
    low-level call to @b send(). Note that @e nonblocking here refers to when
    the function returns, not to whether the GUI blocks during this time.  This
    flag should not be enabled if WriteMsg() is going to be used (it will be
    ignored), if you use it then thread safety may be at risk. Note that
    wxSOCKET_NOWAIT_WRITE impacts only Write operations and does not impact
    Read operations, allowing Read and Write operations to be set differently.

    If @b wxSOCKET_WAITALL is specified, IO calls won't return until ALL
    the data has been read or written (or until an error occurs), blocking if
    necessary, and issuing several low level calls if necessary. This is the
    same as having a loop which makes as many blocking low-level calls to
    @b recv() or @b send() as needed so as to transfer all the data. Note
    that @e blocking here refers to when the function returns, not
    to whether the GUI blocks during this time.  Note that wxSOCKET_WAITALL
    impacts both Read and Write operations.  If you desire to wait
    for all on just Read operations, but not on Write operations, (or vice versa),
    use wxSOCKET_WAITALL_READ or wxSOCKET_WAITALL_WRITE.

    If @b wxSOCKET_WAITALL_READ (this flag is new since wxWidgets 2.9.5) is
    specified, Read operations won't return until ALL the data has been read
    (or until an error occurs), blocking if necessary, and issuing several low
    level calls if necessary. This is the same as having a loop which makes as
    many blocking low-level calls to @b recv() as needed so as to transfer all
    the data. Note that @e blocking here refers to when the function returns,
    not to whether the GUI blocks during this time.  Note that
    wxSOCKET_WAITALL_READ only has an impact on Read operations, and has no
    impact on Write operations, allowing Read and Write operations to have
    different settings.

    If @b wxSOCKET_WAITALL_WRITE (this flag is new since wxWidgets 2.9.5) is
    specified, Write() and WriteMsg() calls won't return until ALL the data has
    been written (or until an error occurs), blocking if necessary, and issuing
    several low level calls if necessary. This is the same as having a loop
    which makes as many blocking low-level calls to @b send() as needed so as
    to transfer all the data. Note that @e blocking here refers to when the
    function returns, not to whether the GUI blocks during this time.  Note
    that wxSOCKET_WAITALL_WRITE only has an impact on Write operations, and has
    no impact on Read operations, allowing Read and Write operations to have
    different settings.

    The @b wxSOCKET_BLOCK flag controls whether the GUI blocks during
    IO operations. If this flag is specified, the socket will not yield
    during IO calls, so the GUI will remain blocked until the operation
    completes. If it is not used, then the application must take extra
    care to avoid unwanted reentrance.

    The @b wxSOCKET_REUSEADDR flag controls the use of the @b SO_REUSEADDR standard
    @b setsockopt() flag. This flag allows the socket to bind to a port that is
    already in use. This is mostly used on UNIX-based systems to allow rapid starting
    and stopping of a server, otherwise you may have to wait several minutes for the
    port to become available.

    @b wxSOCKET_REUSEADDR can also be used with socket clients to (re)bind to a
    particular local port for an outgoing connection.
    This option can have surprising platform dependent behaviour, so check the
    documentation for your platform's implementation of setsockopt().

    Note that on BSD-based systems(e.g. OS X), use of
    @b wxSOCKET_REUSEADDR implies @b SO_REUSEPORT in addition to
    @b SO_REUSEADDR to be consistent with Windows.

    The @b wxSOCKET_BROADCAST flag controls the use of the @b SO_BROADCAST standard
    @b setsockopt() flag. This flag allows the socket to use the broadcast address,
    and is generally used in conjunction with @b wxSOCKET_NOBIND and
    wxIPaddress::BroadcastAddress().

    So:
    - @b wxSOCKET_NONE will try to read at least SOME data, no matter how much.
    - @b wxSOCKET_NOWAIT will always return immediately, even if it cannot
      read or write ANY data.
    - @b wxSOCKET_WAITALL will only return when it has read or written ALL
      the data.
    - @b wxSOCKET_BLOCK has nothing to do with the previous flags and
      it controls whether the GUI blocks.
    - @b wxSOCKET_REUSEADDR controls special platform-specific behaviour for
      reusing local addresses/ports.
*/
enum
{
  wxSOCKET_NONE = 0,
  wxSOCKET_NOWAIT = 1,
  wxSOCKET_WAITALL = 2,
  wxSOCKET_BLOCK = 4,
  wxSOCKET_REUSEADDR = 8,
  wxSOCKET_BROADCAST = 16,
  wxSOCKET_NOBIND = 32,
                            ///< adapter (normally used in conjunction with
                            ///< @b wxSOCKET_BROADCAST)
  wxSOCKET_NOWAIT_READ = 64,
  wxSOCKET_WAITALL_READ = 128,
  wxSOCKET_NOWAIT_WRITE = 256,
  wxSOCKET_WAITALL_WRITE = 512
};
/**
    @class wxSocketBase

    wxSocketBase is the base class for all socket-related objects, and it
    defines all basic IO functionality.

    @note
    When using wxSocket from multiple threads, even implicitly (e.g. by using
    wxFTP or wxHTTP in another thread) you must initialize the sockets from the
    main thread by calling Initialize() before creating the other ones.

    @beginEventEmissionTable{wxSocketEvent}
    @event{EVT_SOCKET(id, func)}
        Process a @c wxEVT_SOCKET event.
        See @ref wxSocketEventFlags and @ref wxSocketFlags for more info.
    @endEventTable

    @library{wxnet}
    @category{net}

    @see wxSocketEvent, wxSocketClient, wxSocketServer, @sample{sockets},
         @ref wxSocketFlags, ::wxSocketEventFlags, ::wxSocketError
*/
class wxSocketBase : public wxObject
{
public:
    /**
        @name Construction and Destruction
    */
    //@{

    /**
        Default constructor.

        Don't use it directly; instead, use wxSocketClient to construct a socket client,
        or wxSocketServer to construct a socket server.
    */
  wxSocketBase();
    /**
        Destructor.

        Do not destroy a socket using the delete operator directly;
        use Destroy() instead. Also, do not create socket objects in the stack.
    */
  virtual ~wxSocketBase();
    /**
        Destroys the socket safely.

        Use this function instead of the delete operator, since otherwise socket events
        could reach the application even after the socket has been destroyed. To prevent
        this problem, this function appends the wxSocket to a list of object to be deleted
        on idle time, after all events have been processed. For the same reason, you should
        avoid creating socket objects in the stack.

        Destroy() calls Close() automatically.

        @return Always @true.
    */
  bool Destroy();
    /**
        Perform the initialization needed in order to use the sockets.

        This function is called from wxSocket constructor implicitly and so
        normally doesn't need to be called explicitly. There is however one
        important exception: as this function must be called from the main
        (UI) thread, if you use wxSocket from multiple threads you must call
        Initialize() from the main thread before creating wxSocket objects in
        the other ones.

        It is safe to call this function multiple times (only the first call
        does anything) but you must call Shutdown() exactly once for every call
        to Initialize().

        This function should only be called from the main thread.

        @return
            @true if the sockets can be used, @false if the initialization
            failed and sockets are not available at all.
     */
  static bool Initialize();
    /**
        Shut down the sockets.

        This function undoes the call to Initialize() and must be called after
        every successful call to Initialize().

        This function should only be called from the main thread, just as
        Initialize().
     */
  static void Shutdown();
    //@}

    /**
        @name Socket State
    */
    //@{

    /**
        Returns @true if an error occurred in the last IO operation.

        Use this function to check for an error condition after one of the
        following calls: Discard(), Peek(), Read(), ReadMsg(), Unread(), Write(), WriteMsg().
    */
  bool Error() const;
    /**
        Return the local address of the socket.

        @return @true if no error happened, @false otherwise.
    */
  virtual bool GetLocal(wxSockAddress& addr) const;
    /**
        Return the peer address field of the socket.

        @return @true if no error happened, @false otherwise.
    */
  virtual bool GetPeer(wxSockAddress& addr) const;
    /**
        Return the socket timeout in seconds.

        The timeout can be set using SetTimeout() and is 10 minutes by default.
     */
  long GetTimeout() const;
    /**
        Returns @true if the socket is connected.
    */
  bool IsConnected() const;
    /**
        Check if the socket can be currently read or written.

        This might mean that queued data is available for reading or, for streamed
        sockets, that the connection has been closed, so that a read operation will
        complete immediately without blocking (unless the @b wxSOCKET_WAITALL flag
        is set, in which case the operation might still block).
    */
  bool IsData();
    /**
        Returns @true if the socket is not connected.
    */
  bool IsDisconnected() const;
    /**
        Returns @true if the socket is initialized and ready and @false in other
        cases.

        @remarks
        For wxSocketClient, IsOk() won't return @true unless the client is connected to a server.
        For wxSocketServer, IsOk() will return @true if the server could bind to the specified address
        and is already listening for new connections.
        IsOk() does not check for IO errors; use Error() instead for that purpose.
    */
  bool IsOk() const;
    /**
        Returns the number of bytes read or written by the last IO call.

        Use this function to get the number of bytes actually transferred
        after using one of the following IO calls: Discard(), Peek(), Read(),
        ReadMsg(), Unread(), Write(), WriteMsg().

        @deprecated
        This function is kept mostly for backwards compatibility.  Use
        LastReadCount() or LastWriteCount() instead.  LastCount() is still
        needed for use with less commonly used functions: Discard(),
        Peek(), and Unread().
    */
  wxUint32 LastCount() const;
    /**
        Returns the number of bytes read by the last Read() or ReadMsg()
        call (receive direction only).

        This function is thread-safe, in case Read() is executed in a
        different thread than Write().  Use LastReadCount() instead of
        LastCount() for this reason.

        Unlike LastCount(), the functions Discard(), Peek(), and Unread()
        are currently not supported by LastReadCount().

        @since 2.9.5
    */
  wxUint32 LastReadCount() const;
    /**
        Returns the number of bytes written by the last Write() or WriteMsg()
        call (transmit direction only).

        This function is thread-safe, in case Write() is executed in a
        different thread than Read().  Use LastWriteCount() instead of
        LastCount() for this reason.

        @since 2.9.5
    */
  wxUint32 LastWriteCount() const;
    /**
        Returns the last wxSocket error. See @ref wxSocketError .

        @note
        This function merely returns the last error code,
        but it should not be used to determine if an error has occurred (this
        is because successful operations do not change the LastError value).
        Use Error() first, in order to determine if the last IO call failed.
        If this returns @true, use LastError() to discover the cause of the error.
    */
  wxSocketError LastError() const;
    /**
        Restore the previous state of the socket, as saved with SaveState().

        Calls to SaveState() and RestoreState() can be nested.

        @see SaveState()
    */
  void RestoreState();
    /**
        Save the current state of the socket in a stack.

        Socket state includes flags, as set with SetFlags(), event mask, as set
        with SetNotify() and Notify(), user data, as set with SetClientData().
        Calls to SaveState and RestoreState can be nested.

        @see RestoreState()
    */
  void SaveState();
    //@}

    /**
        @name Basic I/O

        See also: wxSocketServer::WaitForAccept(), wxSocketClient::WaitOnConnect()
    */
    //@{

    /**
        Shut down the socket, disabling further transmission and reception of
        data and disable events for the socket and frees the associated system
        resources.

        Upon socket destruction, Close() is automatically called, so in most cases
        you won't need to do it yourself, unless you explicitly want to shut down
        the socket, typically to notify the peer that you are closing the connection.

        @remarks
        Although Close() immediately disables events for the socket, it is possible
        that event messages may be waiting in the application's event queue.
        The application must therefore be prepared to handle socket event messages even
        after calling Close().
    */
  virtual bool Close();
    /**
        Shuts down the writing end of the socket.

        This function simply calls the standard shutdown() function on the
        underlying socket, indicating that nothing will be written to this
        socket any more.
     */
  void ShutdownOutput();
    /**
        Delete all bytes in the incoming queue.

        This function always returns immediately and its operation is not
        affected by IO flags.

        Use LastCount() to verify the number of bytes actually discarded.

        If you use Error(), it will always return @false.
    */
  wxSocketBase& Discard();
    /**
        Returns current IO flags, as set with SetFlags()
    */
  wxSocketFlags GetFlags() const;
    /**
        Use this function to interrupt any wait operation currently in progress.

        Note that this is not intended as a regular way to interrupt a Wait call,
        but only as an escape mechanism for exceptional situations where it is
        absolutely necessary to use it, for example to abort an operation due to
        some exception or abnormal problem. InterruptWait is automatically called
        when you Close() a socket (and thus also upon
        socket destruction), so you don't need to use it in these cases.

        @see  Wait(), WaitForLost(), WaitForRead(), WaitForWrite(),
              wxSocketServer::WaitForAccept(), wxSocketClient::WaitOnConnect()
    */
  void InterruptWait();
    /**
        Peek into the socket by copying the next bytes which would be read by
        Read() into the provided buffer.

        Peeking a buffer doesn't delete it from the socket input queue, i.e.
        calling Read() will return the same data.

        Use LastCount() to verify the number of bytes actually peeked.

        Use Error() to determine if the operation succeeded.

        @param buffer
            Buffer where to put peeked data.
        @param nbytes
            Number of bytes.

        @return Returns a reference to the current object.

        @remarks
            The exact behaviour of Peek() depends on the combination of flags being used.
            For a detailed explanation, see SetFlags()

        @see Error(), LastError(), LastCount(), SetFlags()
    */
  wxSocketBase& Peek(void* buffer, wxUint32 nbytes);
    /**
        Read up to the given number of bytes from the socket.

        Use LastReadCount() to verify the number of bytes actually read.
        Use Error() to determine if the operation succeeded.

        @param buffer
            Buffer where to put read data.
        @param nbytes
            Number of bytes.

        @return Returns a reference to the current object.

        @remarks
            The exact behaviour of Read() depends on the combination of flags being used.
            For a detailed explanation, see SetFlags()

        @see Error(), LastError(), LastReadCount(),
             SetFlags()
    */
  wxSocketBase& Read(void* buffer, wxUint32 nbytes);
    /**
        Receive a message sent by WriteMsg().

        If the buffer passed to the function isn't big enough, the remaining
        bytes will be discarded. This function always waits for the buffer to
        be entirely filled, unless an error occurs.

        Use LastReadCount() to verify the number of bytes actually read.

        Use Error() to determine if the operation succeeded.

        @param buffer
            Buffer where to put read data.
        @param nbytes
            Size of the buffer.

        @return Returns a reference to the current object.

        @remarks
            ReadMsg() will behave as if the @b wxSOCKET_WAITALL flag was always set
            and it will always ignore the @b wxSOCKET_NOWAIT flag.
            The exact behaviour of ReadMsg() depends on the @b wxSOCKET_BLOCK flag.
            For a detailed explanation, see SetFlags().
            For thread safety, in case ReadMsg() and WriteMsg() are called in
            different threads, it is a good idea to call
            SetFlags(wxSOCKET_WAITALL|wx_SOCKET_BLOCK) before the first calls
            to ReadMsg() and WriteMsg() in different threads, as each of these
            functions will call SetFlags() which performs read/modify/write.  By
            setting these flags before the multi-threading, it will ensure that
            they don't get reset by thread race conditions.

        @see Error(), LastError(), LastReadCount(), SetFlags(), WriteMsg()
    */
  wxSocketBase& ReadMsg(void* buffer, wxUint32 nbytes);
    /**
        Use SetFlags to customize IO operation for this socket.

        The @a flags parameter may be a combination of flags ORed together.
        Notice that not all combinations of flags affecting the IO calls
        (Read() and Write()) make sense, e.g. @b wxSOCKET_NOWAIT can't be
        combined with @b wxSOCKET_WAITALL nor with @b wxSOCKET_BLOCK.

        The following flags can be used:
        @beginFlagTable
        @flag{wxSOCKET_NONE}
            Default mode: the socket will read some data in the IO calls and
            will process events to avoid blocking UI while waiting for the data
            to become available.
        @flag{wxSOCKET_NOWAIT}
            Don't wait for the socket to become ready in IO calls, read as much
            data as is available -- potentially 0 bytes -- and return
            immediately.
        @flag{wxSOCKET_WAITALL}
            Don't return before the entire amount of data specified in IO calls
            is read or written unless an error occurs. If this flag is not
            specified, the IO calls return as soon as any amount of data, even
            less than the total number of bytes, is processed.
        @flag{wxSOCKET_BLOCK}
            Don't process the UI events while waiting for the socket to become
            ready. This means that UI will be unresponsive during socket IO.
        @flag{wxSOCKET_REUSEADDR}
            Allows the use of an in-use port (wxServerSocket only).
        @flag{wxSOCKET_BROADCAST}
            Switches the socket to broadcast mode.
        @flag{wxSOCKET_NOBIND}
            Stops the socket from being bound to a specific adapter (normally
            used in conjunction with @b wxSOCKET_BROADCAST).
        @endFlagTable

        For more information on socket events see @ref wxSocketFlags .
    */
  void SetFlags(wxSocketFlags flags);
    /**
        Set the local address and port to use.

        This function must always be called for the server sockets but may also
        be called for client sockets, if it is, @b bind() is called before @b
        connect().
    */
  virtual bool SetLocal(const wxIPV4address& local);
    /**
        Set the default socket timeout in seconds.

        This timeout applies to all IO calls, and also to the Wait() family of
        functions if you don't specify a wait interval. Initially, the default
        timeout is 10 minutes.
    */
  void SetTimeout(long seconds);
    /**
        Put the specified data into the input queue.

        The data in the buffer will be returned by the next call to Read().

        This function is not affected by wxSocket flags.

        If you use LastCount(), it will always return @a nbytes.

        If you use Error(), it will always return @false.

        @param buffer
            Buffer to be unread.
        @param nbytes
            Number of bytes.

        @return Returns a reference to the current object.

        @see Error(), LastCount(), LastError()
    */
  wxSocketBase& Unread(const void* buffer, wxUint32 nbytes);
    /**
        Wait for any socket event.

        Possible socket events are:
        @li The socket becomes readable.
        @li The socket becomes writable.
        @li An ongoing connection request has completed (wxSocketClient only)
        @li An incoming connection request has arrived (wxSocketServer only)
        @li The connection has been closed.

        Note that it is recommended to use the individual @b WaitForXXX()
        functions to wait for the required condition, instead of this one.

        @param seconds
            Number of seconds to wait.
            If -1, it will wait for the default timeout,
            as set with SetTimeout().
        @param millisecond
            Number of milliseconds to wait.

        @return
           @true when any of the above conditions is satisfied or @false if the
           timeout was reached.

        @see InterruptWait(), wxSocketServer::WaitForAccept(),
             WaitForLost(), WaitForRead(),
             WaitForWrite(), wxSocketClient::WaitOnConnect()
    */
  bool Wait(long seconds = -1, long millisecond = 0);
    /**
        Wait until the connection is lost.

        This may happen if the peer gracefully closes the connection or if the
        connection breaks.

        @param seconds
            Number of seconds to wait.
            If -1, it will wait for the default timeout,
            as set with SetTimeout().
        @param millisecond
            Number of milliseconds to wait.

        @return Returns @true if the connection was lost, @false if the timeout
                was reached.

        @see InterruptWait(), Wait()
    */
  bool WaitForLost(long seconds = -1, long millisecond = 0);
    /**
        Wait until the socket is readable.

        This might mean that queued data is available for reading or, for streamed
        sockets, that the connection has been closed, so that a read operation will
        complete immediately without blocking (unless the @b wxSOCKET_WAITALL flag
        is set, in which case the operation might still block).

        Notice that this function should not be called if there is already data
        available for reading on the socket.

        @param seconds
            Number of seconds to wait.
            If -1, it will wait for the default timeout,
            as set with SetTimeout().
        @param millisecond
            Number of milliseconds to wait.

        @return Returns @true if the socket becomes readable, @false on timeout.

        @see InterruptWait(), Wait()
    */
  bool WaitForRead(long seconds = -1, long millisecond = 0);
    /**
        Wait until the socket becomes writable.

        This might mean that the socket is ready to send new data, or for streamed
        sockets, that the connection has been closed, so that a write operation is
        guaranteed to complete immediately (unless the @b wxSOCKET_WAITALL flag is set,
        in which case the operation might still block).

        Notice that this function should not be called if the socket is already
        writable.

        @param seconds
            Number of seconds to wait.
            If -1, it will wait for the default timeout,
            as set with SetTimeout().
        @param millisecond
            Number of milliseconds to wait.

        @return Returns @true if the socket becomes writable, @false on timeout.

        @see InterruptWait(), Wait()
    */
  bool WaitForWrite(long seconds = -1, long millisecond = 0);
    /**
        Write up to the given number of bytes to the socket.

        Use LastWriteCount() to verify the number of bytes actually written.

        Use Error() to determine if the operation succeeded.

        @param buffer
            Buffer with the data to be sent.
        @param nbytes
            Number of bytes.

        @return Returns a reference to the current object.

        @remarks

        The exact behaviour of Write() depends on the combination of flags being used.
        For a detailed explanation, see SetFlags().

        @see Error(), LastError(), LastWriteCount(), SetFlags()
    */
  wxSocketBase& Write(const void* buffer, wxUint32 nbytes);
    /**
        Sends a buffer which can be read using ReadMsg().

        WriteMsg() sends a short header before the data so that ReadMsg()
        knows how much data should be actually read.

        This function always waits for the entire buffer to be sent, unless an
        error occurs.

        Use LastWriteCount() to verify the number of bytes actually written.

        Use Error() to determine if the operation succeeded.

        @param buffer
            Buffer with the data to be sent.
        @param nbytes
            Number of bytes to send.

        @return Returns a reference to the current object.

        @remarks

        WriteMsg() will behave as if the @b wxSOCKET_WAITALL flag was always set and
        it will always ignore the @b wxSOCKET_NOWAIT flag. The exact behaviour of
        WriteMsg() depends on the @b wxSOCKET_BLOCK flag. For a detailed explanation,
        see SetFlags().
        For thread safety, in case ReadMsg() and WriteMsg() are called in
        different threads, it is a good idea to call
        @code SetFlags(wxSOCKET_WAITALL|wx_SOCKET_BLOCK) @endcode before the
        first calls to ReadMsg() and WriteMsg() in different threads, as each
        of these functions calls SetFlags() which performs read/modify/write.
        By setting these flags before the multi-threading, it will ensure that
        they don't get reset by thread race conditions.

        @see  Error(), LastError(), LastWriteCount(), SetFlags(), ReadMsg()

    */
  wxSocketBase& WriteMsg(const void* buffer, wxUint32 nbytes);
    //@}

    /**
        @name Handling Socket Events
    */
    //@{

    /**
        Returns a pointer of the client data for this socket, as set with
        SetClientData()
    */
  void* GetClientData() const;
    /**
        According to the @a notify value, this function enables
        or disables socket events. If @a notify is @true, the events
        configured with SetNotify() will
        be sent to the application. If @a notify is @false; no events
        will be sent.
    */
  void Notify(bool notify);
    /**
        Sets user-supplied client data for this socket. All socket events will
        contain a pointer to this data, which can be retrieved with
        the wxSocketEvent::GetClientData() function.
    */
  void SetClientData(void* data);
    /**
        Sets an event handler to be called when a socket event occurs. The
        handler will be called for those events for which notification is
        enabled with SetNotify() and
        Notify().

        @param handler
            Specifies the event handler you want to use.
        @param id
            The id of socket event.

        @see SetNotify(), Notify(), wxSocketEvent, wxEvtHandler
    */
  void SetEventHandler(wxEvtHandler& handler, int id = -1);
    /**
        Specifies which socket events are to be sent to the event handler.
        The @a flags parameter may be combination of flags ORed together. The
        following flags can be used:

        @beginFlagTable
        @flag{wxSOCKET_INPUT_FLAG} to receive @b wxSOCKET_INPUT.
        @flag{wxSOCKET_OUTPUT_FLAG} to receive @b wxSOCKET_OUTPUT.
        @flag{wxSOCKET_CONNECTION_FLAG} to receive @b wxSOCKET_CONNECTION.
        @flag{wxSOCKET_LOST_FLAG} to receive @b wxSOCKET_LOST.
        @endFlagTable

        For example:

        @code
        sock.SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG);
        sock.Notify(true);
        @endcode

        In this example, the user will be notified about incoming socket data and
        whenever the connection is closed.

        For more information on socket events see @ref wxSocketEventFlags .
    */
  void SetNotify(wxSocketEventFlags flags);
    /**
        Returns the native socket descriptor.

        This is intended to use with rarely used specific platform features
        that can only be accessed via the actual socket descriptor.

        Do not use this for reading or writing data from or to the socket as
        this would almost surely interfere with wxSocket code logic and result
        in unexpected behaviour.

        The socket must be successfully initialized, e.g. connected for client
        sockets, before this method can be called.

        @return Returns the native socket descriptor.

        @since 2.9.5
    */
  wxSOCKET_T GetSocket() const;
    //@}
};
/**
    @class wxDatagramSocket

    @todo docme

    @library{wxnet}
    @category{net}
*/
class wxDatagramSocket : public wxSocketBase
{
public:
    /**
        Constructor.

        @param addr
            The socket address.
        @param flags
            Socket flags (See wxSocketBase::SetFlags()).
    */
  wxDatagramSocket(const wxSockAddress& addr, wxSocketFlags flags = wxSOCKET_NONE);
    /**
        Destructor. Please see wxSocketBase::Destroy().
    */
  virtual ~wxDatagramSocket();
    /**
        Write a buffer of @a nbytes bytes to the socket.

        Use wxSocketBase::LastWriteCount() to verify the number of bytes actually wrote.
        Use wxSocketBase::Error() to determine if the operation succeeded.

        @param address
            The address of the destination peer for this data.
        @param buffer
            Buffer where read data is.
        @param nbytes
            Number of bytes.

        @return Returns a reference to the current object.

        @see wxSocketBase::LastError(), wxSocketBase::SetFlags()
    */
  wxDatagramSocket& SendTo(const wxSockAddress& address, const void* buffer, wxUint32 nbytes);
};


text:
title: "Handwriting recognition with logistic regression"
date: 2015-04-14
modified: 2015-04-14
excerpt: "Simple multiclass classification"
layout: post
published: true
status: publish
comments: true
tags: [machine learning, logistic regression, fminunc]
categories: [Rstats]
---

In my previous [post](http://ivyleavedtoadflax.github.io//regularised-logistic-regression/) I completed an exercise using logistic regression to generate complicated non-linear decision boundaries. In this exercise I'm going to use much of the same code for handwriting recognition. These exercises are all part of Andrew Ng's Machine Learning course on [coursera](http://www.coursera.org). All the exercises are done in Matlab/Octave, but I've been stubborn and have worked solutions in R instead.

### The Data

For this exercise the dataset comprises 5000 training examples where each examples is a $20 \times 20$ pixel grayscale image of a digit between 0-9. The pixel values (which are floating point numbers) have been unrolled into a 400 dimensional vector giving a $5000 \times 400$ matrix $X$, where each row is a training example.

To visualise a subset of the data, I have been using the `raster` package in R

# 1.2 Visualising the data

In the Machine learning course by Andrew Ng the raster drawing function is already written. I'm going to try to produce an R equivalent using the raster package.

I'll start by loading the data and randomly selecting a 100 row subset of the data.

{% highlight r %}
library(dplyr)
library(magrittr)
library(raster)
library(grid)
library(ucminf)

# Vector listing the correct numbers for each trainign example

y <- "y.csv" %>%
  read.csv(
    header = FALSE
    )

# Here I bind the y and X matrices together so that I can generate the same
# random dataset

X <- "matrix.csv" %>%
  read.csv(
    header = FALSE
    ) %>%
  cbind(y) %>%
  sample_n(
    100
    ) %>%
  as.matrix

# Designate the training X and y set

train_y <- X[,401]
train <- X[,-401]
{% endhighlight %}

One of the things about the raster package is that for a grayscale image it expects the values to be between 0 and 1, and this is not the case in the training data. The values are also unrolled, so to create a bitmap, they need to be rolled back up.

{% highlight r %}
# Create a value between 0 and 1 by normalising the data

normalise <- function(x) {

  (x - min(x))/(max(x)-min(x))

  }

# Unroll the 20 x 20 pixel images into a 400 dimensional vector

roll <- function(x) {

  x <- normalise(x)
  x <- matrix(1-x,nrow=20,ncol=20)

  return(x)
  }
{% endhighlight %}

Now we can plot a single digit using:

{% highlight r %}
grid.raster(
  roll(train[1,]),
  interpolate = FALSE
  )
{% endhighlight %}

[![plot of chunk 2015-04-14-single-digit](/figures/2015-04-14-single-digit.png)](/figures/2015-04-14-single-digit.png)

So that's great for a single row, or a single training example. But it would be nice to plot the entire 100 row dataset that we are working from as a matrix. The following code loops through each row, and parks the $20 \times 20$ pixel grid into a matrix of $100$ bitmaps.

{% highlight r %}
hw_row <- function(X,ind) {

  out_mat <- roll(X[ind[1],])

  for (i in ind[2]:ind[10]) {

    out_mat %<>% cbind(roll(X[i,]))

    }

  return(out_mat)

  }

hw_mat <- function(X) {

for (j in seq(1,91,10)) {

  if (j == 1) hw_1 <- hw_row(X,1:10) else

    hw_1 %<>% rbind(hw_row(X,j:(j+9)))

  }

return(hw_1)
}
{% endhighlight %}

Which gives us...

{% highlight r %}
grid.raster(
  hw_mat(train),
  interpolate = FALSE
  )
{% endhighlight %}

[![plot of chunk 2015-04-14-digit-matrix](/figures/2015-04-14-digit-matrix.png)](/figures/2015-04-14-digit-matrix.png)

So great, this is what we are trying to classify.

### Multiclass classification

In this exercise I'm going to use the code I wrote in the previous [post](http://ivyleavedtoadflax.github.io//regularised-logistic-regression/), which should be ready to go out of the box.

For multiclass classification with logistic regression we simply run a mdoel for each possible class, then combine this ensemble of mdoels, and pick the value that has the highest likelihood based on the several models.

Now because the code is well vectorised running ten models together is an absolute breaze. First we define the parameter matrix $\theta$.

{% highlight r %}
Theta <- matrix(
  0,
  ncol = 10,
  nrow = 400
  )
{% endhighlight %}

Then use a for loop to generate parameters for each of our ten models

{% highlight r %}
for (i in 1:10) {

  Theta[,i] <- reg_lr(
    X = train,
    y = (train_y == i) * 1,
    theta = Theta[,i],
    lambda = 0
    )

  }
{% endhighlight %}

Now we run a logistic regression model using these parameters, which is simply $h_\theta=g(\theta^TX)$ where $g$ is the sigmoid function $g(z)=\frac{1}{1 + e^{-z}}$.

{% highlight r %}
out <- h(Theta,train)

# call the matrixStats package for the rowMaxs function

library(matrixStats)

out_class <- (rowMaxs(out) == out) %>%
  multiply_by(1) %>%
  multiply_by(
    rep(1:10) %>%
      replicate(n = nrow(out)) %>%
      t
    ) %>%
  rowMaxs
{% endhighlight %}

### The result

That was pretty straightforward. Let's check the first few predictions against the bitmap plotted earlier:

{% highlight r %}
out_class[1:10]
{% endhighlight %}

{% highlight text %}
##  [1]  9  2  9  6  6  7  8  3 10  7
{% endhighlight %}

So far so good. Note that zeros are classified as tens to avoid confusion. So how well does the model work on the training data overall?

{% highlight r %}
sum(out_class == train_y)/100
{% endhighlight %}

{% highlight text %}
## [1] 1
{% endhighlight %}

So currently the model achieved 100% accuracy with $\lambda = 0$ (the regularisation parameter), i.e. no regularisation at all.

### What about a test set?

I'll wrap this all in a function, then try it on a different subset of the $X$ matrix.

{% highlight r %}
hw_rec <- function(train,test,train_y,test_y,lambda,classes) {

  Theta <- matrix(
    0,
    ncol = classes, # number of classes
    nrow = ncol(train)
    )

  for (i in 1:classes) {

    Theta[,i] <- reg_lr(
      X = train,
      y = (train_y == i) * 1,
      theta = Theta[,i],
      lambda = lambda
      )

    }

  out <- h(Theta,test)

  out_class <- (rowMaxs(out) == out) %>%
    multiply_by(1) %>%
    multiply_by(
      rep(1:10) %>%
        replicate(n = nrow(out)) %>%
        t
      ) %>%
    rowMaxs

  acc <- sum(out_class == test_y)/100

  # Gives output of the predicted classes, the parameters (theta), and the
  # percentage accuracy

  return(
    list(
      class = out_class,
      theta = Theta,
      acc = acc
      )
    )

  }
{% endhighlight %}

So repeating the earlier code, I select a different random subset of 100 rows from the $X$ matrix.

{% highlight r %}
y <- "y.csv" %>%
  read.csv(
    header = FALSE
    )

test <- "matrix.csv" %>%
  read.csv(
    header = FALSE
    ) %>%
  cbind(y) %>%
  sample_n(
    100
    ) %>%
  as.matrix

test_y <- test[,401]
test <- test[,-401]
{% endhighlight %}

And looping through a range of $\lambda$, how accurately is the model predicting the digits?

{% highlight r %}
lambdas <- c(0.001,0.01,0.1,0.5,1,10)

test_lambda_y <- sapply(
  lambdas,
  function(x) {
      hw_rec(train,test,train_y,test_y,x,10)$acc
    }
  )

test_lambda_y
{% endhighlight %}

{% highlight text %}
## [1] 0.76 0.75 0.76 0.77 0.76 0.74
{% endhighlight %}

So not bad considering the model was trained on a dataset the same size as the test set. With varying levels of regularisation ($\lambda$) the model has between 74% and 77% accuracy.

Next time I'll define training, test, and cross validation sets with a 60:20:20 split, to improve classification, and better inform my choice of $\lambda$.

{% highlight r %}
sessionInfo()
{% endhighlight %}

{% highlight text %}
## R version 3.1.2 (2014-10-31)
## Platform: x86_64-unknown-linux-gnu (64-bit)
##
## locale:
##  [1] LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C
##  [3] LC_TIME=en_GB.UTF-8        LC_COLLATE=en_GB.UTF-8
##  [5] LC_MONETARY=en_GB.UTF-8    LC_MESSAGES=en_GB.UTF-8
##  [7] LC_PAPER=en_GB.UTF-8       LC_NAME=C
##  [9] LC_ADDRESS=C               LC_TELEPHONE=C
## [11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C
##
## attached base packages:
## [1] grid      methods   stats     graphics  grDevices utils     datasets
## [8] base
##
## other attached packages:
## [1] matrixStats_0.14.0 ucminf_1.1-3       raster_2.3-24
## [4] sp_1.0-15          magrittr_1.5       dplyr_0.2
## [7] testthat_0.9       knitr_1.6
##
## loaded via a namespace (and not attached):
## [1] assertthat_0.1  evaluate_0.5.5  formatR_1.0     lattice_0.20-29
## [5] parallel_3.1.2  Rcpp_0.11.2     stringr_0.6.2   tools_3.1.2
{% endhighlight %}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.olingo.fit.proxy.staticservice.odatawcfservice.types;

// CHECKSTYLE:OFF (Maven checkstyle)
import org.apache.olingo.ext.proxy.api.annotations.Key;

// CHECKSTYLE:ON (Maven checkstyle)

public interface ClubComposableInvoker
    extends org.apache.olingo.ext.proxy.api.StructuredComposableInvoker<Club, Club.Operations>
{

  @Override
  ClubComposableInvoker select(String... select);

  @Override
  ClubComposableInvoker expand(String... expand);

  @Key
  @org.apache.olingo.ext.proxy.api.annotations.Property(name = "ClubID",
      type = "Edm.Int32",
      nullable = false,
      defaultValue = "",
      maxLenght = Integer.MAX_VALUE,
      fixedLenght = false,
      precision = 0,
      scale = 0,
      unicode = true,
      collation = "",
      srid = "")
  java.lang.Integer getClubID();

  void setClubID(java.lang.Integer _clubID);

  @org.apache.olingo.ext.proxy.api.annotations.Property(name = "Name",
      type = "Edm.String",
      nullable = true,
      defaultValue = "",
      maxLenght = Integer.MAX_VALUE,
      fixedLenght = false,
      precision = 0,
      scale = 0,
      unicode = true,
      collation = "",
      srid = "")
  java.lang.String getName();

  void setName(java.lang.String _name);

}


text:
classify
=======

classify string, changes class to Class and some_class to SomeClass

```javascript
var classify = require("@nathanfaucett/classify");

classify("boxes") === "Box";
classify("skies") === "Sky";
classify("bike_riders") === "BikeRider";
classify("mega-big-sales") === "MegaBigSale";
```


text:
layout: post
category: "android"
title:  "Android startActivityForResult返回时需要注意的。 "
tags: [Android]
---
在onActivityResult中,即便是从后一个页面按back键返回的也是有resultCode的,且其值为0,其data为null.


text:
androidapilevel - This page was auto-generated. Feel free to help us improve the documentation by creating a pull request.

```lua
androidapilevel (value)
```

### Parameters ###

`value` - needs documentation.

## Applies To ###

The `config` scope.

### Availability ###

Premake 5.0.0 alpha 14 or later.

### Examples ###

```lua
androidapilevel (value)
```


text:
In glim framework, requests and responses are handled by application controllers. There exists a `Controller` class in `glim.component` module that every controllers must extend. The request & response objects are just wrappers of Werkzeug's `BaseRequest` & `BaseResponse`.
[block:api-header]
{
  "type": "basic",
  "title": "Request"
}
[/block]
After a request is mapped into a controller, the request variables are automatically injected into Controller. Since all the application controllers must extend `Controller` class, it is not needed to set the request explicitly for each controller. The base controller class is the following;
[block:code]
{
  "codes": [
    {
      "code": "class Controller:\n    \"\"\"\n\n    The controller component is responsible for handling requests\n    and returning appropriate response to the requests.\n\n    Attributes\n    ----------\n      request (werkzeug.wrappers.Request): The current request\n        object. This object is automatically passed by dispatch\n        module.\n\n    \"\"\"\n    def __init__(self, request):\n        self.request = request",
      "language": "python"
    }
  ]
}
[/block]
Simple, isn't it? So, each controller can access the request object by `self.request` that is provided by werkzeug dispatcher. `self.request` is an alias of `werkzeug.wrappers.BaseRequest` object that is injected by dispatcher.

Some useful functions for Request are the following;
[block:code]
{
  "codes": [
    {
      "code": "self.request.args()     # returns the dict that holds url parameters\nself.request.base_url() # the url without query string\nself.request.files()    # returns the data with enctype=\"multipart/form-data\" header\nself.request.form()     # returns the form url encoded parameters\nself.request.get_data() # returns the raw post body\nself.request.is_xhr()   # returns the request is coming whether from ajax or not",
      "language": "python"
    }
  ]
}
[/block]
A much more extensive documentation about Request objects can be found [here](http://werkzeug.pocoo.org/docs/0.9/wrappers/#werkzeug.wrappers.BaseRequest)
[block:api-header]
{
  "type": "basic",
  "title": "Response"
}
[/block]
The responses are the returned variables of any application `Controller` class in glim. For example;
[block:code]
{
  "codes": [
    {
      "code": "# controllers.py\nfrom app.models import Post\nfrom glim import Controller\nfrom glim import Response\nfrom glim_extensions.db import Orm\n\nimport json\n\nclass PostController(Controller):\n    def get(id):\n        post = Orm.query(Post).filter_by(post_id=id).first()\n        response = {}\n        if post:\n            response['post'] = dict(zip(post.keys(), post))\n            response['error'] = None\n            return Response(json.dumps(response))\n        else:\n            response['post'] = None\n            response['error'] = 'Cannot find post'\n            return Response(json.dumps(response), status=404)",
      "language": "python"
    }
  ]
}
[/block]
This is a simple REST like web service example of a `PostController`. Notice that, Response is a type of `werkzeug.wrappers.BaseResponse`. You can also drop the use of `return Response()` statement and use only `return json.dumps(response)`. Glim will understand this and create a Response for you.
[block:callout]
{
  "type": "warning",
  "title": "Do not use string based returns in filters",
  "body": "Although glim can convert the string returns into Responses, it is highly suggested not to use string base returns in filters for not having ambiguous definitions."
}
[/block]
Some useful variables for generating response;
[block:parameters]
{
  "data": {
    "0-0": "headers",
    "h-0": "variable",
    "h-1": "description",
    "0-1": "a list of headers or a Headers object",
    "1-0": "status",
    "1-1": "the http status code of response",
    "2-0": "mimetype",
    "2-1": "the mimetype for the request",
    "3-0": "content_type",
    "3-1": "the content type for the request"
  },
  "cols": 2,
  "rows": 4
}
[/block]
A much more extensive documentation of Response objects can be found [here](http://werkzeug.pocoo.org/docs/0.9/wrappers/#werkzeug.wrappers.BaseResponse)


text:
@protocol SelectManagerDelegate <NSObject>
-(void)changedownProgress:(CGFloat)progress;

@end

@interface SelectManager : NSObject<NSURLConnectionDataDelegate,DiandianCoreDataManagerDelegate>

@property(nonatomic,assign) id<SelectManagerDelegate> delegate;

+(SelectManager*)defaultManager;
- (NSArray *)downloadDateFromServiceToLocal:(int)flag;

-(void)downloadRecentShare;
-(void)downloadRecentGood;
-(void)downloadRecentComment;
-(void)downloadRecentReply;

@end


text:
namespace OpenPGP {
namespace Sign {

PKA::Values with_pka(const std::string & digest, const uint8_t pka, const PKA::Values & pri, const PKA::Values & pub, const uint8_t hash) {
    if ((pka == PKA::ID::RSA_ENCRYPT_OR_SIGN) ||
        (pka == PKA::ID::RSA_ENCRYPT_ONLY)) {
        // RFC 4880 sec 5.2.2
        // If RSA, hash value is encoded using EMSA-PKCS1-v1_5
        return {PKA::RSA::sign(EMSA_PKCS1_v1_5(hash, digest, bitsize(pub[0]) >> 3), pri, pub)};
    }
    else if (pka == PKA::ID::DSA) {
        return PKA::DSA::sign(digest, pri, pub);
    }

    // "Error: Undefined or incorrect PKA number: " + std::to_string(pka) + "\n";
    return {};
}

Packet::Tag2::Ptr create_sig_packet(const uint8_t version, const uint8_t type, const uint8_t pka, const uint8_t hash, const std::string & keyid) {
    // Set up signature packet
    Packet::Tag2::Ptr tag2 = std::make_shared <Packet::Tag2> ();
    tag2 -> set_version(version);
    tag2 -> set_pka(pka);
    tag2 -> set_type(type);
    tag2 -> set_hash(hash);

    // Set Time
    Subpacket::Tag2::Sub2::Ptr tag2sub2 = std::make_shared <Subpacket::Tag2::Sub2> ();
    tag2sub2 -> set_time(now());
    tag2 -> set_hashed_subpackets({tag2sub2});

    // Set Key ID
    Subpacket::Tag2::Sub16::Ptr tag2sub16 = std::make_shared <Subpacket::Tag2::Sub16> ();
    tag2sub16 -> set_keyid(keyid);
    tag2 -> set_unhashed_subpackets({tag2sub16});

    return tag2;
}

DetachedSignature detached_signature(const Args & args, const std::string & data) {
    if (!args.valid()) {
        // "Error: Bad argument.\n";
        return DetachedSignature();
    }

    Packet::Tag5::Ptr signer = std::static_pointer_cast <Packet::Tag5> (find_signing_key(args.pri));
    if (!signer) {
        // "Error: No Private Key for signing found.\n";
        return DetachedSignature();
    }

    // Check if key has been revoked
    const int rc = Revoke::check(args.pri);
    if (rc == true) {
        // "Error: Key " + hexlify(signer -> get_keyid()) + " has been revoked. Nothing done.\n";
        return DetachedSignature();
    }
    else if (rc == -1) {
        // "Error: Revoke::check failed.\n";
        return DetachedSignature();
    }

    // create Signature Packet
    Packet::Tag2::Ptr sig = create_sig_packet(args.version, Signature_Type::SIGNATURE_OF_A_BINARY_DOCUMENT, signer -> get_pka(), args.hash, signer -> get_keyid());
    const std::string digest = to_sign_00(binary_to_canonical(data), sig);
    sig -> set_left16(digest.substr(0, 2));
    PKA::Values vals = with_pka(digest, signer -> get_pka(), signer -> decrypt_secret_keys(args.passphrase), signer -> get_mpi(), args.hash);
    if (!vals.size()) {
        // "Error: PKA Signing failed.\n";
        return DetachedSignature();
    }
    sig -> set_mpi(vals);

    DetachedSignature signature;
    signature.set_keys({std::make_pair("Version", "cc")});
    signature.set_packets({sig});

    return signature;
}

// 0x00: Signature of a binary document.
Message binary(const Args & args, const std::string & filename, const std::string & data, const uint8_t compress) {
    if (!args.valid()) {
        // "Error: Bad argument.\n";
        return DetachedSignature();
    }

    // find signing key
    Packet::Tag5::Ptr signer = std::static_pointer_cast <Packet::Tag5> (find_signing_key(args.pri));
    if (!signer) {
        // "Error: No signing key found.\n";
        return Message();
    }

    // create One-Pass Signature Packet
    Packet::Tag4::Ptr tag4 = std::make_shared <Packet::Tag4> ();
    tag4 -> set_type(0);
    tag4 -> set_hash(args.hash);
    tag4 -> set_pka(signer -> get_pka());
    tag4 -> set_keyid(signer -> get_keyid());
    tag4 -> set_last(1); // 1 for no nesting

    // put source data into Literal Data Packet
    Packet::Tag11::Ptr tag11 = std::make_shared <Packet::Tag11> ();
    tag11 -> set_data_format('b');
    tag11 -> set_filename(filename);
    tag11 -> set_time(now());
    tag11 -> set_literal(data);

    // sign data
    Packet::Tag2::Ptr sig = create_sig_packet(args.version, Signature_Type::SIGNATURE_OF_A_BINARY_DOCUMENT, signer -> get_pka(), args.hash, signer -> get_keyid());
    const std::string digest = to_sign_00(binary_to_canonical(tag11 -> get_literal()), sig);
    sig -> set_left16(digest.substr(0, 2));
    PKA::Values vals = with_pka(digest, signer -> get_pka(), signer -> decrypt_secret_keys(args.passphrase), signer -> get_mpi(), args.hash);
    if (!vals.size()) {
        // "Error: PKA Signing failed.\n";
        return Message();
    }
    sig -> set_mpi(vals);

    // put everything together
    Message signature;
    signature.set_keys({std::make_pair("Version", "cc")});
    signature.set_packets({tag4, tag11, sig});

    if (compress) { // only use a Compressed Data Packet if compression was used; don't bother for uncompressed data
        Packet::Tag8 tag8;
        tag8.set_header_format(Packet::HeaderFormat::NEW);
        tag8.set_data(signature.raw());
        tag8.set_comp(compress);
        std::string raw = tag8.write();
        signature = Message(raw);
    }

    return signature;
}

// 0x01: Signature of a canonical text document.
CleartextSignature cleartext_signature(const Args & args, const std::string & text) {
    if (!args.valid()) {
        // "Error: Bad argument.\n";
        return CleartextSignature();
    }

    // find signing key
    Packet::Tag5::Ptr signer = std::static_pointer_cast <Packet::Tag5> (find_signing_key(args.pri));
    if (!signer) {
        // "Error: No signing key found.\n";
        return CleartextSignature();
    }

    // create signature
    Packet::Tag2::Ptr sig = create_sig_packet(args.version, Signature_Type::SIGNATURE_OF_A_CANONICAL_TEXT_DOCUMENT, signer -> get_pka(), args.hash, signer -> get_keyid());
    const std::string digest = to_sign_01(CleartextSignature::data_to_text(text), sig);
    sig -> set_left16(digest.substr(0, 2));
    PKA::Values vals = with_pka(digest, signer -> get_pka(), signer -> decrypt_secret_keys(args.passphrase), signer -> get_mpi(), args.hash);
    if (!vals.size()) {
        // "Error: PKA Signing failed.\n";
        return CleartextSignature();
    }
    sig -> set_mpi(vals);

    // put signature into Detached Signature
    DetachedSignature signature;
    signature.set_keys({std::make_pair("Version", "cc")});
    signature.set_packets({sig});

    // put signature under cleartext
    CleartextSignature message;
    message.set_hash_armor_header({std::make_pair("Hash", Hash::NAME.at(args.hash))});
    message.set_message(text);
    message.set_sig(signature);

    return message;
}

// 0x02: Standalone signature.

// 0x10: Generic certification of a User ID and Public-Key packet.
// 0x11: Persona certification of a User ID and Public-Key packet.
// 0x12: Casual certification of a User ID and Public-Key packet.
// 0x13: Positive certification of a User ID and Public-Key packet.
Packet::Tag2::Ptr primary_key(const Packet::Tag5::Ptr signer_signing_key, const std::string & passphrase, const Packet::Key::Ptr & signee_primary_key, const Packet::User::Ptr & signee_id, Packet::Tag2::Ptr & sig) {
    if (!signer_signing_key) {
        // "Error: No signing key given.\n";
        return nullptr;
    }

    if (!signee_primary_key) {
        // "Error: No signee primary key given.\n";
        return nullptr;
    }

    if (!Packet::is_primary_key(signee_primary_key -> get_tag())) {
        // "Error: signee key is not a primary key.\n";
        return nullptr;
    }

    if (!signee_id) {
        // "Error: No User Identifier given.\n";
        return nullptr;
    }

    if (!sig) {
        // "Error: No signature data given.\n";
        return nullptr;
    }

    if (!Signature_Type::is_certification(sig -> get_type())) {
        // "Error: Invalid Certification Value: 0x" + makehex(sig -> get_type(), 2) + "\n";
        return nullptr;
    }

    const std::string digest = to_sign_cert(sig -> get_type(), signee_primary_key, signee_id, sig);
    sig -> set_left16(digest.substr(0, 2));
    PKA::Values vals = with_pka(digest, signer_signing_key -> get_pka(), signer_signing_key -> decrypt_secret_keys(passphrase), signer_signing_key -> get_mpi(), sig -> get_hash());
    if (!vals.size()) {
        // "Error: PKA Signing failed.\n";
        return nullptr;
    }
    sig -> set_mpi(vals);

    return sig;
}

PublicKey primary_key(const Args & args, const PublicKey & signee, const std::string & user, const uint8_t cert) {
    if (!args.valid()) {
        // "Error: Bad arguments.\n";
        return PublicKey();
    }

    // check if signer has already been revoked
    if (Revoke::check(args.pri)) {
        // "Error: Signer key is revoked. Nothing done.\n";
        return PublicKey();
    }

    if (!signee.meaningful()) {
        // "Error: Bad signee key.\n";
        return PublicKey();
    }

    if (Revoke::check(signee)) {
        // "Error: Signer key is revoked. Nothing done.\n";
        return PublicKey();
    }

    if (!Signature_Type::is_certification(cert)) {
        // "Error: Invalid Certification Value: 0x" + makehex(cert, 2) + "\n";
        return PublicKey();
    }

    // get signer's signing packet
    Packet::Tag5::Ptr signer_signing_key = std::static_pointer_cast <Packet::Tag5> (find_signing_key(args.pri));
    if (!signer_signing_key) {
        // "Error: Signing key not found.\n";
        return PublicKey();
    }

    const PGP::Packets & signee_packets = signee.get_packets();
    Packet::Key::Ptr signee_primary_key = std::static_pointer_cast <Packet::Key> (signee_packets[0]);
    Packet::User::Ptr signee_id = nullptr;

    // find matching user identifier
    PGP::Packets::size_type i = 1;
    do{
        // find matching user identifier
        if (Packet::is_user(signee_packets[i] -> get_tag())) {
            // if the packet is a User ID
            if (signee_packets[i] -> get_tag() == Packet::USER_ID) {
                Packet::Tag13::Ptr tag13 = std::static_pointer_cast <Packet::Tag13> (signee_packets[i]);
                if (tag13 -> get_contents().find(user) != std::string::npos) {
                    signee_id = tag13;
                    i++; // go past User ID packet
                    break;
                }
            }
            // else if (signee_packets[i] -> get_tag() == Packet::USER_ATTRIBUTE) {}
        }

        i++;
    } while (i < signee_packets.size());

    if (!signee_id) {
        // "Error: No Signee user ID found.\n";
        return PublicKey();
    }

    // search through signatures to see signer has already certified this user
    while (i < signee_packets.size() && (signee_packets[i] -> get_tag() == Packet::SIGNATURE)) {
        const int rc = Verify::primary_key(signer_signing_key, signee_primary_key, signee_id, std::static_pointer_cast <Packet::Tag2> (signee_packets[i]));
        if (rc == -1) {
            // "Error: Signature verification failure.\n";
            return PublicKey();
        }
        else if (rc == true) {
            std::cerr << "Warning: Primary Key and User ID have already been signed by " << args.pri << std::endl;
            return signee;
        }

        i++;
    }

    // sign key
    Packet::Tag2::Ptr sig = create_sig_packet(args.version, cert, signer_signing_key -> get_pka(), args.hash, signer_signing_key -> get_keyid());
    if (!sig) {
        // "Error: Signature packet generation failure.\n";
        return PublicKey();
    }

    sig = primary_key(signer_signing_key, args.passphrase, signee_primary_key, signee_id, sig);
    if (!sig) {
        // "Error: Signature calculation failure.\n";
        return PublicKey();
    }

    // Create output key
    PublicKey out(signee);
    PGP::Packets out_packets;

    // push all packets up to and including out packet into new packets
    PGP::Packets::size_type j;
    for(j = 0; j < (signee_packets.size()) && (j < i); j++) {
        out_packets.push_back(signee_packets[j]);
    }

    // append signature to signatures following key
    out_packets.push_back(sig);

    // append rest of packets
    while (j < signee_packets.size()) {
        out_packets.push_back(signee_packets[j++]);
    }

    out.set_packets(out_packets);

    return out;
}

// 0x18: Subkey Binding Signature
Packet::Tag2::Ptr subkey_binding(const Packet::Tag5::Ptr & primary, const std::string & passphrase, const Packet::Tag7::Ptr & sub, Packet::Tag2::Ptr & sig) {
    if (!primary) {
        // "Error: No primary key.\n";
        return nullptr;
    }

    if (!sub) {
        // "Error: No subkey.\n";
        return nullptr;
    }

    if (!sig) {
        // "Error: No signature.\n";
        return nullptr;
    }

    const std::string digest = to_sign_18(primary, sub, sig);
    sig -> set_left16(digest.substr(0, 2));
    PKA::Values vals = with_pka(digest, primary -> get_pka(), primary -> decrypt_secret_keys(passphrase), primary -> get_mpi(), sig -> get_hash());
    if (!vals.size()) {
        // "Error: PKA Signing failed.\n";
        return nullptr;
    }
    sig -> set_mpi(vals);

    return sig;
}

// 0x19: Primary Key Binding Signature
Packet::Tag2::Ptr primary_key_binding(const Args & args, const PublicKey & signee) {
    if (!args.valid()) {
        // "Error: Bad arguments.\n";
        return nullptr;
    }

    // find signing subkey
    Packet::Tag5::Ptr subkey = std::static_pointer_cast <Packet::Tag5> (find_signing_key(args.pri));
    if (!subkey) {
        // "Error: No Signing Subkey found.\n";
        return nullptr;
    }

    // move subkey data into subkey packet
    Packet::Tag7::Ptr signer_subkey = std::static_pointer_cast <Packet::Tag7> (subkey);

    // get signee primary and subkey
    Packet::Tag6::Ptr signee_primary = nullptr;
    for(Packet::Tag::Ptr const & p : signee.get_packets()) {
        if (p -> get_tag() == Packet::PUBLIC_KEY) {
            signee_primary = std::static_pointer_cast <Packet::Tag6> (p);
            break;
        }
    }

    if (!signee_primary) {
        // "Error: Signee Primary Key not found.\n";
        return nullptr;
    }

    Packet::Tag14::Ptr signee_subkey = nullptr;
    for(Packet::Tag::Ptr const & p : args.pri.get_packets()) {
        if (p -> get_tag() == Packet::PUBLIC_SUBKEY) {
            signee_subkey = std::static_pointer_cast <Packet::Tag14> (p);
            break;
        }
    }

    if (!signee_subkey) {
        // "Error: Singee Subkey not found.\n";
        return nullptr;
    }

    Packet::Tag2::Ptr sig = create_sig_packet(args.version, Signature_Type::PRIMARY_KEY_BINDING_SIGNATURE, signer_subkey -> get_pka(), args.hash, signer_subkey -> get_keyid());
    if (!sig) {
        // "Error: Signature packet generation failure.\n";
        return nullptr;
    }

    const std::string digest = to_sign_18(signee_primary, signer_subkey, sig);
    sig -> set_left16(digest.substr(0, 2));
    PKA::Values vals = with_pka(digest, signer_subkey -> get_pka(), signer_subkey -> decrypt_secret_keys(args.passphrase), signer_subkey -> get_mpi(), args.hash);
    if (!vals.size()) {
        // "Error: PKA Signing failed.\n";
        return nullptr;
    }
    sig -> set_mpi(vals);

    return sig;
}

DetachedSignature timestamp(const Args & args, const uint32_t time) {
    if (!args.valid()) {
        // "Error: Bad arguments.\n";
        return DetachedSignature();
    }

    Packet::Tag5::Ptr signer = std::static_pointer_cast <Packet::Tag5> (find_signing_key(args.pri));
    if (!signer) {
        // "Error: Signing key not found.\n";
        return DetachedSignature();
    }

    Packet::Tag2::Ptr sig = create_sig_packet(args.version, Signature_Type::TIMESTAMP_SIGNATURE, signer -> get_pka(), args.hash, signer -> get_keyid());
    if (!sig) {
        // "Error: Signature packet generation failure.\n";
        return DetachedSignature();
    }

    Subpacket::Tag2::Sub2::Ptr tag2sub2 = std::make_shared <Subpacket::Tag2::Sub2> ();
    tag2sub2 -> set_time(time);
    sig -> set_hashed_subpackets({tag2sub2});

    const std::string digest = to_sign_40(sig);
    sig -> set_left16(digest.substr(0, 2));
    PKA::Values vals = with_pka(digest, signer -> get_pka(), signer -> decrypt_secret_keys(args.passphrase), signer -> get_mpi(), args.hash);
    if (!vals.size()) {
        // "Error: PKA Signing failed.\n";
        return DetachedSignature();
    }
    sig -> set_mpi(vals);

    DetachedSignature timestamp;
    timestamp.set_keys({std::make_pair("Version", "cc")});
    timestamp.set_packets({sig});

    return timestamp;
}

}
}


text:
// runV0ChCorrelations.C
//
// Running macro for AliAnalysisTaskV0ChCorrelations task
// Example of usage:  .L runV0ChCorrelations.C
//                     runV0ChCorrelations("proof","full)
//
class AliAnalysisGrid;

//______________________________________________________________________________
void runV0ChCorrelations(
         const char* runtype = "proof", // local, proof or grid
         const char *gridmode = "full", // Set the run mode (can be "full", "test", "offline", "submit" or "terminate"). Full & Test work for proof
         const bool bMCtruth = 0, // 1 = MCEvent handler is on (MC truth), 0 = MCEvent handler is off (MC reconstructed/real data)
         const bool bMCphyssel = 0, // 1 = looking at MC truth or reconstructed, 0 = looking at real data
         const Long64_t nentries = 1234567890, // for local and proof mode, ignored in grid mode. Set to 1234567890 for all events.
         const Long64_t firstentry = 0, // for local and proof mode, ignored in grid mode
         //const char *proofdataset = "/alice/data/LHC10h_000138534_p2_AOD049", // path to dataset on proof cluster, for proof analysis
         const char *proofdataset = "/alice/data/LHC11h_2_000169858_p2_AOD095", // path to dataset on proof cluster, for proof analysis

		 const char *proofcluster = "alice-caf.cern.ch", // which proof cluster to use in proof mode
         const char *taskname = "V0ChCorrelations_task" // sets name of grid generated macros
         )
{
    // check run type
    if(runtype != "local" && runtype != "proof" && runtype != "grid"){
        Printf("\n\tIncorrect run option, check first argument of run macro");
        Printf("\tint runtype = local, proof or grid\n");
        return;
    }
    Printf("%s analysis chosen",runtype);

    // load libraries
    gSystem->Load("libCore");
    gSystem->Load("libGeom");
    gSystem->Load("libVMC");
    gSystem->Load("libPhysics");
    gSystem->Load("libTree");
    gSystem->Load("libSTEERBase");
    gSystem->Load("libESD");
    gSystem->Load("libAOD");
    gSystem->Load("libANALYSIS");
    gSystem->Load("libOADB");
    gSystem->Load("libANALYSISalice");

    // add aliroot indlude path
    gROOT->ProcessLine(Form(".include %s/include",gSystem->ExpandPathName("$ALICE_ROOT")));
    gROOT->SetStyle("Plain");

    // analysis manager
    AliAnalysisManager* mgr = new AliAnalysisManager(taskname);

    // create the alien handler and attach it to the manager
    AliAnalysisGrid *plugin = CreateAlienHandler(taskname, gridmode, proofcluster, proofdataset);
    mgr->SetGridHandler(plugin);

    //AliVEventHandler* iH = new AliESDInputHandler();
    AliAODInputHandler* iH = new AliAODInputHandler();
    mgr->SetInputEventHandler(iH);

    // mc event handlerrunEx01.C
    /*if(bMCtruth) {
        AliMCEventHandler* mchandler = new AliMCEventHandler();
        // Not reading track references
        mchandler->SetReadTR(kFALSE);
        mgr->SetMCtruthEventHandler(mchandler);
    } */

	gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C");
	AliAnalysisTask *pidtask = AddTaskPIDResponse(kFALSE,kTRUE);

    // create task
    gROOT->LoadMacro("AliAnalysisTaskV0ChCorrelations.cxx+g");
    gROOT->LoadMacro("AddTaskV0ChCorrelations.C");
	AliAnalysisTaskV0ChCorrelations *taskV0 = AddTaskV0ChCorrelations(kFALSE);

    // enable debug printouts
    mgr->SetDebugLevel(2);
    mgr->SetNSysInfo(100);
    if (!mgr->InitAnalysis()) return;
    mgr->PrintStatus();

    // start analysis
    Printf("Starting Analysis....");
    mgr->StartAnalysis(runtype,nentries,firstentry);
}

//______________________________________________________________________________
AliAnalysisGrid* CreateAlienHandler(const char *taskname, const char *gridmode, const char *proofcluster, const char *proofdataset)
{
    AliAnalysisAlien *plugin = new AliAnalysisAlien();
    // Set the run mode (can be "full", "test", "offline", "submit" or "terminate")
    plugin->SetRunMode(gridmode);

    // Set versions of used packages
    plugin->SetAPIVersion("V1.1x");
    plugin->SetROOTVersion("v5-34-01-1");
    plugin->SetAliROOTVersion("v5-03-66-AN");

    // Method 1: Create automatically XML collections using alien 'find' command.
    // Define production directory LFN
    //plugin->SetGridDataDir("/alice/data/2010/LHC10h");
    plugin->SetGridDataDir("/alice/data/2011/LHC11h_2");
    // On real reconstructed data:
    // plugin->SetGridDataDir("/alice/data/2009/LHC09d");
    // Data pattern for reconstructed data
    plugin->SetDataPattern("*ESDs/pass2/AOD095/*AOD.root"); // LHC11h data
    //    plugin->SetDataPattern("ESDs/pass2/AOD038/*AliAOD.root"); // CHECK LATEST PASS OF DATA SET IN ALIENSH
    plugin->SetRunPrefix("000");   // real data
    // ...then add run numbers to be considered

    //plugin->AddRunNumber(139038);
    plugin->AddRunNumber(169858);
    //plugin->SetRunRange(146686,146860);

    plugin->SetNrunsPerMaster(1); // 1
    plugin->SetOutputToRunNo();
    // comment out the next line when using the "terminate" option, unless
    // you want separate merged files for each run
    //plugin->SetMergeViaJDL();

    // Method 2: Declare existing data files (raw collections, xml collections, root file)
    // If no path mentioned data is supposed to be in the work directory (see SetGridWorkingDir())
    // XML collections added via this method can be combined with the first method if
    // the content is compatible (using or not tags)
    //   plugin->AddDataFile("tag.xml");
    //   plugin->AddDataFile("/alice/data/2008/LHC08c/000057657/raw/Run57657.Merged.RAW.tag.root");

    // Define alien work directory where all files will be copied. Relative to alien $HOME.
    plugin->SetGridWorkingDir(taskname);

    // Declare alien output directory. Relative to working directory.
    plugin->SetGridOutputDir("outLHC11h"); // In this case will be $HOME/taskname/out

    // Declare the analysis source files names separated by blancs. To be compiled runtime
    // using ACLiC on the worker nodes.
    plugin->SetAnalysisSource("AliAnalysisTaskV0ChCorrelations.cxx");

    // Declare all libraries (other than the default ones for the framework. These will be
    // loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here.
    plugin->SetAdditionalLibs("AliAnalysisTaskV0ChCorrelations.h AliAnalysisTaskV0ChCorrelations.cxx");

    // Declare the output file names separated by blancs.
    // (can be like: file.root or file.root@ALICE::Niham::File)
    // To only save certain files, use SetDefaultOutputs(kFALSE), and then
    // SetOutputFiles("list.root other.filename") to choose which files to save
    plugin->SetDefaultOutputs(kFALSE);
    plugin->SetOutputFiles("list.grid.v0ch.root");

    // Optionally set a name for the generated analysis macro (default MyAnalysis.C)
    plugin->SetAnalysisMacro(Form("%s.C",taskname));

    // Optionally set maximum number of input files/subjob (default 100, put 0 to ignore)
    plugin->SetSplitMaxInputFileNumber(100);

    // Optionally modify the executable name (default analysis.sh)
    plugin->SetExecutable(Form("%s.sh",taskname));

    // set number of test files to use in "test" mode
    plugin->SetNtestFiles(10);

    // Optionally resubmit threshold.
    plugin->SetMasterResubmitThreshold(90);

    // Optionally set time to live (default 30000 sec)
    plugin->SetTTL(30000);

    // Optionally set input format (default xml-single)
    plugin->SetInputFormat("xml-single");

    // Optionally modify the name of the generated JDL (default analysis.jdl)
    plugin->SetJDLName(Form("%s.jdl",taskname));

    // Optionally modify job price (default 1)
    plugin->SetPrice(1);

    // Optionally modify split mode (default 'se')
    plugin->SetSplitMode("se");

    //----------------------------------------------------------
    //---      PROOF MODE SPECIFIC SETTINGS         ------------
    //----------------------------------------------------------
    // Proof cluster
    plugin->SetProofCluster(proofcluster);
    // Dataset to be used
    plugin->SetProofDataSet(proofdataset);
    // May need to reset proof. Supported modes: 0-no reset, 1-soft, 2-hard
    plugin->SetProofReset(0);
    // May limit number of workers
    plugin->SetNproofWorkers(0);
    // May limit the number of workers per slave
    plugin->SetNproofWorkersPerSlave(1);
    // May use a specific version of root installed in proof
    //plugin->SetRootVersionForProof("current");
    plugin->SetRootVersionForProof("VO_ALICE@ROOT::v5-34-01-1");
    // May set the aliroot mode. Check http://aaf.cern.ch/node/83
    plugin->SetAliRootMode("default"); // Loads AF libs by default
    // May request ClearPackages (individual ClearPackage not supported)
    plugin->SetClearPackages(kFALSE);
    // Plugin test mode works only providing a file containing test file locations, used in "local" mode also
    plugin->SetFileForTestMode("LocalData_PbPb_LHC10h.txt"); // file should contain path name to a local directory containg *ESDs.root etc
    // Request connection to alien upon connection to grid
    plugin->SetProofConnectGrid(kFALSE);
    // Other PROOF specific parameters
    plugin->SetProofParameter("PROOF_UseMergers","-1");
    printf("Using: PROOF_UseMergers   : %s\n", plugin->GetProofParameter("PROOF_UseMergers"));
    return plugin;
}


text:
Clazz.declarePackage ("J.adapter.readers.xtal");
Clazz.load (["J.adapter.smarter.AtomSetCollectionReader"], "J.adapter.readers.xtal.VaspPoscarReader", ["java.lang.Float", "JU.Lst", "$.M3", "$.PT", "$.SB", "J.api.JmolAdapter", "JU.Logger", "$.Parser"], function () {
c$ = Clazz.decorateAsClass (function () {
this.atomLabels = null;
this.haveAtomLabels = true;
this.atomsLabeledInline = false;
this.scaleFac = 0;
this.ac = 0;
this.title = null;
this.quiet = false;
this.defaultLabels = null;
this.elementLabel = null;
this.radiusPt = -2147483648;
this.elementPt = -2147483648;
Clazz.instantialize (this, arguments);
}, J.adapter.readers.xtal, "VaspPoscarReader", J.adapter.smarter.AtomSetCollectionReader);
Clazz.overrideMethod (c$, "initializeReader",
function () {
this.isPrimitive = true;
this.readStructure (null);
this.continuing = false;
});
Clazz.defineMethod (c$, "readStructure",
function (titleMsg) {
this.title = this.rd ().trim ();
var pt = this.title.indexOf ("--params");
if ((pt = this.title.indexOf ("& ", pt + 1)) >= 0) {
this.latticeType = this.title.substring (pt + 2, pt + 3);
JU.Logger.info ("AFLOW lattice:" + this.latticeType + " title=" + this.title);
}this.readUnitCellVectors ();
this.readMolecularFormula ();
this.readCoordinates ();
this.asc.setAtomSetName (this.title + (titleMsg == null ? "" : "[" + titleMsg + "]"));
}, "~S");
Clazz.overrideMethod (c$, "finalizeSubclassReader",
function () {
if (!this.haveAtomLabels && !this.atomsLabeledInline) this.appendLoadNote ("VASP POSCAR reader using pseudo atoms Al B C Db...");
this.finalizeReaderASCR ();
});
Clazz.defineMethod (c$, "readUnitCellVectors",
function () {
this.setSpaceGroupName ("P1");
this.setFractionalCoordinates (true);
this.scaleFac = this.parseFloatStr (this.rdline ().trim ());
var isVolume = (this.scaleFac < 0);
if (isVolume) this.scaleFac = Math.pow (-this.scaleFac, 0.3333333333333333);
var unitCellData =  Clazz.newFloatArray (9, 0);
var s = this.rdline () + " " + this.rdline () + " " + this.rdline ();
JU.Parser.parseStringInfestedFloatArray (s, null, unitCellData);
if (isVolume) {
var m = JU.M3.newA9 (unitCellData);
this.scaleFac /= m.determinant3 ();
}if (this.scaleFac != 1) for (var i = 0; i < unitCellData.length; i++) unitCellData[i] *= this.scaleFac;

this.addExplicitLatticeVector (0, unitCellData, 0);
this.addExplicitLatticeVector (1, unitCellData, 3);
this.addExplicitLatticeVector (2, unitCellData, 6);
});
Clazz.defineMethod (c$, "readMolecularFormula",
function () {
if (this.elementLabel == null) this.elementLabel = JU.PT.getTokens (this.discardLinesUntilNonBlank ());
var elementCounts;
if (JU.PT.parseInt (this.elementLabel[0]) == -2147483648) {
this.atomsLabeledInline = false;
elementCounts = JU.PT.getTokens (this.rdline ());
while (this.line != null && (elementCounts.length == 0 || this.parseIntStr (elementCounts[0]) == -2147483648)) elementCounts = JU.PT.getTokens (this.rdline ());

} else {
elementCounts = this.elementLabel;
this.elementLabel = JU.PT.split (this.title, " ");
if (this.elementLabel.length != elementCounts.length || this.elementLabel[0].length > 2) {
this.elementLabel = JU.PT.split ("Al B C Db Eu F Ga Hf I K Li Mn N O P Ru S Te U V W Xe Yb Zn", " ");
this.haveAtomLabels = false;
}}var labels = this.elementLabel;
var mf =  new JU.SB ();
this.atomLabels =  new JU.Lst ();
this.ac = 0;
for (var i = 0; i < elementCounts.length; i++) {
var n = Integer.parseInt (elementCounts[i]);
this.ac += n;
var label = labels[i];
mf.append (" ").append (label).appendI (n);
for (var j = n; --j >= 0; ) this.atomLabels.addLast (label);

}
var s = mf.toString ();
if (!this.quiet) this.appendLoadNote (this.ac + " atoms identified for" + s);
this.asc.newAtomSet ();
this.asc.setAtomSetName (s);
});
Clazz.defineMethod (c$, "readCoordinates",
function () {
var isSelective = this.discardLinesUntilNonBlank ().toLowerCase ().contains ("selective");
if (isSelective) this.rd ();
var isCartesian = (this.line.toLowerCase ().contains ("cartesian"));
if (isCartesian) this.setFractionalCoordinates (false);
for (var i = 0; i < this.ac; i++) {
var radius = NaN;
var tokens = JU.PT.getTokens (this.rdline ());
if (this.radiusPt == -2147483648) {
for (var j = tokens.length; --j > 2; ) if (tokens[j].equals ("radius")) {
this.radiusPt = j + 1;
} else if (this.getElement (tokens[j]) != null) {
this.elementPt = j;
this.atomsLabeledInline = true;
}
}if (this.radiusPt >= 0) radius = this.parseFloatStr (tokens[this.radiusPt]);
var label = (this.atomsLabeledInline ? tokens[this.elementPt] : this.atomLabels.get (i));
if (isCartesian) for (var j = 0; j < 3; j++) tokens[j] = "" + this.parseFloatStr (tokens[j]) * this.scaleFac;

var atom = this.addAtomXYZSymName (tokens, 0, null, label);
if (!Float.isNaN (radius)) atom.radius = radius * this.scaleFac;
if (this.asc.bsAtoms != null) this.asc.bsAtoms.set (atom.index);
}
});
Clazz.defineMethod (c$, "getElement",
function (token) {
var s = null;
switch (token.length) {
default:
s = (token.length > 2 ? token.substring (0, 2) : null);
if (s != null && J.api.JmolAdapter.getElementNumber (s) >= 0) return s;
case 1:
if (J.api.JmolAdapter.getElementNumber (s = token.substring (0)) >= 0) return s;
case 0:
return null;
}
}, "~S");
Clazz.defineMethod (c$, "rdline",
function () {
this.rd ();
if (this.line != null && this.line.startsWith ("[")) this.line = this.line.substring (this.line.indexOf ("]") + 1).trim ();
return this.line;
});
});


text:
"use strict";

describe("loglevel included via node", function () {
    it("is included successfully", function () {
        expect(require('../lib/loglevel')).not.toBeUndefined();
    });

    it("allows setting the logging level", function () {
        var log = require('../lib/loglevel');

        log.setLevel(log.levels.TRACE);
        log.setLevel(log.levels.DEBUG);
        log.setLevel(log.levels.INFO);
        log.setLevel(log.levels.WARN);
        log.setLevel(log.levels.ERROR);
    });

    it("successfully logs", function () {
        var log = require('../lib/loglevel');
        console.info = jasmine.createSpy("info");

        log.setLevel(log.levels.INFO);
        log.info("test message");

        expect(console.info).toHaveBeenCalledWith("test message");
    });

    it("supports using symbols as names", function() {
        var log = require('../lib/loglevel');

        var s1 = Symbol("a-symbol");
        var s2 = Symbol("a-symbol");

        var logger1 = log.getLogger(s1);
        var defaultLevel = logger1.getLevel();
        logger1.setLevel(log.levels.TRACE);

        var logger2 = log.getLogger(s2);

        // Should be unequal: same name, but different symbol instances
        expect(logger1).not.toEqual(logger2);
        expect(logger2.getLevel()).toEqual(defaultLevel);
    });
});