text:
using System;
using java = biz.ritter.javapi;

namespace biz.ritter.javapi.util.prefs{

/**
 * This abstract class is a partial implementation of the abstract class
 * Preferences, which can be used to simplify {@code Preferences} provider's
 * implementation. This class defines nine abstract SPI methods, which must be
 * implemented by a preference provider.
 *
 * @since 1.4
 * @see Preferences
 */
public abstract class AbstractPreferences : Preferences {
    /*
     * ----------------------------------------------------------- Class fields
     * -----------------------------------------------------------
     */
    /** the unhandled events collection */
    private static readonly List<EventObject> events = new LinkedList<EventObject>();
    /** the event dispatcher thread */
    private static readonly EventDispatcher dispatcher = new EventDispatcher(
            "Preference Event Dispatcher"); //$NON-NLS-1$

    /*
     * ----------------------------------------------------------- Class
     * initializer -----------------------------------------------------------
     */
		static AbstractPreferences(){
        dispatcher.setDaemon(true);
        dispatcher.start();
        java.lang.Runtime.getRuntime().addShutdownHook(new IC_Thread());
    }
		class IC_Thread : java.lang.Thread {
			public override void run() {
				Preferences uroot = Preferences.userRoot();
				Preferences sroot = Preferences.systemRoot();
				try {
					uroot.flush();
				} catch (BackingStoreException e) {
					// ignore
				}
				try {
					sroot.flush();
				} catch (BackingStoreException e) {
					// ignore
				}
			}
		}

    /*
     * ----------------------------------------------------------- Instance
     * fields (package-private)
     * -----------------------------------------------------------
     */
    /** true if this node is in user preference hierarchy */
    bool userNode;

    /*
     * ----------------------------------------------------------- Instance
     * fields (private)
     * -----------------------------------------------------------
     */
    /** Marker class for 'lock' field. */
    private class Lock {
    }

    /**
     * The object used to lock this node.
     */
    protected internal readonly Object lockJ;

    /**
     * This field is true if this node is created while it doesn't exist in the
     * backing store. This field's default value is false, and it is checked
     * when the node creation is completed, and if it is true, the node change
     * event will be fired for this node's parent.
     */
    protected bool newNode;

    /** cached child nodes */
    private Map<String, AbstractPreferences> cachedNode;

    // the collections of listeners
    private List<EventListener> nodeChangeListeners;
    private List<EventListener> preferenceChangeListeners;

    // this node's name
    private String nodeName;

    // handler to this node's parent
    private AbstractPreferences parentPref;

    // true if this node has been removed
    private bool isRemovedJ;

    // handler to this node's root node
    private AbstractPreferences root;

    /*
     * ----------------------------------------------------------- Constructors
     * -----------------------------------------------------------
     */
    /**
     * Constructs a new {@code AbstractPreferences} instance using the given
     * parent node and node name.
     *
     * @param parent
     *            the parent node of the new node or {@code null} to indicate
     *            that the new node is a root node.
     * @param name
     *            the name of the new node or an empty string to indicate that
     *            this node is called "root".
     * @throws IllegalArgumentException
     *             if the name contains a slash character or is empty if {@code
     *             parent} is not {@code null}.
     */
    protected AbstractPreferences(AbstractPreferences parent, String name) {
        if ((null == parent ^ name.length() == 0) || name.indexOf("/") >= 0) { //$NON-NLS-1$
            throw new java.lang.IllegalArgumentException();
        }
        root = null == parent ? this : parent.root;
        nodeChangeListeners = new LinkedList<EventListener>();
        preferenceChangeListeners = new LinkedList<EventListener>();
        isRemovedJ = false;
        cachedNode = new HashMap<String, AbstractPreferences>();
        nodeName = name;
        parentPref = parent;
        lockJ = new Lock();
        userNode = root.userNode;
    }

    /*
     * ----------------------------------------------------------- Methods
     * -----------------------------------------------------------
     */
    /**
     * Returns an array of all cached child nodes.
     *
     * @return the array of cached child nodes.
     */
    protected /*final*/ AbstractPreferences[] cachedChildren() {
        return cachedNode.values().toArray(
                new AbstractPreferences[cachedNode.size()]);
    }

    /**
     * Returns the child node with the specified name or {@code null} if it
     * doesn't exist. Implementers can assume that the name supplied to this
     * method will be a valid node name string (conforming to the node naming
     * format) and will not correspond to a node that has been cached or
     * removed.
     *
     * @param name
     *            the name of the desired child node.
     * @return the child node with the given name or {@code null} if it doesn't
     *         exist.
     * @throws BackingStoreException
     *             if the backing store is unavailable or causes an operation
     *             failure.
     */
    protected AbstractPreferences getChild(String name)
		{// throws BackingStoreException {
        lock (lockJ) {
            checkState();
            AbstractPreferences result = null;
            String[] childrenNamesJ = childrenNames();
            for (int i = 0; i < childrenNamesJ.Length; i++) {
                if (childrenNamesJ[i].equals(name)) {
                    result = childSpi(name);
                    break;
                }
            }
            return result;
        }

    }

    /**
     * Returns whether this node has been removed by invoking the method {@code
     * removeNode()}.
     *
     * @return {@code true}, if this node has been removed, {@code false}
     *         otherwise.
     */
    protected internal bool isRemoved() {
        lock (lockJ) {
            return isRemovedJ;
        }
    }

    /**
     * Flushes changes of this node to the backing store. This method should
     * only flush this node and should not include the descendant nodes. Any
     * implementation that wants to provide functionality to flush all nodes at
     * once should override the method {@link #flush() flush()}.
     *
     * @throws BackingStoreException
     *             if the backing store is unavailable or causes an operation
     *             failure.
     */
		protected abstract void flushSpi ();// throws BackingStoreException;

    /**
     * Returns the names of all of the child nodes of this node or an empty
     * array if this node has no children. The names of cached children are not
     * required to be returned.
     *
     * @return the names of this node's children.
     * @throws BackingStoreException
     *             if the backing store is unavailable or causes an operation
     *             failure.
     */
		protected abstract String[] childrenNamesSpi ();// throws BackingStoreException;

    /**
     * Returns the child preference node with the given name, creating it if it
     * does not exist. The caller of this method should ensure that the given
     * name is valid and that this node has not been removed or cached. If the
     * named node has just been removed, the implementation of this method must
     * create a new one instead of reactivating the removed one.
     * <p>
     * The new creation is not required to be persisted immediately until the
     * flush method will be invoked.
     * </p>
     *
     * @param name
     *            the name of the child preference to be returned.
     * @return the child preference node.
     */
    protected abstract AbstractPreferences childSpi(String name);

    /**
     * Puts the given key-value pair into this node. Caller of this method
     * should ensure that both of the given values are valid and that this node
     * has not been removed.
     *
     * @param name
     *            the given preference key.
     * @param value
     *            the given preference value.
     */
    protected abstract void putSpi(String name, String value);

    /**
     * Gets the preference value mapped to the given key. The caller of this
     * method should ensure that the given key is valid and that this node has
     * not been removed. This method should not throw any exceptions but if it
     * does, the caller will ignore the exception, regarding it as a {@code
     * null} return value.
     *
     * @param key
     *            the given key to be searched for.
     * @return the preference value mapped to the given key.
     */
    protected abstract String getSpi(String key);

    /**
     * Returns an array of all preference keys of this node or an empty array if
     * no preferences have been found. The caller of this method should ensure
     * that this node has not been removed.
     *
     * @return the array of all preference keys.
     * @throws BackingStoreException
     *             if the backing store is unavailable or causes an operation
     *             failure.
     */
		protected abstract String[] keysSpi();// throws BackingStoreException;

    /**
     * Removes this node from the preference hierarchy tree. The caller of this
     * method should ensure that this node has no child nodes, which means the
     * method {@link Preferences#removeNode() Preferences.removeNode()} should
     * invoke this method multiple-times in bottom-up pattern. The removal is
     * not required to be persisted until after it is flushed.
     *
     * @throws BackingStoreException
     *             if the backing store is unavailable or causes an operation
     *             failure.
     */
		protected abstract void removeNodeSpi();// throws BackingStoreException;

    /**
     * Removes the preference with the specified key. The caller of this method
     * should ensure that the given key is valid and that this node has not been
     * removed.
     *
     * @param key
     *            the key of the preference that is to be removed.
     */
    protected abstract void removeSpi(String key);

    /**
     * Synchronizes this node with the backing store. This method should only
     * synchronize this node and should not include the descendant nodes. An
     * implementation that wants to provide functionality to synchronize all
     * nodes at once should override the method {@link #sync() sync()}.
     *
     * @throws BackingStoreException
     *             if the backing store is unavailable or causes an operation
     *             failure.
     */
		protected abstract void syncSpi();// throws BackingStoreException;

    /*
     * ----------------------------------------------------------- Methods
     * inherited from Preferences
     * -----------------------------------------------------------
     */

    public override String absolutePath() {
        if (parentPref == null) {
            return "/"; //$NON-NLS-1$
        } else if (parentPref == root) {
            return "/" + nodeName; //$NON-NLS-1$
        }
        return parentPref.absolutePath() + "/" + nodeName; //$NON-NLS-1$
    }

    public override String[] childrenNames(){// throws BackingStoreException {
        lock (lockJ) {
            checkState();
            TreeSet<String> result = new TreeSet<String>(cachedNode.keySet());
            String[] names = childrenNamesSpi();
            for (int i = 0; i < names.Length; i++) {
                result.add(names[i]);
            }
            return result.toArray(new String[result.size()]);
        }
    }

    public override void clear() {//throws BackingStoreException {
        lock (lockJ) {
            String[] keyList = keys();
            for (int i = 0; i < keyList.Length; i++) {
                remove(keyList[i]);
            }
        }
    }

    public override void exportNode(java.io.OutputStream ostream) //throws IOException,
		{//BackingStoreException {
        if (ostream == null) {
            // prefs.5=Stream is null
				throw new java.lang.NullPointerException("Stream is null"); //$NON-NLS-1$
        }
        checkState();
        XMLParser.exportPrefs(this, ostream, false);

    }

    public override void exportSubtree(java.io.OutputStream ostream) //throws IOException,
		{//BackingStoreException {
        if (ostream == null) {
            // prefs.5=Stream is null
				throw new java.lang.NullPointerException("Stream is null"); //$NON-NLS-1$
        }
        checkState();
        XMLParser.exportPrefs(this, ostream, true);
    }

    public override void flush(){// throws BackingStoreException {
        lock (lockJ) {
            flushSpi();
        }
        AbstractPreferences[] cc = cachedChildren();
        int i;
        for (i = 0; i < cc.Length; i++) {
            cc[i].flush();
        }
    }

    public override String get(String key, String deflt) {
        if (key == null) {
            throw new java.lang.NullPointerException();
        }
        String result = null;
        lock (lockJ) {
            checkState();
            try {
                result = getSpi(key);
            } catch (Exception e) {
                // ignored
            }
        }
        return (result == null ? deflt : result);
    }

    public override bool getBoolean(String key, bool deflt) {
        String result = get(key, null);
        if (result == null) {
            return deflt;
        }
        if ("true".equalsIgnoreCase(result)) { //$NON-NLS-1$
            return true;
        } else if ("false".equalsIgnoreCase(result)) { //$NON-NLS-1$
            return false;
        } else {
            return deflt;
        }
    }

    public override byte[] getByteArray(String key, byte[] deflt) {
        java.lang.StringJ svalue = get(key, null);
        if (svalue == null) {
            return deflt;
        }
        if (svalue.length() == 0) {
            return new byte[0];
        }
        try {
            byte[] bavalue = svalue.getBytes("US-ASCII"); //$NON-NLS-1$
            if (bavalue.Length % 4 != 0) {
                return deflt;
            }
			return new java.lang.StringJ(System.Text.Encoding.ASCII.GetString(Convert.FromBase64String(svalue))).getBytes ();
            //return Base64.decode(bavalue);
        } catch (Exception e) {
            return deflt;
        }
    }

    public override double getDouble(String key, double deflt) {
        String result = get(key, null);
        if (result == null) {
            return deflt;
        }
        try {
            return java.lang.Double.parseDouble(result);
        } catch (java.lang.NumberFormatException e) {
            return deflt;
        }
    }

    public override float getFloat(String key, float deflt) {
        String result = get(key, null);
        if (result == null) {
            return deflt;
        }
        try {
            return java.lang.Float.parseFloat(result);
        } catch (java.lang.NumberFormatException e) {
            return deflt;
        }
    }

    public override int getInt(String key, int deflt) {
        String result = get(key, null);
        if (result == null) {
            return deflt;
        }
        try {
            return java.lang.Integer.parseInt(result);
        } catch (java.lang.NumberFormatException e) {
            return deflt;
        }
    }

    public override long getLong(String key, long deflt) {
        String result = get(key, null);
        if (result == null) {
            return deflt;
        }
        try {
            return java.lang.Long.parseLong(result);
        } catch (java.lang.NumberFormatException e) {
            return deflt;
        }
    }

    public override bool isUserNode() {
        return root == Preferences.userRoot();
    }

    public override String[] keys(){// throws BackingStoreException {
        lock (lockJ) {
            checkState();
            return keysSpi();
        }
    }

    public override String name() {
        return nodeName;
    }

    public override Preferences node(String name) {
        AbstractPreferences startNode = null;
        lock (lockJ) {
            checkState();
            validateName(name);
            if ("".equals(name)) { //$NON-NLS-1$
                return this;
            } else if ("/".equals(name)) { //$NON-NLS-1$
                return root;
            }
            if (name.startsWith("/")) { //$NON-NLS-1$
                startNode = root;
                name = name.substring(1);
            } else {
                startNode = this;
            }
        }
        try {
            return startNode.nodeImpl(name, true);
        } catch (BackingStoreException e) {
            // should not happen
            return null;
        }
    }

    private void validateName(String name) {
        if (name.endsWith("/") && name.length() > 1) { //$NON-NLS-1$
            // prefs.6=Name cannot end with '/'
				throw new java.lang.IllegalArgumentException("Name cannot end with '/'"); //$NON-NLS-1$
        }
        if (name.indexOf("//") >= 0) { //$NON-NLS-1$
            // prefs.7=Name cannot contains consecutive '/'
				throw new java.lang.IllegalArgumentException("Name cannot contains consecutive '/'"); //$NON-NLS-1$
        }
    }

    private AbstractPreferences nodeImpl(String path, bool createNew)
		{//throws BackingStoreException {

        String[] names = path.split("/");//$NON-NLS-1$
        AbstractPreferences currentNode = this;
        AbstractPreferences temp = null;

        for (int i = 0; i < names.Length; i++) {
            String name = names[i];
            lock (currentNode.lockJ) {
                temp = currentNode.cachedNode.get(name);
                if (temp == null) {
                    temp = getNodeFromBackend(createNew, currentNode, name);
                }
            }
            currentNode = temp;
            if (null == currentNode) {
                break;
            }
        }
        return currentNode;
    }

    private AbstractPreferences getNodeFromBackend(bool createNew,
            AbstractPreferences currentNode, String name)
		{//throws BackingStoreException {
        if (name.length() > MAX_NAME_LENGTH) {
            // prefs.8=Name length is too long: {0}
				throw new java.lang.IllegalArgumentException("Name length is too long: "+
                    name);
        }
        AbstractPreferences temp;
        if (createNew) {
            temp = currentNode.childSpi(name);
            currentNode.cachedNode.put(name, temp);
            if (temp.newNode && currentNode.nodeChangeListeners.size() > 0) {
                currentNode.notifyChildAdded(temp);
            }
        } else {
            temp = currentNode.getChild(name);
        }
        return temp;
    }

    public override bool nodeExists(String name) {//throws BackingStoreException {
        if (null == name) {
            throw new java.lang.NullPointerException();
        }
        AbstractPreferences startNode = null;
        lock (lockJ) {
            if (isRemoved()) {
                if ("".equals(name)) { //$NON-NLS-1$
                    return false;
                }
                // prefs.9=This node has been removed
					throw new java.lang.IllegalStateException("This node has been removed"); //$NON-NLS-1$
            }
            validateName(name);
            if ("".equals(name) || "/".equals(name)) { //$NON-NLS-1$ //$NON-NLS-2$
                return true;
            }
            if (name.startsWith("/")) { //$NON-NLS-1$
                startNode = root;
                name = name.substring(1);
            } else {
                startNode = this;
            }
        }
        try {
            Preferences result = startNode.nodeImpl(name, false);
            return null == result ? false : true;
        } catch (java.lang.IllegalArgumentException e) {
            return false;
        }
    }

    public override Preferences parent() {
        checkState();
        return parentPref;
    }

    private void checkState() {
        if (isRemoved()) {
            // prefs.9=This node has been removed
				throw new java.lang.IllegalStateException("This node has been removed"); //$NON-NLS-1$
        }
    }

    public override void put(String key, String value) {
        if (null == key || null == value) {
            throw new java.lang.NullPointerException();
        }
        if (key.length() > MAX_KEY_LENGTH || value.length() > MAX_VALUE_LENGTH) {
            throw new java.lang.IllegalArgumentException();
        }
        lock (lockJ) {
            checkState();
            putSpi(key, value);
        }
        notifyPreferenceChange(key, value);
    }

    public override void putBoolean(String key, bool value) {
        String sval = java.lang.StringJ.valueOf(value);
        put(key, sval);
    }

    public override void putByteArray(String key, byte[] value) {
        try {
			put (key, Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(new java.lang.StringJ(value))));
            //put(key, Base64.encode(value, "US-ASCII")); //$NON-NLS-1$
        } catch (java.io.UnsupportedEncodingException e) {
            throw new java.lang.AssertionError(e);
        }
    }

    public override void putDouble(String key, double value) {
        String sval = java.lang.Double.toString(value);
        put(key, sval);
    }

    public override void putFloat(String key, float value) {
        String sval = java.lang.Float.toString(value);
        put(key, sval);
    }

    public override void putInt(String key, int value) {
        String sval = java.lang.Integer.toString(value);
        put(key, sval);
    }

    public override void putLong(String key, long value) {
        String sval = java.lang.Long.toString(value);
        put(key, sval);
    }

    public override void remove(String key) {
        lock (lockJ) {
            checkState();
            removeSpi(key);
        }
        notifyPreferenceChange(key, null);
    }

    public override void removeNode(){// throws BackingStoreException {
        if (root == this) {
            // prefs.A=Cannot remove root node
				throw new java.lang.UnsupportedOperationException("Cannot remove root node!"); //$NON-NLS-1$
        }
        lock (parentPref.lockJ) {
            removeNodeImpl();
        }
    }

    private void removeNodeImpl(){// throws BackingStoreException {
        lock (lockJ) {
            checkState();
            String[] childrenNames = childrenNamesSpi();
            for (int i = 0; i < childrenNames.Length; i++) {
                if (null == cachedNode.get(childrenNames[i])) {
                    AbstractPreferences child = childSpi(childrenNames[i]);
                    cachedNode.put(childrenNames[i], child);
                }
            }

            java.util.Collection<AbstractPreferences> values = cachedNode.values();
            AbstractPreferences[] children = values
                    .toArray(new AbstractPreferences[values.size()]);
            foreach (AbstractPreferences child in children) {
                child.removeNodeImpl();
            }
            removeNodeSpi();
            isRemovedJ = true;
            parentPref.cachedNode.remove(nodeName);
        }
        if (parentPref.nodeChangeListeners.size() > 0) {
            parentPref.notifyChildRemoved(this);
        }
    }

    public override void addNodeChangeListener(NodeChangeListener ncl) {
        if (null == ncl) {
            throw new java.lang.NullPointerException();
        }
        checkState();
        lock (nodeChangeListeners) {
            nodeChangeListeners.add(ncl);
        }
    }

    public override void addPreferenceChangeListener(PreferenceChangeListener pcl) {
        if (null == pcl) {
            throw new java.lang.NullPointerException();
        }
        checkState();
        lock (preferenceChangeListeners) {
            preferenceChangeListeners.add(pcl);
        }
    }

    public override void removeNodeChangeListener(NodeChangeListener ncl) {
        checkState();
        lock (nodeChangeListeners) {
            int pos;
            if ((pos = nodeChangeListeners.indexOf(ncl)) == -1) {
                throw new java.lang.IllegalArgumentException();
            }
            nodeChangeListeners.remove(pos);
        }
    }

    public override void removePreferenceChangeListener(PreferenceChangeListener pcl) {
        checkState();
        lock (preferenceChangeListeners) {
            int pos;
            if ((pos = preferenceChangeListeners.indexOf(pcl)) == -1) {
                throw new java.lang.IllegalArgumentException();
            }
            preferenceChangeListeners.remove(pos);
        }
    }

    public override void sync(){// throws BackingStoreException {
        lock (lockJ) {
            checkState();
            syncSpi();
        }
        AbstractPreferences[] cc = cachedChildren();
        int i;
        for (i = 0; i < cc.Length; i++) {
            cc[i].sync();
        }
    }

    public override String ToString() {
        java.lang.StringBuilder sb = new java.lang.StringBuilder();
        sb.append(isUserNode() ? "User" : "System"); //$NON-NLS-1$ //$NON-NLS-2$
        sb.append(" Preference Node: "); //$NON-NLS-1$
        sb.append(absolutePath());
        return sb.toString();
    }

    private void notifyChildAdded(Preferences child) {
        NodeChangeEvent nce = new NodeAddEvent(this, child);
        lock (events) {
            events.add(nce);
            events.notifyAll();
        }
    }

    private void notifyChildRemoved(Preferences child) {
        NodeChangeEvent nce = new NodeRemoveEvent(this, child);
        lock (events) {
            events.add(nce);
            events.notifyAll();
        }
    }

    private void notifyPreferenceChange(String key, String newValue) {
        PreferenceChangeEvent pce = new PreferenceChangeEvent(this, key,
                newValue);
        lock (events) {
            events.add(pce);
            events.notifyAll();
        }
    }

    private class EventDispatcher : java.lang.Thread {
        internal EventDispatcher(String name) :
            base(name){
        }

        public override void run() {
            while (true) {
                EventObject eventJ = null;
                try {
                    eventJ = getEventObject();
                } catch (java.lang.InterruptedException e) {
                    e.printStackTrace();
                    continue;
                }
                AbstractPreferences pref = (AbstractPreferences) eventJ
                        .getSource();
                if (eventJ is NodeAddEvent) {
                    dispatchNodeAdd((NodeChangeEvent) eventJ,
                            pref.nodeChangeListeners);
                } else if (eventJ is NodeRemoveEvent) {
                    dispatchNodeRemove((NodeChangeEvent) eventJ,
                            pref.nodeChangeListeners);
                } else if (eventJ is PreferenceChangeEvent) {
                    dispatchPrefChange((PreferenceChangeEvent) eventJ,
                            pref.preferenceChangeListeners);
                }
            }
        }

        private EventObject getEventObject() {//throws InterruptedException {
            lock (events) {
                if (events.isEmpty()) {
                    events.wait();
                }
                EventObject eventJ = events.get(0);
                events.remove(0);
                return eventJ;
            }
        }

        private void dispatchPrefChange(PreferenceChangeEvent eventJ,
                List<EventListener> preferenceChangeListeners) {
            lock (preferenceChangeListeners) {
                Iterator<EventListener> i = preferenceChangeListeners
                        .iterator();
                while (i.hasNext()) {
                    PreferenceChangeListener pcl = (PreferenceChangeListener) i
                            .next();
                    pcl.preferenceChange(eventJ);
                }
            }
        }

        private void dispatchNodeRemove(NodeChangeEvent eventJ,
                List<EventListener> nodeChangeListeners) {
            lock (nodeChangeListeners) {
                Iterator<EventListener> i = nodeChangeListeners.iterator();
                while (i.hasNext()) {
                    NodeChangeListener ncl = (NodeChangeListener) i.next();
                    ncl.childRemoved(eventJ);
                }
            }
        }

        private void dispatchNodeAdd(NodeChangeEvent eventJ,
                List<EventListener> nodeChangeListeners) {
            lock (nodeChangeListeners) {
                Iterator<EventListener> i = nodeChangeListeners.iterator();
                while (i.hasNext()) {
                    NodeChangeListener ncl = (NodeChangeListener) i.next();
                    ncl.childAdded(eventJ);
                }
            }
        }
    }

    private class NodeAddEvent : NodeChangeEvent {
        // The base class is NOT serializable, so this class isn't either.
        private static readonly long serialVersionUID = 1L;

        public NodeAddEvent(Preferences p, Preferences c) :
            base(p, c){
        }
    }

    private class NodeRemoveEvent : NodeChangeEvent {
        // The base class is NOT serializable, so this class isn't either.
        private static readonly long serialVersionUID = 1L;

        public NodeRemoveEvent(Preferences p, Preferences c) :
            base(p, c){
        }
    }
}
}


text:
import {DistributedObject} from '../core';

/**
 * A distributed, concurrent countdown latch data structure.
 *
 * ICountDownLatch is a cluster-wide synchronization aid
 * that allows one or more callers to wait until a set of operations being
 * performed in other callers completes.
 *
 * ICountDownLatch count can be reset using `trySetCount()` method after
 * a countdown has finished but not during an active count. This allows
 * the same latch instance to be reused.
 *
 * There is no `await()` method to do an unbound wait since this is undesirable
 * in a distributed application: for example, a cluster can split, or the master
 * and replicas could all die. In most cases, it is best to configure
 * an explicit timeout, so you have the ability to deal with these situations.
 *
 * All of the API methods in the ICountDownLatch offer the exactly-once
 * execution semantics. For instance, even if a `countDown()` call is
 * internally retried because of crashed Hazelcast member, the counter
 * value is decremented only once.
 */
export interface ICountDownLatch extends DistributedObject {

    /**
     * Causes the call to wait until the latch has counted down to
     * zero, or an exception is thrown, or the specified waiting time elapses.
     *
     * If the current count is zero then the promise resolves immediately
     * with the value `true`.
     *
     * If the current count is greater than zero, then the promise
     * is fulfilled only when one of the following things happen:
     *

     *

     * the count reaches zero due to invocations of the `countDown()` method,
     *

     *

     * this ICountDownLatch instance is destroyed,
     *

     *

     * the countdown owner becomes disconnected,
     *

     *

     * the specified waiting time elapses.
     *

     *

     *
     * If the count reaches zero, then the method returns with the
     * value `true`.
     *
     * @param timeout timeout in milliseconds to wait for the count
     *                to reach zero; if the timeout is less than or equal to
     *                zero, the method will not wait at all
     * @returns `true` if the count reached zero, `false` if the waiting
     *          time elapsed before the count reached zero
     * @throws {@link IllegalStateError} if the Hazelcast instance was shut down
     *         while waiting
     */
    await(timeout: number): Promise<boolean>;

    /**
     * Decrements the count of the latch, releasing all waiting calls if
     * the count reaches zero.
     *
     * If the current count is greater than zero, then it is decremented.
     * If the new count is zero, then all waiting callers are notified
     * and can proceed, and the countdown owner is set to `null`.
     *
     * If the current count equals zero, then nothing happens.
     */
    countDown(): Promise<void>;

    /**
     * Returns the current count.
     *
     * @returns the current count
     */
    getCount(): Promise<number>;

    /**
     * Sets the count to the given value if the current count is zero.
     *
     * If count is not zero, then this method does nothing and returns
     * `false`.
     *
     * @param count the number of times `countDown()` must be invoked
     *              before callers can pass through `await()`
     * @returns `true` if the new count was set, `false` if the current
     *          count is not zero
     */
    trySetCount(count: number): Promise<boolean>;
}

redpajama_set_name: RedPajamaGithub


text:
require "scenarios/version"

module Scenarios
end


text: A collection of programming style guides.


text:
<!doctype html>

  <meta charset="utf-8">
  <title>AngularSeed</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="styles.3ff695c00d717f2d2a11.css">

  <app-root></app-root>


text:
//
//  CarMenu.m
//  Delivery
//
//  Created by Michael Blades on 1/11/15.
//  Copyright (c) 2015 Apportable. All rights reserved.
//

#import "CarMenu.h"
#import "Stats.h"
// TEMP
#import "ScrollViewTable.h"

static const CGFloat scrollSpeed = 150.f;

static CarMenu *inst = nil;

@interface CarMenu ()

@property CGPoint initialHero;
@property CGPoint initialFake;

@property CGPoint realInitialHero;

@property BOOL loadAnimationIsMoving;

@end

@implementation CarMenu {
    CCButton *_backCar;

    CCPhysicsNode *_physicsNode;
    CCNode *_ground1;
    CCNode *_ground2;

    CCLightNode *_redLight;
    CCLightNode *_blueLight;
    CCLightNode *_redLightFake;
    CCLightNode *_blueLightFake;

    CCSprite *_hero;
    CCSprite *_fakeHero;

    CCLabelTTF *_carTitle;
    CCLabelTTF *_coinCurrent;

    NSArray *_grounds;

    CCNode *_tutorial;
    CCNode *_tutorialBack;

    // TEMP
    CCButton *_addBtn;
    CCButton *_clear;
    // TEMP
}

- (id)init {
    if(self=[super init]) {
        self.titleCar = @"Delivery Truck";
    }
    return self;
}

+ (CarMenu*)instance {
    if (!inst) {
        inst = [[CarMenu alloc] init];
    }
    return inst;
}

#pragma mark - Load

- (void)didLoadFromCCB {
    _grounds = @[_ground1, _ground2];

    // Set coin total
    NSInteger currentCoin = [[Stats instance].currentCoin integerValue];

    // Format
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];

    NSNumber *numToFormat = [NSNumber numberWithInteger:currentCoin];
    NSString *formatted = [formatter stringFromNumber:numToFormat];

    _coinCurrent.string = [NSString stringWithFormat:@"%@", formatted];

    // Set title of menu
    _carTitle.string = [CarMenu instance].titleCar;

    // Construct Sprite Frame
    NSString *constructedFrame = [NSString stringWithFormat:@"Delivery/Heros/%@.png", [CarMenu instance].titleCar];

    // Fix Delivery
    if ([constructedFrame isEqualToString:@"Delivery/Heros/Delivery Truck.png"]) {
        constructedFrame = @"Delivery/Heros/Truck.png";
    }

    if ([constructedFrame isEqualToString:@"Delivery/Heros/Police Car.png"]) {
        _blueLight.visible = YES;
        _redLight.visible = YES;
    }

    _hero.spriteFrame = [CCSpriteFrame frameWithImageNamed:constructedFrame];

    // Redefine
    self.realInitialHero = _hero.position;
    self.initialHero = _hero.position;
    self.initialFake = _fakeHero.position;

    // Animations
    self.loadAnimationIsMoving = YES;
    CGPoint initial = _hero.position;
    _hero.position = ccp(-100, _hero.position.y);
    CCActionMoveTo *animate = [CCActionMoveTo actionWithDuration:1.5f position:initial];
    [_hero runAction:animate];
    [self performSelector:@selector(loadAnimationEnd) withObject:nil afterDelay:1.6f];

}

- (void)onEnter {

    [super onEnter];

//    NSLog(@"%@", [Stats instance].whereTutorial);

    if ([[Stats instance].whereTutorial isEqual:@"CarMenu"]) {

        // Add coins as default coins
        if ([Stats instance].currentCoin < [NSNumber numberWithInt:5000])
            [Stats instance].currentCoin = [NSNumber numberWithInteger:[[Stats instance].currentCoin integerValue] + 5000];

        _tutorial.visible = YES;
        _backCar.enabled = NO;

    }

}

#pragma mark - Tutorial

- (void)changeTutorial {

    // This hides the current gradients and displays the other tutorial.

    // Get scenes
    CCScene* runningScene = [CCDirector sharedDirector].runningScene;

    // Children of Menu - Index of 0 will always be Menu
    NSArray *array = [[runningScene.children objectAtIndex:0] children];

    for (CCNode *node in array) {
        if ([node.name isEqual:@"tutorial"]) {
            node.visible = NO;
        }

        if ([node.name isEqual:@"tutorialBack"]) {
            node.visible = YES;
        }
    }

    // Re-enable back button
    for (CCButton *button in array) {

        if ([button.name isEqual:@"backBtn"]) {
            button.enabled = YES;
        }

    }

    [Stats instance].whereTutorial = @"SuperPower";

}

#pragma mark - Update

- (void)update:(CCTime)delta {

    _carTitle.string = [CarMenu instance].titleCar;

    // User presses button before everything is done moving
    if ([CarMenu instance].didPressWhileMoving == YES) {
        [_hero stopAllActions];
        [_fakeHero stopAllActions];

        _hero.spriteFrame = _fakeHero.spriteFrame;

        _hero.position = self.initialHero;
        _fakeHero.position = self.initialFake;

        if ([[CarMenu instance].titleCar isEqualToString:@"Police Car"]) {
            if (![CCSpriteFrame frameWithImageNamed:@"Delivery/Heros/Police Car.png"]) {
                _blueLight.visible = NO;
                _redLight.visible = NO;
            }
            _blueLightFake.visible = YES;
            _blueLightFake.visible = YES;
        } else {
            _blueLight.visible = NO;
            _redLight.visible = NO;
            _blueLightFake.visible = NO;
            _redLightFake.visible = NO;
        }

        // Replace method fires, prevent that
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(replaceCars) object:nil];

//        self.doReplace = NO;

        [CarMenu instance].isMoving = YES;
        [self performSelector:@selector(moveCars) withObject:nil];

        [CarMenu instance].didPressWhileMoving = NO;
    }

    if (![CarMenu instance].shouldMove) {
        _hero.position = ccp(_hero.position.x, _hero.position.y);
    } else {
        if ([CarMenu instance].isMoving == NO) {
//            [_hero stopAllActions];
            [CarMenu instance].isMoving = YES;
            [self performSelector:@selector(moveCars) withObject:nil];
        }
    }

    for (CCNode *ground in _grounds){
        ground.position = ccp((ground.position.x + (-scrollSpeed * delta)), ground.position.y);
        if (ground.position.x <= (-ground.boundingBox.size.width)){
            ground.position = ccp(ground.scene.boundingBox.size.width, ground.position.y);
        }
    }
}

/*///////////////////////////////////////////
 *
 * Animations
 *
 ///////////////////////////////////////////*/

#pragma mark - Animations

- (void)moveCars {

//    self.initialHero = self.realInitialHero;
//    self.initialFake = _fakeHero.position;

    // Update displaying coin count
    NSString *coin = [self formatter:[[Stats instance].currentCoin integerValue]];
    _coinCurrent.string = coin;

    // Construct Sprite Frame
    NSString *constructedFrame = [NSString stringWithFormat:@"Delivery/Heros/%@.png", [CarMenu instance].titleCar];

    // Fix Delivery
    if ([constructedFrame isEqualToString:@"Delivery/Heros/Delivery Truck.png"]) {
        constructedFrame = @"Delivery/Heros/Truck.png";
    }

    if ([constructedFrame isEqualToString:@"Delivery/Heros/Police Car.png"]) {
        if (![CCSpriteFrame frameWithImageNamed:@"Delivery/Heros/Police Car.png"]) {
            _blueLight.visible = NO;
            _redLight.visible = NO;
        }

        _blueLightFake.visible = YES;
        _redLightFake.visible = YES;
    } else if (_hero.spriteFrame == [CCSpriteFrame frameWithImageNamed:@"Delivery/Heros/Police Car.png"]) {
        _blueLight.visible = YES;
        _redLight.visible = YES;
        _blueLightFake.visible = NO;
        _redLightFake.visible = NO;
    } else {
        _blueLight.visible = NO;
        _redLight.visible = NO;
        _blueLightFake.visible = NO;
        _redLightFake.visible = NO;
    }

    _fakeHero.spriteFrame = [CCSpriteFrame frameWithImageNamed:constructedFrame];

    CCActionMoveTo *moveHero = [CCActionMoveTo actionWithDuration:1.5f position:ccp(_hero.position.x + 400, _hero.position.y)];

    CCActionMoveTo *moveFake = [CCActionMoveTo actionWithDuration:1.5f position:self.initialHero];

    [self performSelector:@selector(replaceCars) withObject:nil afterDelay:1.6f];

    [_hero runAction:moveHero];
    [_fakeHero runAction:moveFake];

}

- (void)replaceCars {

    // Construct Sprite Frame
    NSString *constructedFrame = [NSString stringWithFormat:@"Delivery/Heros/%@.png", [CarMenu instance].titleCar];

    // Fix Delivery
    if ([constructedFrame isEqualToString:@"Delivery/Heros/Delivery Truck.png"]) {
        constructedFrame = @"Delivery/Heros/Truck.png";
    }

    _hero.spriteFrame = [CCSpriteFrame frameWithImageNamed:constructedFrame];

    // Move back
    _hero.position = self.initialHero;
    _fakeHero.position = self.initialFake;

    if ([constructedFrame isEqualToString:@"Delivery/Heros/Police Car.png"]) {
        _blueLight.visible = YES;
        _redLight.visible = YES;
        _blueLightFake.visible = NO;
        _redLightFake.visible = NO;
    } else {
        _blueLight.visible = NO;
        _redLight.visible = NO;
        _blueLightFake.visible = NO;
        _redLightFake.visible = NO;
    }

    [CarMenu instance].isMoving = NO;

}

- (void)loadAnimationEnd {
    self.loadAnimationIsMoving = NO;
}

/*///////////////////////////////////////////
 *
 * Buttons
 *
 ///////////////////////////////////////////*/

#pragma mark - Buttons

- (void)clear {
    [Stats instance].ownedCars = [[NSMutableArray alloc] init];
//    [[Stats instance].ownedCars addObject:@"DeliveryTruck"];
    NSLog(@"%@", [Stats instance].ownedCars);

    // REMOVE THIS + IMPORT AT TOP
    [ScrollViewTable instance].locks = [[NSMutableArray alloc] init];
}

- (void)addBtn {
    NSLog(@"%@", [Stats instance].ownedCars);
    [Stats instance].currentCoin = [NSNumber numberWithInteger:[[Stats instance].currentCoin integerValue] + 5000];
}

- (void)BackMenu {
    CCScene *gameplayScene = [CCBReader loadAsScene:@"Menu"];
    [[CCDirector sharedDirector] replaceScene:gameplayScene
                            withTransition:[CCTransition transitionCrossFadeWithDuration:.5]];
}

#pragma mark - Formatter

- (NSString *)formatter:(NSInteger)toFormat {

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];

    NSNumber *numToFormat = [NSNumber numberWithInteger:toFormat];
    NSString *formatted = [formatter stringFromNumber:numToFormat];

    return formatted;

}

@end


text:
#include <iostream>

#include "../linearIterator.h"

bool linearIterator_TEST(){
	//databaseFileRelation *fileRelation = new databaseFileRelation(string("../../../docs/datasets/dataset1-uniform/scale6/S.tbl"), string("S"));
	databaseFileRelation *fileRelation = new databaseFileRelation(string("../../../data/twoJoin_multiAttribute/S.tbl"), string("S"));
	fileRelation->GetRelationAttributeNames()->push_back(string("A"));
	fileRelation->GetRelationAttributeNames()->push_back(string("C"));
	fileRelation->GetRelationAttributeNames()->push_back(string("Y"));
	string error;
	if(fileRelation->Load(error) == OK) cout<<"Test passed."<<endl;
	else {
		cout<<error;
	}

	vector<int> indices;
	indices.push_back(0);
	indices.push_back(1);
	indices.push_back(2);
	linearIterator *iterator = new linearIterator(fileRelation, &indices);
	if(iterator->constructSearchTree(&indices) == OK) cout<<"search tree constructed!"<<endl;
	else {
		cout<<"Failed to construct search tree!"<<endl;
	}

	while(!iterator->atEnd()){
		printArray(iterator->key());cout<<",";
		iterator->next();
	}
	cout<<endl<<"Test completed!"<<endl;
	vector<int> temp;
	temp.push_back(0);
	temp.push_back(0);
	temp.push_back(0);
	for(int i=190; i<210;i++){
		temp[0] = i;
		iterator->seek(temp);
		printArray(iterator->key());;
	}
	cout<<endl<<"Test completed!"<<endl;
	while(!iterator->atEnd()){
		printArray(iterator->key());
		iterator->next();
	}
	cout<<endl<<"Test completed!"<<endl;
	if(iterator->constructSearchTree(&indices) == OK) cout<<"search tree constructed!"<<endl;
	else {
		cout<<"Failed to construct search tree!"<<endl;
	}
	while(!iterator->atEnd()){
		printArray(iterator->key());
		iterator->next();
	}
	cout<<endl<<"Test completed!"<<endl;

	delete fileRelation;
}

int main (int, char const **) {
	linearIterator_TEST();
	return 0;
}


text:
<?xml version="1.0"?>

<document>

    <properties>
        <title>Deprecated Excalibur Products</title>
    </properties>

                Over time several Excalibur products have reached the
                end of their lifecycle. This page documents the deprecated
                components.

            <subsection name="Excalibur-Compatibility">

                    Compatibility was a library consisting of several utility classes that
                    Excalibur had ceased developing with the aim of focusing on the charter.

                        Replacements

                        Package
                        Replacement

                        o.a.a.excalibur.cli
                        Commons-CLI

                        o.a.a.excalibur.collections
                        Commons-Collections

                        o.a.a.excalibur.concurrent
                        Doug Leas Concurrent Library

                        o.a.a.excalibur.io
                        Spice-Salt

                        o.a.a.excalibur.naming
                        Spice-JNDIKit

            </subsection>

            <subsection name="Excalibur-Component">

                    ECM (Excalibur Component Manager) was our first container. It's still in use in
                    quite a few projects, but has not been under active development for about two
                    years, as we've written a much better container that is (almost) completely
                    backwards compatible.

Replacement: Excalibur-Fortress

                    Some old documentation about ECM is still available
                    here.

            </subsection>

            <subsection name="Excalibur-Configuration">

                    Excalibur-Configuration was a utility library to manipulate configuration trees.
                    Configuration had never been released and the original developers have
                    redeveloped the code elsewhere. The following table lists the replacement
                    packages for Excalibur-Configuration.

Replacement: Spice-Configkit

                    Some old documentation about Excalibur-Configuration is still available
                    here.

            </subsection>

            <subsection name="Excalibur-Event">

                    Excalibur-Event was an extensive component library to aid in concurrent
                    programming. This package has gradually evolved into a much better package
                    maintained elsewhere. The following table lists the replacement
                    packages for Excalibur-Event.

                        Replacements

                        Package
                        Replacement

                        o.a.excalibur.event
                        D-Haven-Event

                        o.a.excalibur.mpool
                        D-Haven-Managed-Pool

                    Some old documentation about Excalibur-Event is still available
                    here.

            </subsection>

            <subsection name="Excalibur-i18n">

                    Excalibur-i18n was a very small utility library to aid in the use of localized
                    resources. This library stored these resources in an inconvenient location. A
                    much better package has been developed elsewhere.

Replacement: Spice-Salt

            </subsection>

            <subsection name="Excalibur-Testcase">

                    Excalibur-Testcase was a library to aid unit testing of components. It provided
                    an extended TestCase class that would set up an ECM instance for you. Since we
                    now all know this is a bad idea (no component should be tested against an actual
                    container implementation, only in isolation), it has been deprecated along with
                    ECM, with no direct replacement.

Replacement: none

            </subsection>

</document>


text:
import BasePlugin from './../_base';
import ZeroClipboard from 'zeroclipboard';
import {removeClass} from './../../helpers/dom/element';
import {arrayEach} from './../../helpers/array';
import {EventManager} from './../../eventManager';
import {registerPlugin} from './../../plugins';
import {SEPARATOR} from './../contextMenu/predefinedItems';

/**
 * @description
 * This plugin adds a copy/paste functionality to the context menu. Due to browser restrictions, it uses ZeroClipboard to allow
 * copying data with a click.
 *
 * @plugin ContextMenuCopyPaste
 * @dependencies ContextMenu zeroclipboard
 */
class ContextMenuCopyPaste extends BasePlugin {
  /**
   * @param {Object} hotInstance
   */
  constructor(hotInstance) {
    super(hotInstance);
    /**
     * Instance of {@link EventManager}.
     *
     * @type {EventManager}
     */
    this.eventManager = new EventManager(this);
    /**
     * Path to swf file which is necessary for ZeroClipboard.
     *
     * @type {String}
     */
    this.swfPath = null;
    /**
     * outsideClickDeselectsCache setting cache.
     *
     * @type {Boolean}
     */
    this.outsideClickDeselectsCache = null;
  }

  /**
   * Check if the plugin is enabled in the handsontable settings.
   *
   * @returns {Boolean}
   */
  isEnabled() {
    return this.hot.getSettings().contextMenuCopyPaste;
  }

  /**
   * Enable plugin for this Handsontable instance.
   */
  enablePlugin() {
    if (this.enabled) {
      return;
    }
    if (typeof this.hot.getSettings().contextMenuCopyPaste === 'object') {
      this.swfPath = this.hot.getSettings().contextMenuCopyPaste.swfPath;
    }
    if (typeof ZeroClipboard === 'undefined') {
      console.error('To be able to use the Copy/Paste feature from the context menu, you need to manually include ZeroClipboard.js file to your website.');
    }
    try {
      /* jshint -W031 */
      new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
    } catch (exception) {
      if (typeof navigator.mimeTypes['application/x-shockwave-flash'] == 'undefined') {
        console.error('To be able to use the Copy/Paste feature from the context menu, your browser needs to have Flash Plugin installed.');
      }
    }
    if (this.swfPath) {
      ZeroClipboard.config({
        swfPath: this.swfPath
      });
    }
    this.hot.addHook('afterContextMenuShow', () => this.onAfterContextMenuShow());
    this.hot.addHook('afterContextMenuDefaultOptions', (options) => this.onAfterContextMenuDefaultOptions(options));
    this.registerEvents();
    super.enablePlugin();
  }

  /**
   * Disable plugin for this Handsontable instance.
   */
  disablePlugin() {
    super.disablePlugin();
  }

  /**
   * @private
   */
  registerEvents() {
    this.eventManager.addEventListener(document, 'mouseenter', () => this.removeCurrentClass());
    this.eventManager.addEventListener(document, 'mouseleave', () => this.removeZeroClipboardClass());
  }

  /**
   * Get a value to copy.
   *
   * @returns {String}
   */
  getCopyValue() {
    this.hot.copyPaste.setCopyableText();
    this.hot.copyPaste.copyPasteInstance.triggerCopy();
    return this.hot.copyPaste.copyPasteInstance.elTextarea.value;
  }

  /**
   * Add Copy and Paste functionality to the context menu.
   *
   * @private
   * @param {Object} defaultOptions
   */
  onAfterContextMenuDefaultOptions(defaultOptions) {
    defaultOptions.items.unshift({
        key: 'copy',
        name: 'Copy',
        disabled: function() {
          return this.selection.selectedHeader.corner;
        },
      }, {
        key: 'paste',
        name: 'Paste',
        callback: function() {
          this.copyPaste.triggerPaste();
        },
        disabled: function() {
          return this.selection.selectedHeader.corner;
        },
      },
      {name: SEPARATOR}
    );
  }

  /**
   * After context menu show listener.
   *
   * @private
   */
  onAfterContextMenuShow() {
    const contextMenu = this.hot.getPlugin('contextMenu');
    const data = contextMenu.menu.hotMenu.getSourceData();

    // find position of 'copy' option.
    arrayEach(data, (item, index) => {
      if (item.key === 'copy') {
        let zeroClipboardInstance = new ZeroClipboard(contextMenu.menu.hotMenu.getCell(index, 0));

        zeroClipboardInstance.off();
        zeroClipboardInstance.on('copy', (event) => {
          let clipboard = event.clipboardData;

          clipboard.setData('text/plain', this.getCopyValue());
          this.hot.getSettings().outsideClickDeselects = this.outsideClickDeselectsCache;
        });

        return false;
      }
    });
  }

  /**
   * @private
   */
  removeCurrentClass() {
    const contextMenu = this.hot.getPlugin('contextMenu');

    if (!contextMenu.enabled) {
      return;
    }
    if (contextMenu.menu.isOpened()) {
      let element = contextMenu.menu.hotMenu.rootElement.querySelector('td.current');

      if (element) {
        removeClass(element, 'current');
      }
    }
    this.outsideClickDeselectsCache = this.hot.getSettings().outsideClickDeselects;
    this.hot.getSettings().outsideClickDeselects = false;
  }

  /**
   * @private
   */
  removeZeroClipboardClass() {
    const contextMenu = this.hot.getPlugin('contextMenu');

    if (!contextMenu.enabled) {
      return;
    }
    if (contextMenu.menu.isOpened()) {
      let element = contextMenu.menu.hotMenu.rootElement.querySelector('td.zeroclipboard-is-hover');

      if (element) {
        removeClass(element, 'zeroclipboard-is-hover');
      }
    }
    this.hot.getSettings().outsideClickDeselects = this.outsideClickDeselectsCache;
  }
}

export {ContextMenuCopyPaste};

registerPlugin('contextMenuCopyPaste', ContextMenuCopyPaste);


text:
package pineapple.bd.com.pineapple.media.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import pineapple.bd.com.pineapple.PineApplication;
import pineapple.bd.com.pineapple.R;
import pineapple.bd.com.pineapple.db.Music;
import pineapple.bd.com.pineapple.media.adapter.AudioSelectionListAdapter;
import pineapple.bd.com.pineapple.media.entity.AudioItems;
import pineapple.bd.com.pineapple.utils.BaseCoverActivity;

/**
 * A simple activity that allows the user to select a
 * chapter form "The Count of Monte Cristo" to play
 * (limited to chapters 1 - 4).
 */
public class AudioSelectionActivity extends BaseCoverActivity implements AdapterView.OnItemClickListener {

    private AudioSelectionListAdapter audioSelectionListAdapter;
    private ListView mAudioListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_selection_activity);

        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(R.string.music_repo);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
        }
        mAudioListView =  (ListView) findViewById(R.id.selection_activity_list);
        audioSelectionListAdapter = new AudioSelectionListAdapter(this);
        mAudioListView.setAdapter(audioSelectionListAdapter);
        mAudioListView.setOnItemClickListener(this);
        setupData();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        mAudioListView = null;
        audioSelectionListAdapter = null;
        super.onDestroy();
    }

    private void setupData() {
        BmobQuery<Music> bq = new BmobQuery<Music>();
        bq.findObjects(this, new FindListener<Music>(){
            @Override
            public void onSuccess(List<Music> list) {
                AudioItems.clear();
                for (Music music: list) {
                    AudioItems.addAudioItem(new AudioItems.AudioItem(music.getName(),music.getUrl(),music.getPoster_url(),music.getAlbums(),music.getSinger()));
                }
                audioSelectionListAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(int i, String s) {

            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        startAudioPlayerActivity(position);
    }

    private void startAudioPlayerActivity(int selectedIndex) {
        Intent intent = new Intent(this, AudioPlayerActivity.class);
        intent.putExtra(AudioPlayerActivity.EXTRA_INDEX, selectedIndex);
        startActivity(intent);
    }
}


text:
ACCEPTED

#### According to
World Register of Marine Species

#### Published in
Acta Protozool 36 (1), February: 64.

#### Original name
null

### Remarks
null


text:
module Crimagify
  class ApplicationController < ::ApplicationController
  end
end


text:
#pragma once
//------------------------------------------------------------------------------
/**
    @class Jobs::JobPort

    A job port of the N3 job system (see JobPortBase for details).

    (C) 2009 Radon Labs GmbH
*/
#include "core/config.h"
#if __PS3__
#include "jobs/ps3/ps3jobport.h"
namespace Jobs
{
class JobPort : public PS3::PS3JobPort
{
    __DeclareClass(JobPort);
};
} // namespace Jobs
#elif (NEBULA3_USE_SERIAL_JOBSYSTEM || __WII__)
#include "jobs/serial/serialjobport.h"
namespace Jobs
{
class JobPort : public SerialJobPort
{
    __DeclareClass(JobPort);
};
} // namespace Jobs
#elif (__WIN32__ || __XBOX360__ || __ANDROID__ || __OSX__)
#include "jobs/tp/tpjobport.h"
namespace Jobs
{
class JobPort : public TPJobPort
{
    __DeclareClass(JobPort);
};
} // namespace Jobs
#else
#error "Jobs::JobPort not implemented on this platform!"
#endif


text:
/*global describe, it, expect, beforeEach, afterEach, waitsFor, runs, waitsForDone, waitsForFail */

define(function (require, exports, module) {
    "use strict";

    var SpecRunnerUtils = brackets.getModule("spec/SpecRunnerUtils");

    var main                = require("main"),
        InlineDocsViewer    = require("InlineDocsViewer"),
        testCSS             = require("text!unittest-files/test1.css"),
        testHTML            = require("text!unittest-files/test1.html");

    describe("WebPlatformDocs", function () {

        var testCSSInfo     = SpecRunnerUtils.parseOffsetsFromText(testCSS),
            testHTMLInfo    = SpecRunnerUtils.parseOffsetsFromText(testHTML),
            editor,
            doc,
            pos;

        function queryInlineAtPos(info, offset, expectInline, expectedProperty) {
            var widget = null,
                promise;

            runs(function () {
                // set cursor position in editor
                pos = info.offsets[offset];
                editor.setSelection(pos);

                // fetch inline editor
                promise = main._inlineProvider(editor, pos);

                if (expectInline) {
                    expect(promise).toBeTruthy();
                }

                if (promise) {
                    promise.done(function (result) {
                        widget = result;
                    });

                    if (expectInline) {
                        // expecting a valid CSS property
                        waitsForDone(promise, "WebPlatformDocs _inlineProvider", 1000);
                    } else {
                        // expecting an invalid css property
                        waitsForFail(promise, "WebPlatformDocs _inlineProvider", 1000);
                    }
                }
            });

            runs(function () {
                if (promise) {
                    if (expectInline) {
                        expect(widget).toBeTruthy();
                        expect(widget.$htmlContent.find(".css-prop-summary h1").text()).toBe(expectedProperty);
                    } else {
                        expect(widget).toBeNull();
                    }
                }
            });
        }

        describe("InlineDocsProvider database", function () {

            it("should retrieve the CSS docs database", function () {
                var json;

                runs(function () {
                    main._getCSSDocs().done(function (result) {
                        json = result;
                    });
                });

                waitsFor(function () { return json !== undefined; }, "read css.json database", 5000);

                runs(function () {
                    expect(Object.keys(json.PROPERTIES).length).toBeGreaterThan(0);
                });
            });

        });

        describe("InlineDocsProvider parsing in CSS", function () {

            beforeEach(function () {
                var mock = SpecRunnerUtils.createMockEditor(testCSSInfo.text, "css");
                editor = mock.editor;
                doc = mock.doc;
            });

            afterEach(function () {
                SpecRunnerUtils.destroyMockEditor(doc);
            });

            it("should open docs when the selection is on a CSS property", function () {
                /* css property */
                queryInlineAtPos(testCSSInfo, 1, true, "border");

                /* css value */
                queryInlineAtPos(testCSSInfo, 2, true, "border");
            });

            it("should not open docs when the selection is not on a CSS property", function () {
                /* css selector */
                queryInlineAtPos(testCSSInfo, 0, false);

                /* css comment */
                queryInlineAtPos(testCSSInfo, 5, false);
            });

            it("should not open docs for an invalid CSS property", function () {
                /* css invalid property */
                queryInlineAtPos(testCSSInfo, 3, false);
            });

            it("should open docs for a vendor-prefixed CSS property", function () {
                /* css -webkit- prefixed property */
                queryInlineAtPos(testCSSInfo, 6, true, "animation");
            });

            it("should not open docs for an invalid CSS property (looking like a vendor-prefixed one)", function () {
                /* css property invalidly prefixed */
                queryInlineAtPos(testCSSInfo, 7, false);
            });

        });

        describe("InlineDocsProvider parsing in HTML", function () {

            beforeEach(function () {
                var mock = SpecRunnerUtils.createMockEditor(testHTMLInfo.text, "html");
                editor = mock.editor;
                doc = mock.doc;
            });

            afterEach(function () {
                SpecRunnerUtils.destroyMockEditor(doc);
            });

            it("should open docs for CSS in a


text:
NamespaceMux::NamespaceMux()
{
	parseParams();
	setupMuxers();
	setupController();
}

NamespaceMux::~NamespaceMux()
{
	rosNode->shutdown();
	delete rosNode;
}

void NamespaceMux::setupController()
{
	// Setup mux controller:
	control_sub = rosNode->subscribe<std_msgs::String>(MUX_CONTROL_TOPIC, 2, &NamespaceMux::mux_control_callback, this);

}

void NamespaceMux::parseParams()
{
	rosNode = new ros::NodeHandle("");

	rosNode->getParam("/namespace_mux/incoming_ns_prefix", incoming_ns_prefix);
	ROS_INFO("PARAM: incoming_ns_prefix - %s\n", incoming_ns_prefix.c_str());

	rosNode->getParam("/namespace_mux/outgoing_ns", outgoing_ns);
	ROS_INFO("PARAM: outgoing_ns - %s\n", outgoing_ns.c_str());

	rosNode->getParam("/namespace_mux/active_bots", active_bots);
	rosNode->getParam("/namespace_mux/subscribed_topics", subscribed_topics);
	rosNode->getParam("/namespace_mux/published_topics", published_topics);

	if (active_bots.empty()) {
		ROS_ERROR("No bots are active. Dynamic Topic relay disabled\n");
		std::exit(EXIT_FAILURE);
	}

	// Default namespace: first bot
	else {
		currRobotNs = active_bots.begin()->c_str();
		ROS_INFO("Current Robot Namespace: %s\n", currRobotNs.c_str());
	}
}

void NamespaceMux::setupMuxers()
{
	setupSubscribers();
	setupPublishers();
}

void NamespaceMux::setupSubscribers()
{
	for (std::vector<std::string>::iterator it = subscribed_topics.begin(); it != subscribed_topics.end(); ++it) {
		std::string mainTopic = (*it).c_str();
		std::string inputTopic = "/" + currRobotNs + mainTopic;
		std::string outputTopic = "/" + outgoing_ns + mainTopic;

		DynamicTopicRelay* relayedSubTopic = new DynamicTopicRelay(rosNode, mainTopic, inputTopic, outputTopic);
		ros::Subscriber inputSubscription = rosNode->subscribe<topic_tools::ShapeShifter>(relayedSubTopic->getInputTopic(), 10, &DynamicTopicRelay::in_cb, relayedSubTopic);

		inputSubscriptions.push_back(inputSubscription);
		relayedSubs.push_back(relayedSubTopic);
	}
}

void NamespaceMux::setupPublishers()
{
	for (std::vector<std::string>::iterator it = published_topics.begin(); it != published_topics.end(); ++it) {
		std::string mainTopic = (*it).c_str();
		std::string inputTopic = "/" + outgoing_ns + mainTopic;
		std::string outputTopic = "/" + currRobotNs + mainTopic;

		DynamicTopicRelay* relayedPubTopic = new DynamicTopicRelay(rosNode, mainTopic, inputTopic, outputTopic);

		ros::Subscriber inputPublication = rosNode->subscribe<topic_tools::ShapeShifter>(relayedPubTopic->getInputTopic(), 10, &DynamicTopicRelay::in_cb, relayedPubTopic);

		inputPublications.push_back(inputPublication);
		relayedPubs.push_back(relayedPubTopic);
	}
}

void NamespaceMux::mux_control_callback(const std_msgs::String::ConstPtr& cmd)
{
	std::string newBotNs = cmd->data;

	// Ensure that robot namespace exists:
	if (std::find(active_bots.begin(), active_bots.end(), newBotNs) != active_bots.end()) {
		currRobotNs = newBotNs;
		switchMuxes();
		ROS_INFO("Current namespace: %s\n", currRobotNs.c_str());
	} else {
		ROS_ERROR("The namespace '%s' does exist. Check that it was properly initialized in your launch file\n", newBotNs.c_str());
	}
}

void NamespaceMux::manageTopics()
{
	ros::spin();
}

void NamespaceMux::switchMuxes()
{
	switchSubscribers();
	switchPublishers();
}

void NamespaceMux::switchPublishers()
{
	for (std::vector<ros::Subscriber>::iterator it = inputPublications.begin(); it != inputPublications.end(); ++it) {
		(*it).shutdown();
	}

	inputPublications.clear();
	setupPublishers();
}

void NamespaceMux::switchSubscribers()
{
	for (std::vector<ros::Subscriber>::iterator it = inputSubscriptions.begin(); it != inputSubscriptions.end(); ++it) {
		(*it).shutdown();
	}

	inputSubscriptions.clear();
	setupSubscribers();
}

int main(int argc, char **argv)
{
	ros::init(argc, argv, "outgoing_ns_mux");

	NamespaceMux nsMux;
	nsMux.manageTopics();

	return 0;
}


text:
var Q = require("q");

var TestListener = function () {
  this.testMessages = [];
};

TestListener.prototype = {

  initialize: function () {
    var self = this
    var deferred = Q.defer();
    setTimeout(function () {
      self.didInitialize = true;
      deferred.resolve();
    }, 1);
    return deferred.promise;
  },

  listenTo: function (testRun, test, source) {
    var self = this;
    source.addListener("message", function (message) {
      self.testMessages.push(message);
    });
  },

  flush: function () {
    var self = this;
    var deferred = Q.defer();
    setTimeout(function () {
      self.didFlush = true;
      deferred.resolve();
    }, 1);
    return deferred.promise;
  }

};

module.exports = TestListener;


text:
import {isPresent, Type} from 'angular2/src/facade/lang';
import {Predicate} from 'angular2/src/facade/collection';
import {Injector} from 'angular2/src/core/di';
import {ListWrapper, MapWrapper} from 'angular2/src/facade/collection';
import {RenderDebugInfo} from 'angular2/src/core/render/api';

export class EventListener { constructor(public name: string, public callback: Function){}; }

export class DebugNode {
  nativeNode: any;
  listeners: EventListener[];
  parent: DebugElement;

  constructor(nativeNode: any, parent: DebugNode, private _debugInfo: RenderDebugInfo) {
    this.nativeNode = nativeNode;
    if (isPresent(parent) && parent instanceof DebugElement) {
      parent.addChild(this);
    } else {
      this.parent = null;
    }
    this.listeners = [];
  }

  get injector(): Injector { return isPresent(this._debugInfo) ? this._debugInfo.injector : null; }

  get componentInstance(): any {
    return isPresent(this._debugInfo) ? this._debugInfo.component : null;
  }

  get locals(): {[key: string]: any} {
    return isPresent(this._debugInfo) ? this._debugInfo.locals : null;
  }

  get providerTokens(): any[] {
    return isPresent(this._debugInfo) ? this._debugInfo.providerTokens : null;
  }

  get source(): string { return isPresent(this._debugInfo) ? this._debugInfo.source : null; }

  inject(token: any): any { return this.injector.get(token); }

  getLocal(name: string): any { return this.locals[name]; }
}

export class DebugElement extends DebugNode {
  name: string;
  properties: {[key: string]: string};
  attributes: {[key: string]: string};
  childNodes: DebugNode[];
  nativeElement: any;

  constructor(nativeNode: any, parent: any, _debugInfo: RenderDebugInfo) {
    super(nativeNode, parent, _debugInfo);
    this.properties = {};
    this.attributes = {};
    this.childNodes = [];
    this.nativeElement = nativeNode;
  }

  addChild(child: DebugNode) {
    if (isPresent(child)) {
      this.childNodes.push(child);
      child.parent = this;
    }
  }

  removeChild(child: DebugNode) {
    var childIndex = this.childNodes.indexOf(child);
    if (childIndex !== -1) {
      child.parent = null;
      this.childNodes.splice(childIndex, 1);
    }
  }

  insertChildrenAfter(child: DebugNode, newChildren: DebugNode[]) {
    var siblingIndex = this.childNodes.indexOf(child);
    if (siblingIndex !== -1) {
      var previousChildren = this.childNodes.slice(0, siblingIndex + 1);
      var nextChildren = this.childNodes.slice(siblingIndex + 1);
      this.childNodes =
          ListWrapper.concat(ListWrapper.concat(previousChildren, newChildren), nextChildren);
      for (var i = 0; i < newChildren.length; ++i) {
        var newChild = newChildren[i];
        if (isPresent(newChild.parent)) {
          newChild.parent.removeChild(newChild);
        }
        newChild.parent = this;
      }
    }
  }

  query(predicate: Predicate<DebugElement>): DebugElement {
    var results = this.queryAll(predicate);
    return results.length > 0 ? results[0] : null;
  }

  queryAll(predicate: Predicate<DebugElement>): DebugElement[] {
    var matches: DebugElement[] = [];
    _queryElementChildren(this, predicate, matches);
    return matches;
  }

  queryAllNodes(predicate: Predicate<DebugNode>): DebugNode[] {
    var matches: DebugNode[] = [];
    _queryNodeChildren(this, predicate, matches);
    return matches;
  }

  get children(): DebugElement[] {
    var children: DebugElement[] = [];
    this.childNodes.forEach((node) => {
      if (node instanceof DebugElement) {
        children.push(node);
      }
    });
    return children;
  }

  triggerEventHandler(eventName: string, eventObj: any) {
    this.listeners.forEach((listener) => {
      if (listener.name == eventName) {
        listener.callback(eventObj);
      }
    });
  }
}

export function asNativeElements(debugEls: DebugElement[]): any {
  return debugEls.map((el) => el.nativeElement);
}

function _queryElementChildren(element: DebugElement, predicate: Predicate<DebugElement>,
                               matches: DebugElement[]) {
  element.childNodes.forEach(node => {
    if (node instanceof DebugElement) {
      if (predicate(node)) {
        matches.push(node);
      }
      _queryElementChildren(node, predicate, matches);
    }
  });
}

function _queryNodeChildren(parentNode: DebugNode, predicate: Predicate<DebugNode>,
                            matches: DebugNode[]) {
  if (parentNode instanceof DebugElement) {
    parentNode.childNodes.forEach(node => {
      if (predicate(node)) {
        matches.push(node);
      }
      if (node instanceof DebugElement) {
        _queryNodeChildren(node, predicate, matches);
      }
    });
  }
}

// Need to keep the nodes in a global Map so that multiple angular apps are supported.
var _nativeNodeToDebugNode = new Map<any, DebugNode>();

export function getDebugNode(nativeNode: any): DebugNode {
  return _nativeNodeToDebugNode.get(nativeNode);
}

export function getAllDebugNodes(): DebugNode[] {
  return MapWrapper.values(_nativeNodeToDebugNode);
}

export function indexDebugNode(node: DebugNode) {
  _nativeNodeToDebugNode.set(node.nativeNode, node);
}

export function removeDebugNodeFromIndex(node: DebugNode) {
  _nativeNodeToDebugNode.delete(node.nativeNode);
}


text:
package org.jboss.aerogear.todo.fragments;

import java.util.ArrayList;
import java.util.List;

import org.jboss.aerogear.android.pipeline.LoaderPipe;
import org.jboss.aerogear.todo.R;
import org.jboss.aerogear.todo.ToDoApplication;
import org.jboss.aerogear.todo.activities.TodoActivity;
import org.jboss.aerogear.todo.callback.DeleteCallback;
import org.jboss.aerogear.todo.callback.ListFragmentCallbackHelper;
import org.jboss.aerogear.todo.callback.ReadCallback;
import org.jboss.aerogear.todo.data.Tag;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;

public class TagListFragment extends SherlockFragment implements ListFragmentCallbackHelper<Tag> {
	private ArrayAdapter<Tag> adapter;
	private List<Tag> tags = new ArrayList<Tag>();
	private LoaderPipe<Tag> pipe;

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

		View view = inflater.inflate(R.layout.list, null);

		TextView title = (TextView) view.findViewById(R.id.title);
		title.setText(getResources().getString(R.string.tags));

		ImageView add = (ImageView) view.findViewById(R.id.add);
		add.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				((TodoActivity) getActivity()).showTagForm();
			}
		});

		adapter = new ArrayAdapter<Tag>(getActivity(),
				android.R.layout.simple_list_item_1, tags);
		ListView tagListView = (ListView) view.findViewById(R.id.list);
		tagListView.setAdapter(adapter);

		tagListView
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					public void onItemClick(AdapterView<?> adapterView,
							View view, int position, long id) {
						final Tag tag = tags.get(position);
						((TodoActivity) getActivity()).showTagForm(tag);
					}
				});

		tagListView
				.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
					@Override
					public boolean onItemLongClick(AdapterView<?> adapterView,
							View view, int position, long id) {
						final Tag tag = tags.get(position);
						new AlertDialog.Builder(getActivity())
								.setMessage("Delete '" + tag.getTitle() + "'?")
								.setPositiveButton("Yes",
										new DialogInterface.OnClickListener() {
											@Override
											public void onClick(
													DialogInterface dialogInterface,
													int i) {
												startDelete(tag);
											}
										}).setNegativeButton("Cancel", null)
								.show();
						return true;
					}
				});

		return view;

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		pipe = ((ToDoApplication) getActivity().getApplication()).getPipeline()
				.get("tags", this, getActivity().getApplicationContext());
	}

	@Override
	public void onStart() {
		super.onStart();
		startRefresh();
	}

	@Override
	public void startRefresh() {
		pipe.reset();
		pipe.read(new ReadCallback<Tag>());
	}

	private void startDelete(Tag tag) {
		pipe.remove(tag.getId(), new DeleteCallback());
	}

	@Override
	public List<Tag> getList() {
		return tags;
	}

	@Override
	public ArrayAdapter<Tag> getAdapter() {
		return adapter;
	}

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.buzzrobotics.subsystems</title>
<meta name="date" content="2012-02-11">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

org.buzzrobotics.subsystems

Classes

BallFeeder

BridgeArm

Camera

DriveTrain

FloorLight

irSensor

Light

RollerArm

Shifter

Shooter

ShooterAngle


text:
id: 5900f3ab1000cf542c50febe
title: 'Problema 63: Contagem poderosa de algarismos'
challengeType: 5
forumTopicId: 302175
dashedName: problem-63-powerful-digit-counts
---

# --description--

O número de 5 algarismos, 16807 = 75, também é uma quinta potência. Da mesma forma, o número de 9 algarismos, 134217728 = 89, é uma nona potência.

Complete a função para que ela retorne quantos números inteiros e positivos são da `n`-ésima potência e de comprimento `n`.

# --hints--

`powerfulDigitCounts(1)` deve retornar um número.

```js
assert(typeof powerfulDigitCounts(1) === 'number');
```

`powerfulDigitCounts(1)` deve retornar `9`.

```js
assert.strictEqual(powerfulDigitCounts(1), 9);
```

`powerfulDigitCounts(2)` deve retornar `6`.

```js
assert.strictEqual(powerfulDigitCounts(2), 6);
```

`powerfulDigitCounts(3)` deve retornar `5`.

```js
assert.strictEqual(powerfulDigitCounts(3), 5);
```

`powerfulDigitCounts(4)` deve retornar `4`.

```js
assert.strictEqual(powerfulDigitCounts(4), 4);
```

`powerfulDigitCounts(5)` deve retornar `3`.

```js
assert.strictEqual(powerfulDigitCounts(5), 3);
```

`powerfulDigitCounts(6)` deve retornar `3`.

```js
assert.strictEqual(powerfulDigitCounts(6), 3);
```

`powerfulDigitCounts(7)` deve retornar `2`.

```js
assert.strictEqual(powerfulDigitCounts(7), 2);
```

`powerfulDigitCounts(8)` deve retornar `2`.

```js
assert.strictEqual(powerfulDigitCounts(8), 2);
```

`powerfulDigitCounts(10)` deve retornar `2`.

```js
assert.strictEqual(powerfulDigitCounts(10), 2);
```

`powerfulDigitCounts(21)` deve retornar `1`.

```js
assert.strictEqual(powerfulDigitCounts(21), 1);
```

# --seed--

## --seed-contents--

```js
function powerfulDigitCounts(n) {

  return true;
}

powerfulDigitCounts(1);
```

# --solutions--

```js
function powerfulDigitCounts(n) {
  function countDigits(num) {
    let counter = 0;
    while (num > 0) {
      num = Math.floor(num / 10);
      counter++;
    }
    return counter;
  }

  let numbersCount = 0;

  let curNum = 1;
  while (curNum < 10) {
    let power = n;
    if (power === countDigits(curNum ** power)) {
      numbersCount++;
    }
    curNum++;
  }

  return numbersCount;
}
```


text:
package org.opencb.opencga.analysis.variant.operations;

import org.opencb.opencga.core.tools.annotations.Tool;
import org.opencb.opencga.core.models.operations.variant.VariantSecondaryIndexParams;
import org.opencb.opencga.core.models.common.Enums;

@Tool(id = VariantSecondaryIndexOperationTool.ID, description = VariantSecondaryIndexOperationTool.DESCRIPTION,
        type = Tool.Type.OPERATION,
        scope = Tool.Scope.PROJECT,
        resource = Enums.Resource.VARIANT)
public class VariantSecondaryIndexOperationTool extends OperationTool {

    public static final String ID = "variant-secondary-index";
    public static final String DESCRIPTION = "Creates a secondary index using a search engine. "
            + "If samples are provided, sample data will be added to the secondary index.";
    private VariantSecondaryIndexParams indexParams;
    private String projectFqn;

    @Override
    protected void check() throws Exception {
        super.check();
        indexParams = VariantSecondaryIndexParams.fromParams(VariantSecondaryIndexParams.class, params);
        projectFqn = getProjectFqn();
    }

    @Override
    protected void run() throws Exception {
        step(() -> variantStorageManager.secondaryIndex(projectFqn, indexParams.getRegion(), indexParams.isOverwrite(), params, token));
    }
}


text:
const { resolve } = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')

const rootDir = __dirname
const srcDir = resolve(rootDir, 'src')
const distDir = resolve(rootDir, 'dist')
const mockDir = resolve(srcDir, 'assets', 'mocks')
// const nodeModulesDir = resolve(rootDir, 'node_modules')
const appName = 'index.js'
const port = 2017

const basicConfig = {
  // webpack创建依赖图的入口
  entry: [
    'react-hot-loader/patch',
    // `webpack-dev-server/client?http://localhost:${port}`,
    // 'webpack/hot/only-dev-server',
    resolve(srcDir, appName),
  ],
  // webpack生成打包后文件的处理配置
  output: {
    path: distDir,
    publicPath: '/',
    filename: '[name].js',
  },
  module: {
    rules: [
      { test: /.jsx?$/, use: ['babel-loader'], exclude: /node_modules/ },
      {
        test: /.css$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              modules: true,
              localIdentName: '[path][name]__[local]--[hash:base64:5]',
            },
          },
        ],
      },
    ],
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
    new HtmlWebpackPlugin({
      template: resolve(srcDir, 'assets/index.tpl'),
      // svg format image as favicon is not supported yet (except for FF 👍)
      favicon:resolve(srcDir, 'assets', 'favicon.svg'),
    }),
  ],
  resolve: {
    extensions: ['.js', '.jsx'],
    modules: [srcDir, 'node_modules'],
  },
  devtool: 'cheap-module-eval-source-map',
  // will be picked up by webpack-dev-server
  devServer: {
    // hot: true, // refresh when error happens
    hotOnly: true, // don't refresh when error happens
    contentBase: mockDir, // serve static files from here
    historyApiFallback: true, // 404 falls back to index.html
    port,
    host: '0.0.0.0', // make it externally accessible
    overlay: true, // I like it's color!
  },
}

module.exports = basicConfig


text:
#ifndef HUES_RESPACK_H_
#define HUES_RESPACK_H_

#include <cmath>
#include <locale>
#include <string>
#include <vector>

#include <png.h>

#include <common.hpp>

using namespace std;

class ImageResource;
class AudioResource;

class ResourcePack {
  DISALLOW_COPY_AND_ASSIGN(ResourcePack)

public:

  /**
   * Create a new ResourcePack whose base directory is path.
   *
   * @param path the root path of the resource pack.
   */
  ResourcePack(const string& path) : base_path(path) { }
  ~ResourcePack();

  /**
   * Initialize the ResourcePack, parsing all XML metadata and making the List* methods callable.
   *
   * @return true if initialization was successful, false otherwise.
   */
  bool Init();

  /**
   * Populate a vector with a list of loops (including buildups) present in this resource pack.
   *
   * Note that buildups are NOT counted as a separate song, but instead are returned with (and
   * loaded with) the main loop.
   *
   * @param song_list a vector to place the song list into.
   * @return the number of songs present in this resource pack.
   */
  int GetAllSongs(vector<AudioResource*>& song_list) const;
  /**
   * Populate a vector with a list of images present in this resource pack.
   *
   * @param images_list a vector to place the images list into.
   * @return the number of images present in this resource pack.
   */
  int GetAllImages(vector<ImageResource*>& image_list) const;

  string GetBasePath() const;

private:
  void ParseSongXmlFile();
  void ParseImageXmlFile();

  const string base_path;

  vector<AudioResource*> song_list;
  vector<ImageResource*> image_list;
};

class ImageResource {
  DISALLOW_COPY_AND_ASSIGN(ImageResource)

  friend class ResourcePack;

public:

  /** Alignment for upscaled images and non-matching aspect ratios. */
  enum class Align {
    LEFT,
    CENTER,
    RIGHT
  };

  /**
   * Constructs a new, named ImageResource.
   *
   * @param base_path the base path of the containing ResourcePack.
   * @param name the name of this ImageResource.
   */
  ImageResource(const string& base_path, const string& name, const Align alignment) :
      base_path(base_path), image_name(name), alignment(alignment) { }

  /**
   * Reads this image resource into an OpenGL-compatible RGB(A) byte-array bitmap.
   * The caller is responsible for deallocating the returned byte array once finished.
   *
   * @param width OPTIONAL: a pointer to receive the decoded image's true width.
   * @param height OPTIONAL: a pointer to receive the decoded image's true height.
   * @param color_type OPTIONAL: a pointer to receive the decoded image's color type (usually RGBA).
   */
  png_byte* ReadAndDecode(int *width, int *height, int *color_type) const;

  /** Returns this ImageResource's name (without file extension). */
  string GetName() const { return this->image_name; }
  /** Returns this ImageResource's alignment. */
  Align GetAlignment() const { return this->alignment; }

  /** C++ enums are le suck. */
  static Align ParseAlignmentString(const string& align) {
    if (align == "left") {
      return Align::LEFT;
    } else if (align == "center") {
      return Align::CENTER;
    } else if (align == "right") {
      return Align::RIGHT;
    }
    return Align::CENTER;
  }

private:
  const string base_path;
  const string image_name;
  const Align alignment;
};

class AudioResource {
  DISALLOW_COPY_AND_ASSIGN(AudioResource)

  friend class ResourcePack;

public:

  enum class Beat {
    VERTICAL_BLUR,
    HORIZONTAL_BLUR,
    NO_BLUR,
    BLACKOUT,
    SHORT_BLACKOUT,
    COLOR_ONLY,
    IMAGE_ONLY,
    NO_TRANSITION
  };

  enum class Type {
    LOOP,
    BUILDUP
  };

  /**
   * Constructs a new, named AudioResource.
   *
   * @param base_path the base path of the containing ResourcePack.
   * @param name the name of this AudioResource.
   */
  AudioResource(const string& base_path, const string& song_title,
      const string& loop_name, const string& buildup_name) :
      buildup(buildup_name), loop(loop_name),
      base_path(base_path), song_title(song_title) { }

  /** Returns whether or not this song has a buildup. */
  bool HasBuildup() const { return !this->buildup.name.empty(); }

  string GetTitle() const { return song_title; }
  string GetName(const Type type) const {
    return (type == Type::LOOP ? this->loop : this->buildup).name;
  }
  string GetBeatmap(const Type type) const {
    return (type == Type::LOOP ? this->loop : this->buildup).beatmap;
  }
  double GetSongDurationUsec(const Type type) const {
    return (double) (type == Type::LOOP ? this->loop : this->buildup).sample_count
        / (type == Type::LOOP ? this->loop : this->buildup).sample_rate * 1000 * 1000;
  }
  double GetBeatDurationUsec(const Type type) const {
    return (type == Type::LOOP ? this->loop : this->buildup).usec_per_beat;
  }
  uint8_t* GetPcmData(const Type type) const {
    return (type == Type::LOOP ? this->loop : this->buildup).pcm_data;
  }
  size_t GetPcmDataSize(const Type type) const {
    return (type == Type::LOOP ? this->loop : this->buildup).sample_count
      * GetChannelCount(type) * /* bytes per sample */ 2;
  }
  int GetChannelCount(const Type type) const {
    return (type == Type::LOOP ? this->loop : this->buildup).channel_count;
  }
  int GetSampleRate(const Type type) const {
    return (type == Type::LOOP ? this->loop : this->buildup).sample_rate;
  }

  /**
   * Reads loop/buildup MP3 file (if present), decodes it into a 16 bits per channel, little-endian
   * PCM stream. Once decoded, the appropriate getters can be used to obtain information about this
   * audio resource.
   *
   * If called more than once for the same audio_type, nothing is done.
   *
   * @param audio_type controls whether we decode the loop or beatmap.
   */
  void ReadAndDecode(const Type audio_type);

  static Beat ParseBeatCharacter(const char beatChar) {
    switch (beatChar) {
      case 'x': return Beat::VERTICAL_BLUR;
      case 'o': return Beat::HORIZONTAL_BLUR;
      case '-': return Beat::NO_BLUR;
      case '+': return Beat::BLACKOUT;
      case '|': return Beat::SHORT_BLACKOUT;
      case ':': return Beat::COLOR_ONLY;
      case '*': return Beat::IMAGE_ONLY;
      case '.': return Beat::NO_TRANSITION;
    }
    return Beat::NO_TRANSITION;
  }

private:

  void SetBuildupBeatmap(const string& beatmap) { this->buildup.beatmap = beatmap; }
  void SetLoopBeatmap(const string& beatmap) { this->loop.beatmap = beatmap; }

  struct song_info {
    const string name;
    string beatmap;
    uint8_t *pcm_data;
    int channel_count;
    int sample_count;
    int sample_rate;
    double usec_per_beat;

    song_info(const string& name) : name(name) {}
  } buildup;
  struct song_info loop;

  const string base_path;
  const string song_title;
};

#endif // HUES_RESPACK_H_


text:
![](https://raw.githubusercontent.com/kitware/cinema/master/web/dist/assets/img/icon.png)
# Cinema

Cinema - An Image-based Approach to Extreme Scale In Situ Visualization and Analysis - is an open-source toolkit licensed under the BSD license.

http://kitware.github.io/cinema

Copyright (c) 2014 Kitware Inc. All rights reserved.

Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:

  * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
  disclaimer.
  * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
  disclaimer in the documentation and/or other materials provided with the distribution.
  * Neither name of Kitware Inc. nor the names of any contributors may be used to endorse or promote products derived
  from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


text:
package com.iluwatar.model.view.controller;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * Date: 12/20/15 - 2:10 PM
 *
 * @author Jeroen Meulemeester
 */
public class GiantModelTest {

  /**
   * Verify if the health value is set properly though the constructor and setter
   */
  @Test
  public void testSetHealth() {
    final GiantModel model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
    assertEquals(Health.HEALTHY, model.getHealth());
    for (final Health health : Health.values()) {
      model.setHealth(health);
      assertEquals(health, model.getHealth());
      assertEquals("The giant looks " + health.toString() + ", alert and saturated.", model.toString());
    }
  }

  /**
   * Verify if the fatigue level is set properly though the constructor and setter
   */
  @Test
  public void testSetFatigue() {
    final GiantModel model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
    assertEquals(Fatigue.ALERT, model.getFatigue());
    for (final Fatigue fatigue : Fatigue.values()) {
      model.setFatigue(fatigue);
      assertEquals(fatigue, model.getFatigue());
      assertEquals("The giant looks healthy, " + fatigue.toString() + " and saturated.", model.toString());
    }
  }

  /**
   * Verify if the nourishment level is set properly though the constructor and setter
   */
  @Test
  public void testSetNourishment() {
    final GiantModel model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
    assertEquals(Nourishment.SATURATED, model.getNourishment());
    for (final Nourishment nourishment : Nourishment.values()) {
      model.setNourishment(nourishment);
      assertEquals(nourishment, model.getNourishment());
      assertEquals("The giant looks healthy, alert and " + nourishment.toString() + ".", model.toString());
    }
  }

}


text:
import {
  moduleFor,
  test
} from 'ember-qunit';

moduleFor('route:opportunities', {
  // Specify the other units that are required for this test.
  // needs: ['controller:foo']
});

test('it exists', function(assert) {
  var route = this.subject();
  assert.ok(route);
});


text:
<?php
namespace Topxia\Service\Search\Adapter;

class ArticleSearchAdapter extends AbstractSearchAdapter
{
    public function adapt(array $articles)
    {
        $adaptResult = array();

        foreach ($articles as $index => $article) {
            $articleLocal = $this->getArticleService()->getArticle($article['articleId']);

            if (!empty($articleLocal)) {
                $article['publishedTime'] = $articleLocal['publishedTime'];
                $article['thumb']         = $articleLocal['thumb'];
                $article['id']            = $articleLocal['id'];
                $article['body']          = $article['content'];
                $article['category']      = array('name' => $article['category']);
            }else{
                  $article['publishedTime'] = $article['updatedTime'];
                  $article['body']          = $article['content'];
                  $article['category']      = array('name' => $article['category']);
            }
            array_push($adaptResult, $article);
        }

        return $adaptResult;
    }

    protected function getArticleService()
    {
        return $this->createService('Article.ArticleService');
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations

from corehq.apps.accounting.bootstrap.config.community_v1 import BOOTSTRAP_CONFIG
from corehq.apps.accounting.bootstrap.utils import ensure_plans
from corehq.apps.hqadmin.management.commands.cchq_prbac_bootstrap import cchq_prbac_bootstrap
from corehq.sql_db.operations import HqRunPython

def _bootstrap_new_community_role(apps, schema_editor):
    ensure_plans(BOOTSTRAP_CONFIG, dry_run=False, verbose=True, apps=apps)

class Migration(migrations.Migration):

    dependencies = [
        ('accounting', '0039_auto_20160829_0828'),
    ]

    operations = [
        HqRunPython(cchq_prbac_bootstrap),
        HqRunPython(_bootstrap_new_community_role),
    ]


text:
package io.undertow.servlet.test.listener.request.async.onTimeout;

import io.undertow.util.StatusCodes;

import java.io.IOException;

import jakarta.servlet.AsyncEvent;
import jakarta.servlet.AsyncListener;
import jakarta.servlet.http.HttpServletResponse;

public class SimpleAsyncListener implements AsyncListener {

    @Override
    public void onComplete(AsyncEvent event) throws IOException {
    }

    @Override
    public void onTimeout(AsyncEvent event) throws IOException {
        HttpServletResponse response = (HttpServletResponse) event.getSuppliedResponse();
        response.setStatus(StatusCodes.OK);
        event.getAsyncContext().complete();
    }

    @Override
    public void onError(AsyncEvent event) throws IOException {
    }

    @Override
    public void onStartAsync(AsyncEvent event) throws IOException {
    }

}


text:
const assert = require('chai').assert;
const path = require('path');
const spawnSync = require('child_process').spawnSync;

describe('# Integration (CLI)', () => {

    before(() => {
        this.scriptPath = path.resolve(__dirname, '../index.js');
    });

    describe('#Input files', () => {
        it('# should throw if input file is corrupted', () => {
            const corruptedFilePath = path.resolve(__dirname, './fixtures/corrupted.xml');
            const resultCode = spawnSync(this.scriptPath, ['--input', corruptedFilePath]).status;

            assert.equal(resultCode, 1);
        });
    });

    describe('# Tresholds', () => {
        it('# should not allow \'excelent\' treshold smaller than \'good\'', () => {
            const resultCode = spawnSync(this.scriptPath, ['--excelentTreshold', '50', '--goodTreshold', '70', '--mediumTreshold', '30']).status;

            assert.equal(resultCode, 1);
        });

        it('# should not allow \'excelent\' treshold smaller than \'medium\'', () => {
            const resultCode = spawnSync(this.scriptPath, ['--excelentTreshold', '50', '--goodTreshold', '30', '--mediumTreshold', '70']).status;

            assert.equal(resultCode, 1);
        });

        it('# should not allow \'good\' treshold smaller than \'medium\'', () => {
            const resultCode = spawnSync(this.scriptPath, ['--excelentTreshold', '70', '--goodTreshold', '30', '--mediumTreshold', '50']).status;

            assert.equal(resultCode, 1);
        });
    });
});