text:
#ifndef _ALLJOYN_REMOTEBUSOBJECT_H
#define _ALLJOYN_REMOTEBUSOBJECT_H
/**
 * @file
 * This file defines the class ProxyBusObject.
 * The ProxyBusObject represents a single object registered  registered on the bus.
 * ProxyBusObjects are used to make method calls on these remotely located DBus objects.
 */

/******************************************************************************
 * Copyright AllSeen Alliance. All rights reserved.
 *
 *    Permission to use, copy, modify, and/or distribute this software for any
 *    purpose with or without fee is hereby granted, provided that the above
 *    copyright notice and this permission notice appear in all copies.
 *
 *    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *    WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *    MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *    ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 ******************************************************************************/

#include <qcc/platform.h>
#include <set>
#include <qcc/String.h>
#include <alljoyn/InterfaceDescription.h>
#include <alljoyn/MessageReceiver.h>
#include <alljoyn/MsgArg.h>
#include <alljoyn/Message.h>
#include <alljoyn/Session.h>

#include <alljoyn/Status.h>

namespace qcc {
/** @internal Forward references */
class Mutex;
class Condition;
class Thread;
}

namespace ajn {

/** @internal Forward references */
class BusAttachment;

/**
 * Each %ProxyBusObject instance represents a single DBus/AllJoyn object registered
 * somewhere on the bus. ProxyBusObjects are used to make method calls on these
 * remotely located DBus objects.
 */
class ProxyBusObject : public MessageReceiver {
    friend class XmlHelper;
    friend class AllJoynObj;
    friend class MatchRuleTracker;

  public:

    /**
     * The default timeout for method calls (25 seconds)
     */
    static const uint32_t DefaultCallTimeout = 25000;

    /**
     * Base class used as a container for callback typedefs
     *
     * @internal Do not use this pattern for creating new public Async versions of the APIs.  See
     * the PropertiesChangedListener class below for an example of how to add new async APIs.
     */
    class Listener {
      public:
        /**
         * Callback registered with IntrospectRemoteObjectAsync()
         *
         * @param status    ER_OK if successful or an error status indicating the reason for the failure.
         * @param obj       Remote bus object that was introspected
         * @param context   Context passed in IntrospectRemoteObjectAsync()
         */
        typedef void (ProxyBusObject::Listener::* IntrospectCB)(QStatus status, ProxyBusObject* obj, void* context);

        /**
         * Callback registered with GetPropertyAsync()
         *
         * @param status    - ER_OK if the property get request was successfull or:
         *                  - #ER_BUS_OBJECT_NO_SUCH_INTERFACE if the specified interfaces does not exist on the remote object.
         *                  - #ER_BUS_NO_SUCH_PROPERTY if the property does not exist
         *                  - Other error status codes indicating the reason the get request failed.
         * @param obj       Remote bus object that was introspected
         * @param value     If status is ER_OK a MsgArg containing the returned property value
         * @param context   Caller provided context passed in to GetPropertyAsync()
         */
        typedef void (ProxyBusObject::Listener::* GetPropertyCB)(QStatus status, ProxyBusObject* obj, const MsgArg& value, void* context);

        /**
         * Callback registered with GetAllPropertiesAsync()
         *
         * @param status    - ER_OK if the get all properties request was successfull or:
         *                  - #ER_BUS_OBJECT_NO_SUCH_INTERFACE if the specified interfaces does not exist on the remote object.
         *                  - Other error status codes indicating the reason the get request failed.
         * @param obj         Remote bus object that was introspected
         * @param[out] values If status is ER_OK an array of dictionary entries, signature "a{sv}" listing the properties.
         * @param context     Caller provided context passed in to GetPropertyAsync()
         */
        typedef void (ProxyBusObject::Listener::* GetAllPropertiesCB)(QStatus status, ProxyBusObject* obj, const MsgArg& values, void* context);

        /**
         * Callback registered with SetPropertyAsync()
         *
         * @param status    - ER_OK if the property was successfully set or:
         *                  - #ER_BUS_OBJECT_NO_SUCH_INTERFACE if the specified interfaces does not exist on the remote object.
         *                  - #ER_BUS_NO_SUCH_PROPERTY if the property does not exist
         *                  - Other error status codes indicating the reason the set request failed.
         * @param obj       Remote bus object that was introspected
         * @param context   Caller provided context passed in to SetPropertyAsync()
         */
        typedef void (ProxyBusObject::Listener::* SetPropertyCB)(QStatus status, ProxyBusObject* obj, void* context);
    };

    /**
     * Pure virtual base class for the Properties Changed listener.
     */
    class PropertiesChangedListener {
      public:
        virtual ~PropertiesChangedListener() { }

        /**
         * Callback to receive property changed events.
         *
         * @param obj           Remote bus object that owns the property that changed.
         * @param ifaceName     Name of the interface that defines the property.
         * @param changed       Property values that changed as an array of dictionary entries, signature "a{sv}".
         * @param invalidated   Properties whose values have been invalidated, signature "as".
         * @param context       Caller provided context passed in to RegisterPropertiesChangedListener
         */
        virtual void PropertiesChanged(ProxyBusObject& obj,
                                       const char* ifaceName,
                                       const MsgArg& changed,
                                       const MsgArg& invalidated,
                                       void* context) = 0;
    };

    /**
     * Create a default (unusable) %ProxyBusObject.
     *
     * This constructor exist only to support assignment.
     */
    ProxyBusObject();

    /**
     * Create an empty proxy object that refers to an object at given remote service name. Note
     * that the created proxy object does not contain information about the interfaces that the
     * actual remote object implements with the exception that org.freedesktop.DBus.Peer
     * interface is special-cased (per the DBus spec) and can always be called on any object. Nor
     * does it contain information about the child objects that the actual remote object might
     * contain. The security mode can be specified if known or can be derived from the XML
     * description.
     *
     * To fill in this object with the interfaces and child object names that the actual remote
     * object describes in its introspection data, call IntrospectRemoteObject() or
     * IntrospectRemoteObjectAsync().
     *
     * If the remote service name is set to a unique name, then both
     * GetServiceName() and GetUniqueName() will return the unique name.
     *
     * @param bus        The bus.
     * @param service    The remote service name (well-known or unique).
     * @param path       The absolute (non-relative) object path for the remote object.
     * @param sessionId  The session id the be used for communicating with remote object.
     * @param secure     The security mode for the remote object.
     */
    ProxyBusObject(BusAttachment& bus, const char* service, const char* path, SessionId sessionId, bool secure = false);

    /**
     * Create an empty proxy object that refers to an object at given remote service name. Note
     * that the created proxy object does not contain information about the interfaces that the
     * actual remote object implements with the exception that org.freedesktop.DBus.Peer
     * interface is special-cased (per the DBus spec) and can always be called on any object. Nor
     * does it contain information about the child objects that the actual remote object might
     * contain. The security mode can be specified if known or can be derived from the XML
     * description.
     *
     * To fill in this object with the interfaces and child object names that the actual remote
     * object describes in its introspection data, call IntrospectRemoteObject() or
     * IntrospectRemoteObjectAsync().
     *
     * This version is primarily used during introspection where the
     * unique name is known.  If, when creating the ProxyBusObject,
     * both an alias is known and the unique name is known, then use
     * this constructor.  Note, that the only the service name is used
     * when generating messages.
     *
     * @param bus        The bus.
     * @param service    The remote service name (well-known or unique).
     * @param uniqueName The remote service's unique name.
     * @param path       The absolute (non-relative) object path for the remote object.
     * @param sessionId  The session id the be used for communicating with remote object.
     * @param secure     The security mode for the remote object.
     */
    ProxyBusObject(BusAttachment& bus, const char* service, const char* uniqueName, const char* path, SessionId sessionId, bool secure = false);

    /**
     *  %ProxyBusObject destructor.
     */
    virtual ~ProxyBusObject();

    /**
     * Return the absolute object path for the remote object.
     *
     * @return Object path
     */
    const qcc::String& GetPath(void) const;

    /**
     * Return the remote service name for this object.
     *
     * @return Service name (typically a well-known service name but may be a unique name)
     */
    const qcc::String& GetServiceName(void) const;

    /**
     * Return the remote unique name for this object.
     *
     * @return Service name (typically a well-known service name but may be a unique name)
     */
    const qcc::String& GetUniqueName(void) const;

    /**
     * Return the session Id for this object.
     *
     * @return Session Id
     */
    SessionId GetSessionId(void) const;

    /**
     * Query the remote object on the bus to determine the interfaces and
     * children that exist. Use this information to populate this proxy's
     * interfaces and children.
     *
     * @param timeout   Timeout specified in milliseconds to wait for a reply
     *
     * @return
     *      - #ER_OK if successful
     *      - An error status otherwise
     */
    QStatus IntrospectRemoteObject(uint32_t timeout = DefaultCallTimeout);

    /**
     * Query the remote object on the bus to determine the interfaces and
     * children that exist. Use this information to populate this object's
     * interfaces and children.
     *
     * This call executes asynchronously. When the introspection response
     * is received from the actual remote object, this ProxyBusObject will
     * be updated and the callback will be called.
     *
     * This call exists primarily to allow introspection of remote objects
     * to be done inside AllJoyn method/signal/reply handlers and ObjectRegistered
     * callbacks.
     *
     * @param listener  Pointer to the object that will receive the callback.
     * @param callback  Method on listener that will be called.
     * @param context   User defined context which will be passed as-is to callback.
     * @param timeout   Timeout specified in milliseconds to wait for a reply
     * @return
     *      - #ER_OK if successful.
     *      - An error status otherwise
     */
    QStatus IntrospectRemoteObjectAsync(ProxyBusObject::Listener* listener, ProxyBusObject::Listener::IntrospectCB callback, void* context, uint32_t timeout = DefaultCallTimeout);

    /**
     * Get a property from an interface on the remote object.
     *
     * @param iface       Name of interface to retrieve property from.
     * @param property    The name of the property to get.
     * @param[out] value  Property value.
     * @param timeout     Timeout specified in milliseconds to wait for a reply
     *
     * @return
     *      - #ER_OK if the property was obtained.
     *      - #ER_BUS_OBJECT_NO_SUCH_INTERFACE if the no such interface on this remote object.
     *      - #ER_BUS_NO_SUCH_PROPERTY if the property does not exist
     */
    QStatus GetProperty(const char* iface, const char* property, MsgArg& value, uint32_t timeout = DefaultCallTimeout) const;

    /**
     * Make an asynchronous request to get a property from an interface on the remote object.
     * The property value is passed to the callback function.
     *
     * @param iface     Name of interface to retrieve property from.
     * @param property  The name of the property to get.
     * @param listener  Pointer to the object that will receive the callback.
     * @param callback  Method on listener that will be called.
     * @param context   User defined context which will be passed as-is to callback.
     * @param timeout   Timeout specified in milliseconds to wait for a reply
     * @return
     *      - #ER_OK if the request to get the property was successfully issued .
     *      - #ER_BUS_OBJECT_NO_SUCH_INTERFACE if the no such interface on this remote object.
     *      - An error status otherwise
     */
    QStatus GetPropertyAsync(const char* iface,
                             const char* property,
                             ProxyBusObject::Listener* listener,
                             ProxyBusObject::Listener::GetPropertyCB callback,
                             void* context,
                             uint32_t timeout = DefaultCallTimeout);

    /**
     * Get all properties from an interface on the remote object.
     *
     * @param iface       Name of interface to retrieve all properties from.
     * @param[out] values Property values returned as an array of dictionary entries, signature "a{sv}".
     * @param timeout     Timeout specified in milliseconds to wait for a reply
     *
     * @return
     *      - #ER_OK if the property was obtained.
     *      - #ER_BUS_OBJECT_NO_SUCH_INTERFACE if the no such interface on this remote object.
     *      - #ER_BUS_NO_SUCH_PROPERTY if the property does not exist
     */
    QStatus GetAllProperties(const char* iface, MsgArg& values, uint32_t timeout = DefaultCallTimeout) const;

    /**
     * Make an asynchronous request to get all properties from an interface on the remote object.
     *
     * @param iface     Name of interface to retrieve property from.
     * @param listener  Pointer to the object that will receive the callback.
     * @param callback  Method on listener that will be called.
     * @param context   User defined context which will be passed as-is to callback.
     * @param timeout   Timeout specified in milliseconds to wait for a reply
     * @return
     *      - #ER_OK if the request to get all properties was successfully issued .
     *      - #ER_BUS_OBJECT_NO_SUCH_INTERFACE if the no such interface on this remote object.
     *      - An error status otherwise
     */
    QStatus GetAllPropertiesAsync(const char* iface,
                                  ProxyBusObject::Listener* listener,
                                  ProxyBusObject::Listener::GetPropertyCB callback,
                                  void* context,
                                  uint32_t timeout = DefaultCallTimeout);

    /**
     * Set a property on an interface on the remote object.
     *
     * @param iface     Remote object's interface on which the property is defined.
     * @param property  The name of the property to set
     * @param value     The value to set
     * @param timeout   Timeout specified in milliseconds to wait for a reply
     *
     * @return
     *      - #ER_OK if the property was set
     *      - #ER_BUS_OBJECT_NO_SUCH_INTERFACE if the specified interfaces does not exist on the remote object.
     *      - #ER_BUS_NO_SUCH_PROPERTY if the property does not exist
     */
    QStatus SetProperty(const char* iface, const char* property, MsgArg& value, uint32_t timeout = DefaultCallTimeout) const;

    /**
     * Make an asynchronous request to set a property on an interface on the remote object.
     * A callback function reports the success or failure of ther operation.
     *
     * @param iface     Remote object's interface on which the property is defined.
     * @param property  The name of the property to set.
     * @param value     The value to set
     * @param listener  Pointer to the object that will receive the callback.
     * @param callback  Method on listener that will be called.
     * @param context   User defined context which will be passed as-is to callback.
     * @param timeout   Timeout specified in milliseconds to wait for a reply
     * @return
     *      - #ER_OK if the request to set the property was successfully issued .
     *      - #ER_BUS_OBJECT_NO_SUCH_INTERFACE if the specified interfaces does not exist on the remote object.
     *      - An error status otherwise
     */
    QStatus SetPropertyAsync(const char* iface,
                             const char* property,
                             MsgArg& value,
                             ProxyBusObject::Listener* listener,
                             ProxyBusObject::Listener::SetPropertyCB callback,
                             void* context,
                             uint32_t timeout = DefaultCallTimeout);

    /**
     * Helper function to sychronously set a uint32 property on the remote object.
     *
     * @param iface     Remote object's interface on which the property is defined.
     * @param property  The name of the property to set
     * @param u         The uint32 value to set
     * @param timeout   Timeout specified in milliseconds to wait for a reply
     *
     * @return
     *      - #ER_OK if the property was set
     *      - #ER_BUS_OBJECT_NO_SUCH_INTERFACE if the specified interfaces does not exist on the remote object.
     *      - #ER_BUS_NO_SUCH_PROPERTY if the property does not exist
     */
    QStatus SetProperty(const char* iface, const char* property, uint32_t u, uint32_t timeout = DefaultCallTimeout) const {
        MsgArg arg("u", u); return SetProperty(iface, property, arg, timeout);
    }

    /**
     * Helper function to sychronously set an int32 property on the remote object.
     *
     * @param iface     Remote object's interface on which the property is defined.
     * @param property  The name of the property to set
     * @param i         The int32 value to set
     * @param timeout   Timeout specified in milliseconds to wait for a reply
     *
     * @return
     *      - #ER_OK if the property was set
     *      - #ER_BUS_OBJECT_NO_SUCH_INTERFACE if the specified interfaces does not exist on the remote object.
     *      - #ER_BUS_NO_SUCH_PROPERTY if the property does not exist
     */
    QStatus SetProperty(const char* iface, const char* property, int32_t i, uint32_t timeout = DefaultCallTimeout) const {
        MsgArg arg("i", i); return SetProperty(iface, property, arg, timeout);
    }

    /**
     * Helper function to sychronously set string property on the remote object from a C string.
     *
     * @param iface     Remote object's interface on which the property is defined.
     * @param property  The name of the property to set
     * @param s         The string value to set
     * @param timeout   Timeout specified in milliseconds to wait for a reply
     *
     * @return
     *      - #ER_OK if the property was set
     *      - #ER_BUS_OBJECT_NO_SUCH_INTERFACE if the specified interfaces does not exist on the remote object.
     *      - #ER_BUS_NO_SUCH_PROPERTY if the property does not exist
     */
    QStatus SetProperty(const char* iface, const char* property, const char* s, uint32_t timeout = DefaultCallTimeout) const {
        MsgArg arg("s", s); return SetProperty(iface, property, arg, timeout);
    }

    /**
     * Helper function to sychronously set string property on the remote object from a qcc::String.
     *
     * @param iface     Remote object's interface on which the property is defined.
     * @param property  The name of the property to set
     * @param s         The string value to set
     * @param timeout   Timeout specified in milliseconds to wait for a reply
     *
     * @return
     *      - #ER_OK if the property was set
     *      - #ER_BUS_OBJECT_NO_SUCH_INTERFACE if the specified interfaces does not exist on the remote object.
     *      - #ER_BUS_NO_SUCH_PROPERTY if the property does not exist
     */
    QStatus SetProperty(const char* iface, const char* property, const qcc::String& s, uint32_t timeout = DefaultCallTimeout) const {
        MsgArg arg("s", s.c_str()); return SetProperty(iface, property, arg, timeout);
    }

    /**
     * Function to register a handler for property change events.
     * Note that registering the same handler callback for the same
     * interface will overwrite the previous registration.  The same
     * handler callback may be registered for several different
     * interfaces simultaneously.
     *
     * Note that this makes method calls under the hood.  If this is
     * called from a message handler or other AllJoyn callback, you
     * must call BusAttachment::EnableConcurrentCallbacks().
     *
     * @param iface             Remote object's interface on which the property is defined.
     * @param properties        The name of the properties to monitor (NULL for all).
     * @param propertiesSize    Number of properties to monitor.
     * @param listener          Reference to the object that will receive the callback.
     * @param context           User defined context which will be passed as-is to callback.
     *
     * @return
     *      - #ER_OK if the handler was registered successfully
     *      - #ER_BUS_OBJECT_NO_SUCH_INTERFACE if the specified interfaces does not exist on the remote object.
     *      - #ER_BUS_NO_SUCH_PROPERTY if the property does not exist
     */
    QStatus RegisterPropertiesChangedListener(const char* iface,
                                              const char** properties,
                                              size_t propertiesSize,
                                              ProxyBusObject::PropertiesChangedListener& listener,
                                              void* context);

    /**
     * Function to unregister a handler for property change events.
     *
     * @param iface     Remote object's interface on which the property is defined.
     * @param listener  Reference to the object that used to receive the callback.
     *
     * @return
     *      - #ER_OK if the handler was registered successfully
     *      - #ER_BUS_OBJECT_NO_SUCH_INTERFACE if the specified interfaces does not exist on the remote object.
     */
    QStatus UnregisterPropertiesChangedListener(const char* iface, ProxyBusObject::PropertiesChangedListener& listener);

    /**
     * Returns the interfaces implemented by this object. Note that all proxy bus objects
     * automatically inherit the "org.freedesktop.DBus.Peer" which provides the built-in "ping"
     * method, so this method always returns at least that one interface.
     *
     * @param ifaces     A pointer to an InterfaceDescription array to receive the interfaces. Can be NULL in
     *                   which case no interfaces are returned and the return value gives the number
     *                   of interface available.
     * @param numIfaces  The size of the InterfaceDescription array. If this value is smaller than the total
     *                   number of interfaces only numIfaces will be returned.
     *
     * @return  The number of interfaces returned or the total number of interfaces if ifaces is NULL.
     */
    size_t GetInterfaces(const InterfaceDescription** ifaces = NULL, size_t numIfaces = 0) const;

    /**
     * Returns a pointer to an interface description. Returns NULL if the object does not implement
     * the requested interface.
     *
     * @param iface  The name of interface to get.
     *
     * @return
     *      - A pointer to the requested interface description.
     *      - NULL if requested interface is not implemented or not found
     */
    const InterfaceDescription* GetInterface(const char* iface) const;

    /**
     * Tests if this object implements the requested interface.
     *
     * @param iface  The interface to check
     *
     * @return  true if the object implements the requested interface
     */
    bool ImplementsInterface(const char* iface) const { return GetInterface(iface) != NULL; }

    /**
     * Add an interface to this ProxyBusObject.
     *
     * Occasionally, AllJoyn library user may wish to call a method on
     * a %ProxyBusObject that was not reported during introspection of the remote object.
     * When this happens, the InterfaceDescription will have to be registered with the
     * Bus manually and the interface will have to be added to the %ProxyBusObject using this method.
     * @remark
     * The interface added via this call must have been previously registered with the
     * Bus. (i.e. it must have come from a call to Bus::GetInterface()).
     *
     * @param iface    The interface to add to this object. Must come from Bus::GetInterface().
     * @return
     *      - #ER_OK if successful.
     *      - An error status otherwise
     */
    QStatus AddInterface(const InterfaceDescription& iface);

    /**
     * Add an existing interface to this object using the interface's name.
     *
     * @param name   Name of existing interface to add to this object.
     * @return
     *      - #ER_OK if successful.
     *      - An error status otherwise.
     */
    QStatus AddInterface(const char* name);

    /**
     * Returns an array of ProxyBusObject pointers for the children of this
     * %ProxyBusObject.
     *
     * @param children     An array to %ProxyBusObject pointers to receive the
     *                     children.  Can be NULL in which case no children are
     *                     returned and the return value gives the number of
     *                     children available.  Note that the lifetime of the
     *                     pointers is limited to the lifetime of the parent.
     * @param numChildren  The size of the %ProxyBusObject array. If this value
     *                     is smaller than the total number of children only
     *                     numChildren will be returned.
     *
     * @return  The number of children returned or the total number of children
     *          if children is NULL.
     */
    size_t GetChildren(ProxyBusObject** children = NULL, size_t numChildren = 0);

    /**
     * Returns an array of _ProxyBusObjects for the children of this %ProxyBusObject.
     * Unlike the unmanaged version of GetChildren, it is expected the caller will call
     * delete on each _ProxyBusObject in the array returned.
     *
     * @param children     A pointer to a %_ProxyBusObject array to receive the children. Can be NULL in
     *                     which case no children are returned and the return value gives the number
     *                     of children available.
     * @param numChildren  The size of the %_ProxyBusObject array. If this value is smaller than the total
     *                     number of children only numChildren will be returned.
     *
     * @return  The number of children returned or the total number of children if children is NULL.
     */
    QCC_DEPRECATED(size_t GetManagedChildren(void* children = NULL, size_t numChildren = 0));

    /**
     * Get a path descendant ProxyBusObject (child) by its absolute or relative path name.
     *
     * For example, if this ProxyBusObject's path is @c "/foo/bar", then you
     * can retrieve the ProxyBusObject for @c "/foo/bar/bat/baz" by calling
     * @c GetChild("/foo/bar/bat/baz") or @c GetChild("/bat/baz").  The pointer
     * that is returned is owned by the parent instance of ProxyBusObject and
     * will be deleted when the parent is destroyed.
     *
     * @param path the absolute or relative path for the child.
     *
     * @return
     *      - The (potentially deep) descendant ProxyBusObject
     *      - NULL if not found.
     */
    ProxyBusObject* GetChild(const char* path);

    /**
     * Get a path descendant _ProxyBusObject (child) by its absolute or relative path name.
     *
     * For example, if this _ProxyBusObject's path is @c "/foo/bar", then you can retrieve the
     * _ProxyBusObject for @c "/foo/bar/bat/baz" by calling @c GetChild("/foo/bar/bat/baz") or
     * @c GetChild("bat/baz"). Unlike the unmanaged version of GetChild, it is expected the
     * caller will call delete on the _ProxyBusObject returned.
     *
     * @param inPath the absolute or relative path for the child.
     *
     * @return
     *      - The (potentially deep) descendant _ProxyBusObject
     *      - NULL if not found.
     */
    QCC_DEPRECATED(void* GetManagedChild(const char* inPath));

    /**
     * Add a child object (direct or deep object path descendant) to this object.
     * If you add a deep path descendant, this method will create intermediate
     * ProxyBusObject children as needed.
     *
     * @remark
     *  - It is an error to try to add a child that already exists.
     *  - It is an error to try to add a child that has an object path that is not a descendant of this object's path.
     *
     * @param child  Child ProxyBusObject
     * @return
     *      - #ER_OK if successful.
     *      - #ER_BUS_BAD_CHILD_PATH if the path is a bad path
     *      - #ER_BUS_OBJ_ALREADY_EXISTS if the object already exists on the ProxyBusObject
     */
    QStatus AddChild(const ProxyBusObject& child);

    /**
     * Remove a child object and any descendants it may have.
     *
     * @param path   Absolute or relative (to this ProxyBusObject) object path.
     * @return
     *      - #ER_OK if successful.
     *      - #ER_BUS_BAD_CHILD_PATH if the path given was not a valid path
     *      - #ER_BUS_OBJ_NOT_FOUND if the Child object was not found
     *      - #ER_FAIL any other unexpected error.
     */
    QStatus RemoveChild(const char* path);

    /**
     * Make a synchronous method call from this object
     *
     * @param method       Method being invoked.
     * @param args         The arguments for the method call (can be NULL)
     * @param numArgs      The number of arguments
     * @param replyMsg     The reply message received for the method call
     * @param timeout      Timeout specified in milliseconds to wait for a reply
     * @param flags        Logical OR of the message flags for this method call. The following flags apply to method calls:
     *                     - If #ALLJOYN_FLAG_ENCRYPTED is set the message is authenticated and the payload if any is encrypted.
     *                     - If #ALLJOYN_FLAG_AUTO_START is set the bus will attempt to start a service if it is not running.
     *
     *
     * @return
     *      - #ER_OK if the method call succeeded and the reply message type is #MESSAGE_METHOD_RET
     *      - #ER_BUS_REPLY_IS_ERROR_MESSAGE if the reply message type is #MESSAGE_ERROR
     */
    QStatus MethodCall(const InterfaceDescription::Member& method,
                       const MsgArg* args,
                       size_t numArgs,
                       Message& replyMsg,
                       uint32_t timeout = DefaultCallTimeout,
                       uint8_t flags = 0) const;

    /**
     * Make a synchronous method call from this object
     *
     * @param ifaceName    Name of interface.
     * @param methodName   Name of method.
     * @param args         The arguments for the method call (can be NULL)
     * @param numArgs      The number of arguments
     * @param replyMsg     The reply message received for the method call
     * @param timeout      Timeout specified in milliseconds to wait for a reply
     * @param flags        Logical OR of the message flags for this method call. The following flags apply to method calls:
     *                     - If #ALLJOYN_FLAG_ENCRYPTED is set the message is authenticated and the payload if any is encrypted.
     *                     - If #ALLJOYN_FLAG_AUTO_START is set the bus will attempt to start a service if it is not running.
     *
     * @return
     *      - #ER_OK if the method call succeeded and the reply message type is #MESSAGE_METHOD_RET
     *      - #ER_BUS_REPLY_IS_ERROR_MESSAGE if the reply message type is #MESSAGE_ERROR
     */
    virtual QStatus MethodCall(const char* ifaceName,
                               const char* methodName,
                               const MsgArg* args,
                               size_t numArgs,
                               Message& replyMsg,
                               uint32_t timeout = DefaultCallTimeout,
                               uint8_t flags = 0) const;

    /**
     * Make a fire-and-forget method call from this object. The caller will not be able to tell if
     * the method call was successful or not. This is equivalent to calling MethodCall() with
     * flags == ALLJOYN_FLAG_NO_REPLY_EXPECTED. Because this call doesn't block it can be made from
     * within a signal handler.
     *
     * @param ifaceName    Name of interface.
     * @param methodName   Name of method.
     * @param args         The arguments for the method call (can be NULL)
     * @param numArgs      The number of arguments
     * @param flags        Logical OR of the message flags for this method call. The following flags apply to method calls:
     *                     - If #ALLJOYN_FLAG_ENCRYPTED is set the message is authenticated and the payload if any is encrypted.
     *                     - If #ALLJOYN_FLAG_AUTO_START is set the bus will attempt to start a service if it is not running.
     *
     * @return
     *      - #ER_OK if the method call succeeded
     */
    QStatus MethodCall(const char* ifaceName,
                       const char* methodName,
                       const MsgArg* args,
                       size_t numArgs,
                       uint8_t flags = 0) const
    {
        return MethodCallAsync(ifaceName, methodName, NULL, NULL, args, numArgs, NULL, 0, flags |= ALLJOYN_FLAG_NO_REPLY_EXPECTED);
    }

    /**
     * Make a fire-and-forget method call from this object. The caller will not be able to tell if
     * the method call was successful or not. This is equivalent to calling MethodCall() with
     * flags == ALLJOYN_FLAG_NO_REPLY_EXPECTED. Because this call doesn't block it can be made from
     * within a signal handler.
     *
     * @param method       Method being invoked.
     * @param args         The arguments for the method call (can be NULL)
     * @param numArgs      The number of arguments
     * @param flags        Logical OR of the message flags for this method call. The following flags apply to method calls:
     *                     - If #ALLJOYN_FLAG_ENCRYPTED is set the message is authenticated and the payload if any is encrypted.
     *                     - If #ALLJOYN_FLAG_AUTO_START is set the bus will attempt to start a service if it is not running.
     *
     * @return
     *      - #ER_OK if the method call succeeded and the reply message type is #MESSAGE_METHOD_RET
     */
    QStatus MethodCall(const InterfaceDescription::Member& method,
                       const MsgArg* args,
                       size_t numArgs,
                       uint8_t flags = 0) const
    {
        return MethodCallAsync(method, NULL, NULL, args, numArgs, NULL, 0, flags |= ALLJOYN_FLAG_NO_REPLY_EXPECTED);
    }

    /**
     * Make an asynchronous method call from this object
     *
     * @param method       Method being invoked.
     * @param receiver     The object to be called when the asych method call completes.
     * @param replyFunc    The function that is called to deliver the reply
     * @param args         The arguments for the method call (can be NULL)
     * @param numArgs      The number of arguments
     * @param receiver     The object to be called when the asych method call completes.
     * @param context      User-defined context that will be returned to the reply handler
     * @param timeout      Timeout specified in milliseconds to wait for a reply
     * @param flags        Logical OR of the message flags for this method call. The following flags apply to method calls:
     *                     - If #ALLJOYN_FLAG_ENCRYPTED is set the message is authenticated and the payload if any is encrypted.
     *                     - If #ALLJOYN_FLAG_AUTO_START is set the bus will attempt to start a service if it is not running.
     * @return
     *      - ER_OK if successful
     *      - An error status otherwise
     */
    QStatus MethodCallAsync(const InterfaceDescription::Member& method,
                            MessageReceiver* receiver,
                            MessageReceiver::ReplyHandler replyFunc,
                            const MsgArg* args = NULL,
                            size_t numArgs = 0,
                            void* context = NULL,
                            uint32_t timeout = DefaultCallTimeout,
                            uint8_t flags = 0) const;

    /**
     * Make an asynchronous method call from this object
     *
     * @param ifaceName    Name of interface for method.
     * @param methodName   Name of method.
     * @param receiver     The object to be called when the asynchronous method call completes.
     * @param replyFunc    The function that is called to deliver the reply
     * @param args         The arguments for the method call (can be NULL)
     * @param numArgs      The number of arguments
     * @param context      User-defined context that will be returned to the reply handler
     * @param timeout      Timeout specified in milliseconds to wait for a reply
     * @param flags        Logical OR of the message flags for this method call. The following flags apply to method calls:
     *                     - If #ALLJOYN_FLAG_ENCRYPTED is set the message is authenticated and the payload if any is encrypted.
     *                     - If #ALLJOYN_FLAG_AUTO_START is set the bus will attempt to start a service if it is not running.
     * @return
     *      - ER_OK if successful
     *      - An error status otherwise
     */
    QStatus MethodCallAsync(const char* ifaceName,
                            const char* methodName,
                            MessageReceiver* receiver,
                            MessageReceiver::ReplyHandler replyFunc,
                            const MsgArg* args = NULL,
                            size_t numArgs = 0,
                            void* context = NULL,
                            uint32_t timeout = DefaultCallTimeout,
                            uint8_t flags = 0) const;

    /**
     * Initialize this proxy object from an XML string. Calling this method does several things:
     *
     *  -# Create and register any new InterfaceDescription(s) that are mentioned in the XML.
     *     (Interfaces that are already registered with the bus are left "as-is".)
     *  -# Add all the interfaces mentioned in the introspection data to this ProxyBusObject.
     *  -# Recursively create any child ProxyBusObject(s) and create/add their associated @n
     *     interfaces as mentioned in the XML. Then add the descendant object(s) to the appropriate
     *     descendant of this ProxyBusObject (in the children collection). If the named child object
     *     already exists as a child of the appropriate ProxyBusObject, then it is updated
     *     to include any new interfaces or children mentioned in the XML.
     *
     * Note that when this method fails during parsing, the return code will be set accordingly.
     * However, any interfaces which were successfully parsed prior to the failure
     * may be registered with the bus. Similarly, any objects that were successfully created
     * before the failure will exist in this object's set of children.
     *
     * @param xml         An XML string in DBus introspection format.
     * @param identifier  An optional identifying string to include in error logging messages.
     *
     * @return
     *      - #ER_OK if parsing is completely successful.
     *      - An error status otherwise.
     */
    QStatus ParseXml(const char* xml, const char* identifier = NULL);

    /**
     * Explicitly secure the connection to the remote peer for this proxy object. Peer-to-peer
     * connections can only be secured if EnablePeerSecurity() was previously called on the bus
     * attachment for this proxy object. If the peer-to-peer connection is already secure this
     * function does nothing. Note that peer-to-peer connections are automatically secured when a
     * method call requiring encryption is sent.
     *
     * This call causes messages to be send on the bus, therefore it cannot be called within AllJoyn
     * callbacks (method/signal/reply handlers or ObjectRegistered callbacks, etc.)
     *
     * @param forceAuth  If true, forces an re-authentication even if the peer connection is already
     *                   authenticated.
     *
     * @return
     *          - #ER_OK if the connection was secured or an error status indicating that the
     *            connection could not be secured.
     *          - #ER_BUS_NO_AUTHENTICATION_MECHANISM if BusAttachment::EnablePeerSecurity() has not been called.
     *          - #ER_AUTH_FAIL if the attempt(s) to authenticate the peer failed.
     *          - Other error status codes indicating a failure.
     */
    QStatus SecureConnection(bool forceAuth = false);

    /**
     * Asynchronously secure the connection to the remote peer for this proxy object. Peer-to-peer
     * connections can only be secured if EnablePeerSecurity() was previously called on the bus
     * attachment for this proxy object. If the peer-to-peer connection is already secure this
     * function does nothing. Note that peer-to-peer connections are automatically secured when a
     * method call requiring encryption is sent.
     *
     * Notification of success or failure is via the AuthListener passed to EnablePeerSecurity().
     *
     * @param forceAuth  If true, forces an re-authentication even if the peer connection is already
     *                   authenticated.
     *
     * @return
     *          - #ER_OK if securing could begin.
     *          - #ER_BUS_NO_AUTHENTICATION_MECHANISM if BusAttachment::EnablePeerSecurity() has not been called.
     *          - Other error status codes indicating a failure.
     */
    QStatus SecureConnectionAsync(bool forceAuth = false);

    /**
     * Checks if other refers to the same internal instance has this.
     *
     * @param other  The object being compared
     * @return true iff this has identical internals to other
     */
    bool iden(const ProxyBusObject& other) const { return internal.iden(other.internal); }

    /**
     * Equivalence operator.
     *
     * @param other  The object being compared
     * @return true iff this is the same as other
     */
    bool operator==(const ProxyBusObject& other) const;

    /**
     * Less than operator.
     *
     * @param other  The object being compared
     * @return true iff this is less than other
     */
    bool operator<(const ProxyBusObject& other) const;

    /**
     * Assignment operator.
     *
     * @param other  The object being assigned from
     * @return a copy of the ProxyBusObject
     */
    ProxyBusObject& operator=(const ProxyBusObject& other);

    /**
     * Copy constructor
     *
     * @param other  The object being copied from.
     */
    ProxyBusObject(const ProxyBusObject& other);

    /**
     * Indicates if this is a valid (usable) proxy bus object.
     *
     * @return true if a valid proxy bus object, false otherwise.
     */
    bool IsValid() const;

    /**
     * Indicates if the remote object for this proxy bus object is secure.
     *
     * @return  true if the object is secure
     */
    bool IsSecure() const;

    /**
     * Enable property caching for this proxy bus object.
     */
    void EnablePropertyCaching();

  private:

    class Internal;
    qcc::ManagedObj<Internal> internal; /**< Internal ProxyBusObject state */

    bool isExiting;             /**< true iff ProxyBusObject is in the process of being destroyed */

    ProxyBusObject(qcc::ManagedObj<Internal> internal);

    /**
     * @internal
     * Called by XmlHelper to set the secure flag when introspecting.
     *
     * @param isSecure  indicates if node is secure or not
     */
    void SetSecure(bool isSecure);

    /**
     * @internal
     * Method return handler used to process synchronous method calls.
     *
     * @param msg     Method return message
     * @param context Opaque context passed from method_call to method_return
     */
    void SyncReplyHandler(Message& msg, void* context);

    /**
     * @internal
     * Introspection method_reply handler. (Internal use only)
     *
     * @param message Method return Message
     * @param context Opaque context passed from method_call to method_return
     */
    void IntrospectMethodCB(Message& message, void* context);

    /**
     * @internal
     * GetProperty method_reply handler. (Internal use only)
     *
     * @param message Method return Message
     * @param context Opaque context passed from method_call to method_return
     */
    void GetPropMethodCB(Message& message, void* context);

    /**
     * @internal
     * GetAllProperties method_reply handler. (Internal use only)
     *
     * @param message Method return Message
     * @param context Opaque context passed from method_call to method_return
     */
    void GetAllPropsMethodCB(Message& message, void* context);

    /**
     * @internal
     * SetProperty method_reply handler. (Internal use only)
     *
     * @param message Method return Message
     * @param context Opaque context passed from method_call to method_return
     */
    void SetPropMethodCB(Message& message, void* context);

    /**
     * @internal
     * Set the B2B endpoint to use for all communication with remote object.
     * This method is for internal use only.
     *
     * @param b2bEp the RemoteEndpoint for Bus to Bus communication
     */
    void SetB2BEndpoint(RemoteEndpoint& b2bEp);

    /**
     * @internal
     * Internal introspection xml parse tree type.
     */
    struct IntrospectionXml;

    /**
     * @internal
     * Parse a single introspection @<node@> element.
     *
     * @param node  XML element (must be a @<node@>).
     *
     * @return
     *       - #ER_OK if completely successful.
     *       - An error status otherwise
     */
    static QStatus ParseNode(const IntrospectionXml& node);

    /**
     * @internal
     * Parse a single introspection @<interface@> element.
     *
     * @param ifc  XML element (must be an @<interface@>).
     *
     * @return
     *       - #ER_OK if completely successful.
     *       - An error status otherwise
     */
    static QStatus ParseInterface(const IntrospectionXml& ifc);
};

/**
 * _ProxyBusObject is a reference counted (managed) version of ProxyBusObject
 */
QCC_DEPRECATED(typedef qcc::ManagedObj<ProxyBusObject> _ProxyBusObject);

}

#endif


text:
package org.apache.sling.models.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.inject.Qualifier;

/**
 * Provide a filter on an @Inject.
 */
@Target({ ElementType.FIELD, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Source("osgi-services")
@Qualifier
public @interface Filter {

    public String value();

}

redpajama_set_name: RedPajamaGithub


text:
Port of the real-time multiplayer 2D maze war BSD game "Hunt" to Google
App Engine and modern web browsers.

[https://en.wikipedia.org/wiki/Hunt_(video_game)](https://en.wikipedia.org/wiki/Hunt_(video_game))

Moderately complex multiplayer real-time web and mobile games require
a mix of stateless and stateful components to deal with managing game
state, load balancing, scaling, matchmaking, statistics gathering,
monitoring, analytics, and more.

This project implements one such design and architecture for modernizing
the retro terminal based real-time multiplayer 1980's BSD game, "Hunt"
and running in Google App Engine (GAE) Platform as a Service.

It includes the entire client and server side applications, from the
Javascript Single Page App running in a browser, to the stateless
serving infrastructure running in the GAE Standard
Environment, a stateful game engine in the GAE Flexible environment.
Memcache, Datastore, Cloud Pub-Sub, Cron, and Metadata services are
utilized as architectural components.

##Highlights
* Client: HTML / Javascript
* Frontend: Golang application for App Engine Standard
* Backend: Game engine (Original Hunt daemon & Golang instance manager)
  in App Engine Flex

##Licenses
* All Google authored code is covered by the license detailed in the LICENSE
  file at the top of the tree.
* This repository also contains code covered by other licenses.
  All such code can be found within the "third_party" directory tree.

##Installation
###Prerequisites

* Install The Go Programming Language
	Installation instructions can be found at [https://golang.org](https://golang.org "https://golang.org")

* Install docker
	Installation instructions can be found at [https://docker.github.io/engine/installation](https://docker.github.io/engine/installation)

* Install the App Engine SDK for Go
	Installation instructions can be found at [https://cloud.google.com/appengine/docs/go/download](https://cloud.google.com/appengine/docs/go/download)

* Install the Google Cloud SDK
	Installation instructions can be found at [https://cloud.google.com/sdk/docs/quickstarts](https://cloud.google.com/sdk/docs/quickstarts)

###Build and Deploy
* Using the Google Cloud Platform dashboard, go to the Projects page and
create a new project.
[https://console.cloud.google.com/iam-admin/projects](https://console.cloud.google.com/iam-admin/projects)
Make note of the name assigned to the new project.

* From the root of the web-bsd-hunt directory, build and deploy the project by executing the command:

     `make PROJECT=<project-name> build deploy`

     Where `<project-name>` is the name given to the Google Platform project created in the previous step.

* Once the build and deployment finishes, you can view the application in a web browser using the following URL:
 https://`<project-name>`.appspot.com

##Notes
* This is not an official Google product.


text:
using System;
using System.Runtime.InteropServices;

namespace Hell.LastCircle.Options
{
	/// <summary>
	/// Mapping of C structure OPTIONSDIALOGPAGE from m_options.h header.
	/// </summary>
	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
	public class OptionsDialogPage
	{
		[UnmanagedFunctionPointer(CallingConvention.StdCall)]
		public delegate IntPtr DlgProc(IntPtr hDlg, uint message,
			IntPtr wParam, IntPtr hParam);

		private int cbSize = Marshal.SizeOf(typeof (OptionsDialogPage));
		public int position;
		public string pszTitle;
		[MarshalAs(UnmanagedType.FunctionPtr)] public DlgProc pfnDlgProc;
		public IntPtr pszTemplate;
		public IntPtr hInstance;
		public IntPtr hIcon;
		public string pszGroup;
		public int groupPosition;
		public IntPtr hGroupIcon;
		public int flags;
		public string tab;
		public IntPtr dwInitParam;
		public int hLangpack;
	}
}


text:
ULP coprocessor instruction set
===============================

This document provides details about the instructions used by ESP32 ULP coprocessor assembler.

ULP coprocessor has 4 16-bit general purpose registers, labeled R0, R1, R2, R3. It also has an 8-bit counter register (stage_cnt) which can be used to implement loops. Stage count regiter is accessed using special instructions.

ULP coprocessor can access 8k bytes of RTC_SLOW_MEM memory region. Memory is addressed in 32-bit word units. It can also access peripheral registers in RTC_CNTL, RTC_IO, and SENS peripherals.

All instructions are 32-bit. Jump instructions, ALU instructions, peripheral register and memory access instructions are executed in 1 cycle. Instructions which work with peripherals (TSENS, ADC, I2C) take variable number of cycles, depending on peripheral operation.

The instruction syntax is case insensitive. Upper and lower case letters can be used and intermixed arbitrarily. This is true both for register names and instruction names.

Note about addressing
---------------------
ESP32 ULP coprocessor's JUMP, ST, LD instructions which take register as an argument (jump address, store/load base address) expect the argument to be expressed in 32-bit words.

Consider the following example program::

  entry:
          NOP
          NOP
          NOP
          NOP
  loop:
          MOVE R1, loop
          JUMP R1

When this program is assembled and linked, address of label ``loop`` will be equal to 16 (expressed in bytes). However `JUMP` instruction expects the address stored in register to be expressed in 32-bit words. To account for this common use case, assembler will convert the address of label `loop` from bytes to words, when generating ``MOVE`` instruction, so the code generated code will be equivalent to::

  0000    NOP
  0004    NOP
  0008    NOP
  000c    NOP
  0010    MOVE R1, 4
  0014    JUMP R1

The other case is when the argument of ``MOVE`` instruction is not a label but a constant. In this case assembler will use the value as is, without any conversion::

          .set        val, 0x10
          MOVE        R1, val

In this case, value loaded into R1 will be ``0x10``.

Similar considerations apply to ``LD`` and ``ST`` instructions. Consider the following code::

          .global array
  array:  .long 0
          .long 0
          .long 0
          .long 0

          MOVE R1, array
          MOVE R2, 0x1234
          ST R2, R1, 0      // write value of R2 into the first array element,
                            // i.e. array[0]

          ST R2, R1, 4      // write value of R2 into the second array element
                            // (4 byte offset), i.e. array[1]

          ADD R1, R1, 2     // this increments address by 2 words (8 bytes)
          ST R2, R1, 0      // write value of R2 into the third array element,
                            // i.e. array[2]

Note about instruction execution time
-------------------------------------

ULP coprocessor is clocked from RTC_FAST_CLK, which is normally derived from the internal 8MHz oscillator. Applications which need to know exact ULP clock frequency can calibrate it against the main XTAL clock::

    #include "soc/rtc.h"

    // calibrate 8M/256 clock against XTAL, get 8M/256 clock period
    uint32_t rtc_8md256_period = rtc_clk_cal(RTC_CAL_8MD256, 100);
    uint32_t rtc_fast_freq_hz = 1000000ULL * (1 << RTC_CLK_CAL_FRACT) * 256 / rtc_8md256_period;

ULP coprocessor needs 2 clock cycle to fetch each instuction (fetching is not pipelined), plus certain number of cycles to execute, depending on the instruction. See description of each instruction for details on the execution time.

Note that when accessing RTC memories and RTC registers, ULP coprocessor has lower priority than the main CPUs. This means that ULP coprocessor execution may be suspended while the main CPUs access same memory region as the ULP.

**NOP** - no operation
----------------------

**Syntax**
  **NOP**
**Operands**
  None
**Cycles**
  2 (fetch) + 1 (execute)
**Description**
  No operation is performed. Only the PC is incremented.

**Example**::

  1:    NOP

**ADD** - Add to register
-------------------------

**Syntax**
    **ADD**      *Rdst, Rsrc1, Rsrc2*

    **ADD**      *Rdst, Rsrc1, imm*

**Operands**
  - *Rdst* - Register R[0..3]
  - *Rsrc1* - Register R[0..3]
  - *Rsrc2* - Register R[0..3]
  - *Imm* - 16-bit signed value

**Cycles**
  2 (fetch) + 2 (execute)

**Description**
  The instruction adds source register to another source register or to a 16-bit signed value and stores result to the destination register.

**Examples**::

  1:    ADD R1, R2, R3        //R1 = R2 + R3

  2:    Add R1, R2, 0x1234    //R1 = R2 + 0x1234

  3:    .set value1, 0x03     //constant value1=0x03
        Add R1, R2, value1    //R1 = R2 + value1

  4:    .global label         //declaration of variable label
        Add R1, R2, label     //R1 = R2 + label
          ...
        label: nop            //definition of variable label

**SUB** - Subtract from register
--------------------------------

**Syntax**
  **SUB** *Rdst, Rsrc1, Rsrc2*

  **SUB** *Rdst, Rsrc1, imm*

**Operands**
  - *Rdst*  - Register R[0..3]
  - *Rsrc1* - Register R[0..3]
  - *Rsrc2* - Register R[0..3]
  - *Imm*   - 16-bit signed value

**Cycles**
  2 (fetch) + 2 (execute)

**Description**
  The instruction subtracts the source register from another source register or subtracts 16-bit signed value from a source register, and stores result to the destination register.

**Examples**::

  1:         SUB R1, R2, R3             //R1 = R2 - R3

  2:         sub R1, R2, 0x1234         //R1 = R2 - 0x1234

  3:         .set value1, 0x03          //constant value1=0x03
             SUB R1, R2, value1         //R1 = R2 - value1
  4:         .global label              //declaration of variable label
             SUB R1, R2, label          //R1 = R2 - label
               ....
    label:   nop                        //definition of variable label

**AND** - Logical AND of two operands
-------------------------------------

**Syntax**
    **AND** *Rdst, Rsrc1, Rsrc2*

    **AND** *Rdst, Rsrc1, imm*

**Operands**
  - *Rdst* - Register R[0..3]
  - *Rsrc1* - Register R[0..3]
  - *Rsrc2* - Register R[0..3]
  - *Imm* - 16-bit signed value

**Cycles**
  2 (fetch) + 2 (execute)

**Description**
  The instruction does logical AND of a source register and another source register or 16-bit signed value and stores result to the destination register.

**Examples**::

  1:        AND R1, R2, R3          //R1 = R2 & R3

  2:        AND R1, R2, 0x1234      //R1 = R2 & 0x1234

  3:        .set value1, 0x03       //constant value1=0x03
            AND R1, R2, value1      //R1 = R2 & value1

  4:        .global label           //declaration of variable label
            AND R1, R2, label       //R1 = R2 & label
                ...
    label:  nop                     //definition of variable label

**OR** - Logical OR of two operands
-----------------------------------

**Syntax**
  **OR** *Rdst, Rsrc1, Rsrc2*

  **OR** *Rdst, Rsrc1, imm*

**Operands**
  - *Rdst* - Register R[0..3]
  - *Rsrc1* - Register R[0..3]
  - *Rsrc2* - Register R[0..3]
  - *Imm* - 16-bit signed value

**Cycles**
  2 (fetch) + 2 (execute)

**Description**
  The instruction does logical OR of a source register and another source register or 16-bit signed value and stores result to the destination register.

**Examples**::

  1:       OR R1, R2, R3           //R1 = R2 \| R3

  2:       OR R1, R2, 0x1234       //R1 = R2 \| 0x1234

  3:       .set value1, 0x03       //constant value1=0x03
           OR R1, R2, value1       //R1 = R2 \| value1

  4:       .global label           //declaration of variable label
           OR R1, R2, label        //R1 = R2 \|label
           ...
    label: nop                     //definition of variable label

**LSH** - Logical Shift Left
----------------------------

**Syntax**
  **LSH** *Rdst, Rsrc1, Rsrc2*

  **LSH** *Rdst, Rsrc1, imm*

**Operands**
  - *Rdst* - Register R[0..3]
  - *Rsrc1* - Register R[0..3]
  - *Rsrc2* - Register R[0..3]
  - *Imm* - 16-bit signed value

**Cycles**
  2 (fetch) + 2 (execute)

**Description**
   The instruction does logical shift to left of source register to number of bits from another source register or 16-bit signed value and store result to the destination register.

**Examples**::

  1:       LSH R1, R2, R3            //R1 = R2 << R3

  2:       LSH R1, R2, 0x03          //R1 = R2 << 0x03

  3:       .set value1, 0x03         //constant value1=0x03
           LSH R1, R2, value1        //R1 = R2 << value1

  4:       .global label             //declaration of variable label
           LSH R1, R2, label         //R1 = R2 << label
           ...
    label:  nop                       //definition of variable label

**RSH** - Logical Shift Right
-----------------------------

**Syntax**
   **RSH** *Rdst, Rsrc1, Rsrc2*

   **RSH** *Rdst, Rsrc1, imm*

**Operands**
  *Rdst* - Register R[0..3]
  *Rsrc1* - Register R[0..3]
  *Rsrc2* - Register R[0..3]
  *Imm* - 16-bit signed value

**Cycles**
  2 (fetch) + 2 (execute)

**Description**
  The instruction does logical shift to right of source register to number of bits from another source register or 16-bit signed value and store result to the destination register.

**Examples**::

  1:        RSH R1, R2, R3              //R1 = R2 >> R3

  2:        RSH R1, R2, 0x03            //R1 = R2 >> 0x03

  3:        .set value1, 0x03           //constant value1=0x03
            RSH R1, R2, value1          //R1 = R2 >> value1

  4:        .global label               //declaration of variable label
            RSH R1, R2, label           //R1 = R2 >> label
    label:  nop                         //definition of variable label

**MOVE** – Move to register
---------------------------

**Syntax**
  **MOVE**     *Rdst, Rsrc*

  **MOVE**     *Rdst, imm*

**Operands**
  - *Rdst* – Register R[0..3]
  - *Rsrc* – Register R[0..3]
  - *Imm*  – 16-bit signed value

**Cycles**
  2 (fetch) + 2 (execute)

**Description**
   The instruction move to destination register value from source register or 16-bit signed value.

   Note that when a label is used as an immediate, the address of the label will be converted from bytes to words. This is because LD, ST, and JUMP instructions expect the address register value to be expressed in words rather than bytes. To avoid using an extra instruction

**Examples**::

  1:        MOVE       R1, R2            //R1 = R2 >> R3

  2:        MOVE       R1, 0x03          //R1 = R2 >> 0x03

  3:        .set       value1, 0x03      //constant value1=0x03
            MOVE       R1, value1        //R1 = value1

  4:        .global     label            //declaration of label
            MOVE        R1, label        //R1 = address_of(label) / 4
            ...
    label:  nop                          //definition of label

**ST** – Store data to the memory
---------------------------------

**Syntax**
  **ST**     *Rsrc, Rdst, offset*

**Operands**
  - *Rsrc* – Register R[0..3], holds the 16-bit value to store
  - *Rdst* – Register R[0..3], address of the destination, in 32-bit words
  - *Offset* – 10-bit signed value, offset in bytes

**Cycles**
  2 (fetch) + 4 (execute)

**Description**
  The instruction stores the 16-bit value of Rsrc to the lower half-word of memory with address Rdst+offset. The upper half-word is written with the current program counter (PC), expressed in words, shifted left by 5 bits::

    Mem[Rdst + offset / 4]{31:0} = {PC[10:0], 5'b0, Rsrc[15:0]}

  The application can use higher 16 bits to determine which instruction in the ULP program has written any particular word into memory.

**Examples**::

  1:        ST  R1, R2, 0x12        //MEM[R2+0x12] = R1

  2:        .data                   //Data section definition
    Addr1:  .word     123           // Define label Addr1 16 bit
            .set      offs, 0x00    // Define constant offs
            .text                   //Text section definition
            MOVE      R1, 1         // R1 = 1
            MOVE      R2, Addr1     // R2 = Addr1
            ST        R1, R2, offs  // MEM[R2 +  0] = R1
                                    // MEM[Addr1 + 0] will be 32'h600001

**LD** – Load data from the memory
----------------------------------

**Syntax**
   **LD**      *Rdst, Rsrc, offset*

**Operands**
   *Rdst*  – Register R[0..3], destination

   *Rsrc* – Register R[0..3], holds address of destination, in 32-bit words

   *Offset* – 10-bit signed value, offset in bytes

**Cycles**
  2 (fetch) + 4 (execute)

**Description**
   The instruction loads lower 16-bit half-word from memory with address Rsrc+offset into the destination register Rdst::

     Rdst[15:0] = Mem[Rsrc + offset / 4][15:0]

**Examples**::

  1:        LD  R1, R2, 0x12            //R1 = MEM[R2+0x12]

  2:        .data                       //Data section definition
    Addr1:  .word     123               // Define label Addr1 16 bit
            .set      offs, 0x00        // Define constant offs
            .text                       //Text section definition
            MOVE      R1, 1             // R1 = 1
            MOVE      R2, Addr1         // R2 = Addr1 / 4 (address of label is converted into words)
            LD        R1, R2, offs      // R1 = MEM[R2 +  0]
                                        // R1 will be 123

**JUMP** – Jump to an absolute address
--------------------------------------

**Syntax**
  **JUMP**        *Rdst*

  **JUMP**        *ImmAddr*

  **JUMP**        *Rdst, Condition*

  **JUMP**        *ImmAddr, Condition*

**Operands**
  - *Rdst* – Register R[0..3] containing address to jump to (expressed in 32-bit words)

  - *ImmAddr* – 13 bits address (expressed in bytes), aligned to 4 bytes

  - *Condition*:
     - EQ – jump if last ALU operation result was zero
     - OV – jump if last ALU has set overflow flag

**Cycles**
  2 (fetch) + 2 (execute)

**Description**
  The instruction makes jump to the specified address. Jump can be either unconditional or based on an ALU flag.

**Examples**::

  1:        JUMP       R1            // Jump to address in R1 (address in R1 is in 32-bit words)

  2:        JUMP       0x120, EQ     // Jump to address 0x120 (in bytes) if ALU result is zero

  3:        JUMP       label         // Jump to label
            ...
    label:  nop                      // Definition of label

  4:        .global    label         // Declaration of global label

            MOVE       R1, label     // R1 = label (value loaded into R1 is in words)
            JUMP       R1            // Jump to label
            ...
    label:  nop                      // Definition of label

**JUMPR** – Jump to a relative offset (condition based on R0)
-------------------------------------------------------------

**Syntax**
   **JUMPR**        *Step, Threshold, Condition*

**Operands**
   - *Step*          – relative shift from current position, in bytes
   - *Threshold*     – threshold value for branch condition
   - *Condition*:
      - *GE* (greater or equal) – jump if value in R0 >= threshold

      - *LT* (less than) – jump if value in R0 < threshold

**Cycles**
  2 (fetch) + 2 (execute)

**Description**
   The instruction makes a jump to a relative address if condition is true. Condition is the result of comparison of R0 register value and the threshold value.

**Examples**::

  1:pos:    JUMPR       16, 20, GE   // Jump to address (position + 16 bytes) if value in R0 >= 20

  2:        // Down counting loop using R0 register
            MOVE        R0, 16       // load 16 into R0
    label:  SUB         R0, R0, 1    // R0--
            NOP                      // do something
            JUMPR       label, 1, GE // jump to label if R0 >= 1

**JUMPS** – Jump to a relative address (condition based on stage count)
-----------------------------------------------------------------------

**Syntax**
   **JUMPS**        *Step, Threshold, Condition*

**Operands**
   - *Step*       – relative shift from current position, in bytes
   - *Threshold*  – threshold value for branch condition
   - *Condition*:
       - *EQ* (equal) – jump if value in stage_cnt == threshold
       - *LT* (less than) –  jump if value in stage_cnt < threshold
       - *GT* (greater than) –  jump if value in stage_cnt > threshold

**Cycles**
  2 (fetch) + 2 (execute)

**Description**
    The instruction makes a jump to a relative address if condition is true. Condition is the result of comparison of count register value and threshold value.

**Examples**::

   1:pos:    JUMPS     16, 20, EQ     // Jump to (position + 16 bytes) if stage_cnt == 20

   2:        // Up counting loop using stage count register
             STAGE_RST                  // set stage_cnt to 0
     label:  STAGE_INC  1               // stage_cnt++
             NOP                        // do something
             JUMPS       label, 16, LT  // jump to label if stage_cnt < 16

**STAGE_RST** – Reset stage count register
------------------------------------------
**Syntax**
     **STAGE_RST**

**Operands**
   No operands

**Description**
   The instruction sets the stage count register to 0

**Cycles**
  2 (fetch) + 2 (execute)

**Examples**::

   1:       STAGE_RST      // Reset stage count register

**STAGE_INC** – Increment stage count register
----------------------------------------------

**Syntax**
  **STAGE_INC**      *Value*

**Operands**
   - *Value* – 8 bits value

**Cycles**
  2 (fetch) + 2 (execute)

**Description**
   The instruction increments stage count register by given value.

**Examples**::

  1:        STAGE_INC      10          // stage_cnt += 10

  2:        // Up counting loop example:
            STAGE_RST                  // set stage_cnt to 0
    label:  STAGE_INC  1               // stage_cnt++
            NOP                        // do something
            JUMPS      label, 16, LT   // jump to label if stage_cnt < 16

**STAGE_DEC** – Decrement stage count register
----------------------------------------------

**Syntax**
  **STAGE_DEC**      *Value*

**Operands**
   - *Value* – 8 bits value

**Cycles**
  2 (fetch) + 2 (execute)

**Description**
   The instruction decrements stage count register by given value.

**Examples**::

  1:        STAGE_DEC      10        // stage_cnt -= 10;

  2:        // Down counting loop exaple
            STAGE_RST                // set stage_cnt to 0
            STAGE_INC  16            // increment stage_cnt to 16
    label:  STAGE_DEC  1             // stage_cnt--;
            NOP                      // do something
            JUMPS      label, 0, GT  // jump to label if stage_cnt > 0

**HALT** – End the program
--------------------------

**Syntax**
  **HALT**

**Operands**
  No operands

**Cycles**
  2 (fetch) + 2 (execute)

**Description**
   The instruction halts the ULP coprocessor and restarts ULP wakeup timer, if it is enabled.

**Examples**::

  1:       HALT      // Halt the coprocessor

**WAKE** – Wake up the chip
---------------------------

**Syntax**
   **WAKE**

**Operands**
  No operands

**Cycles**
  2 (fetch) + 2 (execute)

**Description**
  The instruction sends an interrupt from ULP to RTC controller.

  - If the SoC is in deep sleep mode, and ULP wakeup is enabled, this causes the SoC to wake up.

  - If the SoC is not in deep sleep mode, and ULP interrupt bit (RTC_CNTL_ULP_CP_INT_ENA) is set in RTC_CNTL_INT_ENA_REG register, RTC interrupt will be triggered.

  Note that before using WAKE instruction, ULP program may needs to wait until RTC controller is ready to wake up the main CPU. This is indicated using RTC_CNTL_RDY_FOR_WAKEUP bit of RTC_CNTL_LOW_POWER_ST_REG register. If WAKE instruction is executed while RTC_CNTL_RDY_FOR_WAKEUP is zero, it has no effect (wake up does not occur).

**Examples**::

  1: is_rdy_for_wakeup:                   // Read RTC_CNTL_RDY_FOR_WAKEUP bit
            READ_RTC_FIELD(RTC_CNTL_LOW_POWER_ST_REG, RTC_CNTL_RDY_FOR_WAKEUP)
            AND r0, r0, 1
            JUMP is_rdy_for_wakeup, eq    // Retry until the bit is set
            WAKE                          // Trigger wake up
            REG_WR 0x006, 24, 24, 0       // Stop ULP timer (clear RTC_CNTL_ULP_CP_SLP_TIMER_EN)
            HALT                          // Stop the ULP program
            // After these instructions, SoC will wake up,
            // and ULP will not run again until started by the main program.

**SLEEP** – set ULP wakeup timer period
---------------------------------------

**Syntax**
  **SLEEP**   *sleep_reg*

**Operands**
   - *sleep_reg* – 0..4, selects one of ``SENS_ULP_CP_SLEEP_CYCx_REG`` registers.

**Cycles**
  2 (fetch) + 2 (execute)

**Description**
   The instruction selects which of the ``SENS_ULP_CP_SLEEP_CYCx_REG`` (x = 0..4) register values is to be used by the ULP wakeup timer as wakeup period. By default, the value from ``SENS_ULP_CP_SLEEP_CYC0_REG`` is used.

**Examples**::

  1:        SLEEP     1         // Use period set in SENS_ULP_CP_SLEEP_CYC1_REG

  2:        .set sleep_reg, 4   // Set constant
            SLEEP  sleep_reg    // Use period set in SENS_ULP_CP_SLEEP_CYC4_REG

**WAIT** – wait some number of cycles
-------------------------------------

**Syntax**
   **WAIT**   *Cycles*

**Operands**
   - *Cycles* – number of cycles for wait

**Cycles**
  2 (fetch) + *Cycles* (execute)

**Description**
   The instruction delays for given number of cycles.

**Examples**::

  1:        WAIT     10         // Do nothing for 10 cycles

  2:        .set  wait_cnt, 10  // Set a constant
            WAIT  wait_cnt      // wait for 10 cycles

**TSENS** – do measurement with temperature sensor
--------------------------------------------------

**Syntax**
   - **TSENS**   *Rdst, Wait_Delay*

**Operands**
  - *Rdst* – Destination Register R[0..3], result will be stored to this register
  - *Wait_Delay* – number of cycles used to perform the measurement

**Cycles**
  2 (fetch) + *Wait_Delay* + 3 * TSENS_CLK

**Description**
   The instruction performs measurement using TSENS and stores the result into a general purpose register.

**Examples**::

  1:        TSENS     R1, 1000     // Measure temperature sensor for 1000 cycles,
                                   // and store result to R1

**ADC** – do measurement with ADC
---------------------------------

**Syntax**
  - **ADC**   *Rdst, Sar_sel, Mux*

  - **ADC**   *Rdst, Sar_sel, Mux, 0* — deprecated form

**Operands**
  - *Rdst* – Destination Register R[0..3], result will be stored to this register
  - *Sar_sel* – Select ADC: 0 = SARADC1, 1 = SARADC2
  - *Mux*  -  selected PAD, SARADC Pad[Mux+1] is enabled

**Cycles**
  2 (fetch) + 21 + max(1, SAR_AMP_WAIT1) + max(1, SAR_AMP_WAIT2) + max(1, SAR_AMP_WAIT3) + SARx_SAMPLE_CYCLE + SARx_SAMPLE_BIT

**Description**
  The instruction makes measurements from ADC.

**Examples**::

   1:        ADC      R1, 0, 1      // Measure value using ADC1 pad 2 and store result into R1

**I2C_RD** - read single byte from I2C slave
----------------------------------------------

**Syntax**
  - **I2C_RD**   *Sub_addr, High, Low, Slave_sel*

**Operands**
  - *Sub_addr* – Address within the I2C slave to read.
  - *High*, *Low* — Define range of bits to read. Bits outside of [High, Low] range are masked.
  - *Slave_sel*  -  Index of I2C slave address to use.

**Cycles**
  2 (fetch) + I2C communication time

**Description**
  ``I2C_RD`` instruction reads one byte from I2C slave with index ``Slave_sel``. Slave address (in 7-bit format) has to be set in advance into `SENS_I2C_SLAVE_ADDRx` register field, where ``x == Slave_sel``.
  8 bits of read result is stored into `R0` register.

**Examples**::

   1:        I2C_RD      0x10, 7, 0, 0      // Read byte from sub-address 0x10 of slave with address set in SENS_I2C_SLAVE_ADDR0

**I2C_WR** - write single byte to I2C slave
----------------------------------------------

**Syntax**
  - **I2C_WR**   *Sub_addr, Value, High, Low, Slave_sel*

**Operands**
  - *Sub_addr* – Address within the I2C slave to write.
  - *Value* – 8-bit value to be written.
  - *High*, *Low* — Define range of bits to write. Bits outside of [High, Low] range are masked.
  - *Slave_sel*  -  Index of I2C slave address to use.

**Cycles**
  2 (fetch) + I2C communication time

**Description**
  ``I2C_WR`` instruction writes one byte to I2C slave with index ``Slave_sel``. Slave address (in 7-bit format) has to be set in advance into `SENS_I2C_SLAVE_ADDRx` register field, where ``x == Slave_sel``.

**Examples**::

   1:        I2C_WR      0x20, 0x33, 7, 0, 1      // Write byte 0x33 to sub-address 0x20 of slave with address set in SENS_I2C_SLAVE_ADDR1.

**REG_RD** – read from peripheral register
------------------------------------------

**Syntax**
   **REG_RD**   *Addr, High, Low*

**Operands**
  - *Addr* – register address, in 32-bit words
  - *High* – High part of R0
  - *Low* – Low part of R0

**Cycles**
  2 (fetch) + 6 (execute)

**Description**
   The instruction reads up to 16 bits from a peripheral register into a general purpose register: ``R0 = REG[Addr][High:Low]``.

   This instruction can access registers in RTC_CNTL, RTC_IO, SENS, and RTC_I2C peripherals. Address of the the register, as seen from the ULP,
   can be calculated from the address of the same register on the DPORT bus as follows::

    addr_ulp = (addr_dport - DR_REG_RTCCNTL_BASE) / 4

**Examples**::

  1:        REG_RD      0x120, 2, 0     // load 4 bits: R0 = {12'b0, REG[0x120][7:4]}

**REG_WR** – write to peripheral register
-----------------------------------------

**Syntax**
  **REG_WR**   *Addr, High, Low, Data*

**Operands**
  - *Addr* – register address, in 32-bit words.
  - *High* – High part of R0
  - *Low* – Low part of R0
  - *Data* – value to write, 8 bits

**Cycles**
  2 (fetch) + 10 (execute)

**Description**
   The instruction writes up to 8 bits from a general purpose register into a peripheral register. ``REG[Addr][High:Low] = data``

   This instruction can access registers in RTC_CNTL, RTC_IO, SENS, and RTC_I2C peripherals. Address of the the register, as seen from the ULP,
   can be calculated from the address of the same register on the DPORT bus as follows::

    addr_ulp = (addr_dport - DR_REG_RTCCNTL_BASE) / 4

**Examples**::

   1:        REG_WR      0x120, 7, 0, 0x10   // set 8 bits: REG[0x120][7:0] = 0x10

Convenience macros for peripheral registers access
--------------------------------------------------

ULP source files are passed through C preprocessor before the assembler. This allows certain macros to be used to facilitate access to peripheral registers.

Some existing macros are defined in ``soc/soc_ulp.h`` header file. These macros allow access to the fields of peripheral registers by their names.
Peripheral registers names which can be used with these macros are the ones defined in ``soc/rtc_cntl_reg.h``, ``soc/rtc_io_reg.h``, ``soc/sens_reg.h``, and ``soc/rtc_i2c_reg.h``.

READ_RTC_REG(rtc_reg, low_bit, bit_width)
  Read up to 16 bits from rtc_reg[low_bit + bit_width - 1 : low_bit] into R0. For example::

    #include "soc/soc_ulp.h"
    #include "soc/rtc_cntl_reg.h"

    /* Read 16 lower bits of RTC_CNTL_TIME0_REG into R0 */
    READ_RTC_REG(RTC_CNTL_TIME0_REG, 0, 16)

READ_RTC_FIELD(rtc_reg, field)
  Read from a field in rtc_reg into R0, up to 16 bits. For example::

    #include "soc/soc_ulp.h"
    #include "soc/sens_reg.h"

    /* Read 8-bit SENS_TSENS_OUT field of SENS_SAR_SLAVE_ADDR3_REG into R0 */
    READ_RTC_FIELD(SENS_SAR_SLAVE_ADDR3_REG, SENS_TSENS_OUT)

WRITE_RTC_REG(rtc_reg, low_bit, bit_width, value)
  Write immediate value into rtc_reg[low_bit + bit_width - 1 : low_bit], bit_width <= 8. For example::

    #include "soc/soc_ulp.h"
    #include "soc/rtc_io_reg.h"

    /* Set BIT(2) of RTC_GPIO_OUT_DATA_W1TS field in RTC_GPIO_OUT_W1TS_REG */
    WRITE_RTC_REG(RTC_GPIO_OUT_W1TS_REG, RTC_GPIO_OUT_DATA_W1TS_S + 2, 1, 1)

WRITE_RTC_FIELD(rtc_reg, field, value)
  Write immediate value into a field in rtc_reg, up to 8 bits. For example::

    #include "soc/soc_ulp.h"
    #include "soc/rtc_cntl_reg.h"

    /* Set RTC_CNTL_ULP_CP_SLP_TIMER_EN field of RTC_CNTL_STATE0_REG to 0 */
    WRITE_RTC_FIELD(RTC_CNTL_STATE0_REG, RTC_CNTL_ULP_CP_SLP_TIMER_EN, 0)


text:
from __future__ import absolute_import, division, print_function

import threading

from cryptography.hazmat.bindings.utils import (
    build_ffi_for_binding, load_library_for_binding,
)

class Binding(object):
    """
    CommonCrypto API wrapper.
    """
    _module_prefix = "cryptography.hazmat.bindings.commoncrypto."
    _modules = [
        "cf",
        "common_digest",
        "common_hmac",
        "common_key_derivation",
        "common_cryptor",
        "secimport",
        "secitem",
        "seckey",
        "seckeychain",
        "sectransform",
    ]

    ffi = build_ffi_for_binding(
        module_prefix=_module_prefix,
        modules=_modules,
        extra_link_args=[
            "-framework", "Security", "-framework", "CoreFoundation"
        ],
    )
    lib = None
    _init_lock = threading.Lock()

    def __init__(self):
        self._ensure_ffi_initialized()

    @classmethod
    def _ensure_ffi_initialized(cls):
        if cls.lib is not None:
            return

        with cls._init_lock:
            if cls.lib is None:
                cls.lib = load_library_for_binding(
                    cls.ffi,
                    module_prefix=cls._module_prefix,
                    modules=cls._modules,
                )


text:
#include "text.h"

#include "gba/gba.h"

/* Static variables used only by functions defined in this file */
static short txtPalette = 0;

/* Sets the palette used to render the text */
void txtSetPalette(short pal) {
   if (pal >= 0 && pal <= 15)
      txtPalette = (pal << 12);
}

/* Gets the palette used to render the text */
short txtGetPalette(void) {
   return (txtPalette >> 12);
}

/* Returns the number of digits in a number, including the '-' if negative */
short txtLenN(short n) {
   short len = 0;

   /* Add an extra digit to the length if negative */
   if (n < 0) {
      n = -n;
      len++;
   }

   if (n < 10)         /* Requires only one character  */
      len++;
   else if (n < 100)   /* Requires two characters      */
      len += 2;
   else if (n < 1000)  /* Requires three characters    */
      len += 3;
   else if (n < 10000) /* Requires four characters     */
      len += 4;
   else                /* Requires all five characters */
      len += 5;

   return len;
}

/* Prints a single character at the location specified */
void txtPrintC(short x, short y, char c) {
   unsigned short *tileMem = ScreenBaseBlockAddr(17) + (((y << 5) + x) << 1);
   *tileMem = txtPalette | txtIndexOf(c);
}

/* Prints a string beginning at the location specified */
void txtPrintS(short x, short y, const char* str, short len) {
   short i;

   for (i = 0; i < len; i++)
      txtPrintC(x++, y, *(str+i));
}

/* Prints a number beginning at the location specified */
void txtPrintN(short x, short y, short n) {
   /* A short can't take up more than 6 characters */
   char str[6];
   short nStart = 0;
   short nCur, len;

   /* Determine the length of the string */
   len = txtLenN(n);
   nCur = len - 1;

   /* If it's a negative number add the negate symbol */
   if (n < 0) {
      *str = '-';
      nStart++;
      n = -n;
   }

   /* Convert each decimal to a character, starting at the 1's digit */
   while (nCur >= nStart) {
      *(str + nCur--) = '0' + (n % 10);
      n /= 10;
   }

   /* Print the string we've created */
   txtPrintS(x, y, str, len);
}

/* Returns the tileset index of the specified character */
short txtIndexOf(char c) {
   /* We can map out alphanumerics mathematically */
   if (c >= 'A' && c <= 'Z')
      return (c - 'A' + 10);
   else if (c >= 'a' && c <= 'z')
      return (c - 'a' + 36);
   else if (c >= '0' && c <= '9')
      return (c - '0' + 62);

   /* "Special" Characters */
   switch (c) {
   case ':':
      return 72;
   case '/':
      return 73;
   case '.':
      return 74;
   case ',':
      return 75;
   case '-':
      return 76;
   default:
      break;
   }

   /* Default returns index of space ' ' */
   return 0;
}


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<title>JavaScript & jQuery:The Missing Manual</title>
<link href="../_css/site.css" rel="stylesheet">

JavaScript & jQuery The

      Missing

      Manual

Regular Expression Tester

Results (Matched text in red)

      <form action="" method="post" name="form1" id="regexTester">

Test

          String to search
          <textarea name="string" rows="3" class="wide" id="string"></textarea>

          Regular Expression to use
          <input name="regex" type="text" class="wide" id="regex">

Method to Use

            <input name="method" type="radio" id="search" value="search" checked>
            Search

            <input type="radio" name="method" id="match" value="match">
            Match

            <input type="radio" name="method" id="replace" value="replace">
            Replace

          Replace with:
          <input name="replaceString" type="text" class="medium" id="replaceString">

Options

            <input name="case" type="checkbox" id="case" value="i">
            Case Insensitive

            <input name="global" type="checkbox" id="global" value="g">
            Global

        <input type="submit" name="button" id="button" value="Run">
      </form>

JavaScript & jQuery: The Missing Manual, by David McFarland. Published by O'Reilly Media, Inc.

+

Test Beds

jQuery Selectors Testbed

jQuery Content Functions Test Bed

Events Test Bed

jQuery Effects Test Bed

Array Methods

Regular Expression Tester

jQuery Resources

jQuery

jQuery UI

jQuery Mobile

jQAPI.com


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Theatre.Storage;
using Theatre.Storage.Movies;

namespace Theatre.Storage
{
    public abstract class StorageDataSource
    {
        public abstract void GetNowPlaying(int onpage = 1, Action<List<Movie>> callback = null, DateTime ondate = new DateTime(), string cinema = "null");
        public abstract void GetUpcoming(int onpage = 1, Action<List<Movie>> callback = null);
        public abstract void GetExtendMovieInformation(Movie movie, Action<Movie> callback);

        public List<Movie> NowMovies;
        public List<Movie> UpcomingMovies;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LRWarehouse.Business
{
	public class EvaluationSummaryV2
	{
		public int ResourceId { get; set; }
		public int EvaluationId { get; set; } //ID of the evaluation session itself
		public int ContextId { get; set; } //Standard or Dimension ID
		public double ScorePercent { get; set; }
		public int TotalEvaluations { get; set; }
		public int CreatedById { get; set; }
		public string Title { get; set; }
		public string Description { get; set; }
	}

}


text:
package wherehows.dao.view;

import java.util.List;
import java.util.Map;
import javax.persistence.EntityManagerFactory;

public class DataTypesViewDao extends BaseViewDao {

  public DataTypesViewDao(EntityManagerFactory factory) {
    super(factory);
  }

  /**
   * Get all compliance dataTypes
   */
  public List<Map<String, Object>> getAllComplianceDataTypes() throws Exception {
    throw new UnsupportedOperationException("Operation not implemented");
  }

  /**
   * Get all data platforms
   */
  public List<Map<String, Object>> getAllPlatforms() throws Exception {
    throw new UnsupportedOperationException("Operation not implemented");
  }
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no,target-densitydpi=medium-dpi">
        <title>blog-Bootstrap기반 반응형웹 html 템플릿</title>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                        Toggle navigation

                    </button>
                     BS-html-examples

View on GitHub

작업중 입니다.

Blog

default

list 목록

list-nopost 목록-게시물 없음

view 보기

write 쓰기

List

    blog-list
    ├── blog-heading
    │   ├── search-result
    │   └── toolbar
    ├── blog-body
    │   └── table
    └── blog-footer
        ├── pagination
        ├── toolbar
        └── search

                                코드보기

View

    blog-view
    ├── blog-heading
    │   ├── user photo
    │   ├── meta data
    │   └── toolbar
    ├── blog-body
    └── blog-footer
        ├── tag
        ├── attach
        ├── toolbar
        ├── comment
        └── trackback

                                코드보기

Write

    blog-write
    ├── category
    ├── title
    ├── option
    ├── toolbar
    ├── editor
    ├── attach-file
    ├── attach-photo
    ├── tag
    ├── option
    └── toolbar

                                코드보기

웹서비스 html 템플릿 maintained by gitaeks

Published with GitHub Pages


text:
  * Changed handling of base64 encoded mime words where multiple words are joined together if possible. This fixes issues with multi byte characters getting split into different mime words (against the RFC but occurs)

## v2.0.3 2016-02-29

  * Fixed an issue with rfc2231 filenames

## v2.0.2 2016-02-11

  * Fixed an issue with base64 mime words encoding

## v2.0.1 2016-02-11

  * Fix base64 mime-word encoding. Final string length was calculated invalidly

## v2.0.0 2016-01-04

  * Replaced jshint with eslint
  * Refactored file structure

## v1.2.1 2015-10-05

Added support for emojis in header params (eg. filenames)

## v1.2.0 2015-10-05

Added support for emojis in header params (eg. filenames)

## v1.1.0 2015-09-24

Updated encoded word encoding with quoted printable, should be more like required in https://tools.ietf.org/html/rfc2047#section-5

## v1.0.0 2015-04-15

Changed versioning scheme to use 1.x instead of 0.x versions. Bumped dependency versions, no actual code changes.

## v0.1.7 2015-01-19

Updated unicode filename handling – only revert to parameter continuation if the value actually includes
non-ascii characters or is too long. Previously filenames were encoded if they included anything
besides letters, numbers, dot or space.

## v0.1.6 2014-10-25

Fixed an issue with `encodeWords` where a trailing space was invalidly included in a word if the word
ended with an non-ascii character.

## v0.1.5 2014-09-12

Do not use quotes for continuation encoded filename parts. Fixes an issue with Gmail where the Gmail webmail keeps the charset as part of the filename.


text:
f = open("flowsFromMathematica.txt", "rt")
flowStr = f.read()
f.close()

flowStr = flowStr.replace("\"", "") #remove quotes
flowStr = flowStr.replace(" ", "") #remove spaces
flowStr = flowStr.replace("\n", "") #remove line breaks
flowStr = flowStr[1:-1] #remove brakets

flows = flowStr.split("},{")
flows[0] = flows[0].replace("{", "")
flows[-1] = flows[-1].replace("}", "")

f = open("flowsFromMathematica4Db.txt", "wt")

clusterNumber = 0
for flow in flows:
	clusterNumber += 1
	ops = flow.split(",")
	stepNumber = 0
	for op in ops:
		stepNumber += 1
		f.write(str(clusterNumber) + "\t" + op + "\t" + str(stepNumber) +"\n")

f.close()


text:
'use strict';

var TypedError = require('error/typed');

var ManyErrors = module.exports.ManyErrors = TypedError({
    type: 'many.errors',
    message: '{count} errors. Example: {example}',
    count: null,
    example: null,
    errors: null
});

module.exports.resultArrayToError = resultArrayToError;

function resultArrayToError(items, type, message) {
    var errors = [];
    var i;
    for (i = 0; i < items.length; i++) {
        if (items[i].err) {
            errors.push(items[i].err);
        }
    }

    return errorArrayToError(errors, type, message);
}

module.exports.errorArrayToError = errorArrayToError;

function errorArrayToError(errors, type, message) {
    if (errors.length === 0) {
        return null;
    } else if (errors.length === 1) {
        return errors[0];
    } else {
        return ManyErrors({
            message: message,
            type: type,
            errors: errors,
            count: errors.length,
            example: errors[0].message
        });
    }
}


text:
package ch.jalu.injector.handlers.dependency.providers;

import javax.inject.Inject;

/**
 * Test class.
 */
public class Charlie {

    @Inject
    private Alfa alfa;

    @Inject
    private Bravo bravo;

    Charlie() {
    }

    public String getString() {
        return bravo.getServiceName() + alfa.transform("_Charlie");
    }
}


text:
/**
 * <fullname>Elastic Load Balancing</fullname>
 *

 * A load balancer distributes incoming traffic across targets, such as your EC2 instances. This enables you to increase
 * the availability of your application. The load balancer also monitors the health of its registered targets and
 * ensures that it routes traffic only to healthy targets. You configure your load balancer to accept incoming traffic
 * by specifying one or more listeners, which are configured with a protocol and port number for connections from
 * clients to the load balancer. You configure a target group with a protocol and port number for connections from the
 * load balancer to the targets, and with health check settings to be used when checking the health status of the
 * targets.
 *

 *

 * Elastic Load Balancing supports two types of load balancers: Classic Load Balancers and Application Load Balancers. A
 * Classic Load Balancer makes routing and load balancing decisions either at the transport layer (TCP/SSL) or the
 * application layer (HTTP/HTTPS), and supports either EC2-Classic or a VPC. An Application Load Balancer makes routing
 * and load balancing decisions at the application layer (HTTP/HTTPS), supports path-based routing, and can route
 * requests to one or more ports on each EC2 instance or container instance in your virtual private cloud (VPC). For
 * more information, see the Elastic Load
 * Balancing User Guide.
 *

 *

 * This reference covers the 2015-12-01 API, which supports Application Load Balancers. The 2012-06-01 API supports
 * Classic Load Balancers.
 *

 *

 * To get started, complete the following tasks:
 *

 *

 *

 *

 * Create an Application Load Balancer using CreateLoadBalancer.
 *

 *

 *

 *

 * Create a target group using CreateTargetGroup.
 *

 *

 *

 *

 * Register targets for the target group using RegisterTargets.
 *

 *

 *

 *

 * Create one or more listeners for your load balancer using CreateListener.
 *

 *

 *

 *

 * (Optional) Create one or more rules for content routing based on URL using CreateRule.
 *

 *

 *

 *

 * To delete an Application Load Balancer and its related resources, complete the following tasks:
 *

 *

 *

 *

 * Delete the load balancer using DeleteLoadBalancer.
 *

 *

 *

 *

 * Delete the target group using DeleteTargetGroup.
 *

 *

 *

 *

 * All Elastic Load Balancing operations are idempotent, which means that they complete at most one time. If you repeat
 * an operation, it succeeds.
 *

 */
package com.amazonaws.services.elasticloadbalancingv2;


text:
<!DOCTYPE html>

		<title>three.js webgl - fire</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<link type="text/css" rel="stylesheet" href="main.css">

			three.js fire and smoke demo


text:
package com.mrxiong.argot.store.cp;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by Ted on 2016/1/25.
 *
 * @ com.mrxiong.argot.db.cp
 */
public class BaseSQLiteHelper extends SQLiteOpenHelper {
  public static final String DATABASE_NAME = "inputer.db";
  public static final int DATABASE_VERSION = 1;

  public BaseSQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }

  @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    ArgotDb.updateDb(db, oldVersion, newVersion);
    AppExDb.updateDb(db, oldVersion, newVersion);
  }

  @Override public void onCreate(SQLiteDatabase db) {
    ArgotDb.createDb(db);
    AppExDb.createDb(db);
  }
}