text:
edge = {}  # edge[edge cost] = [(node1, node2), (node3, node4),...]
find = {}  # find[node] = leader node of the connected component
cluster = {}  # cluster[leader node of the connected component] = [node1, node2, node3,...]
size = {}  # size[leader node of the connected component] = size of the connected component
with open('clustering1.txt', 'r') as fhand:
    for line in fhand:
        lst = [int(s) for s in line.split()]
        if len(lst) == 1:
            n = lst[0]  # Number of nodes
        elif len(lst) == 3:
            edge[lst[2]] = edge.get(lst[2], []) + [(lst[0], lst[1])]
            find[lst[0]] = find.get(lst[0], lst[0])
            find[lst[1]] = find.get(lst[1], lst[1])
            cluster[lst[0]] = cluster.get(lst[0], [lst[0]])
            cluster[lst[1]] = cluster.get(lst[1], [lst[1]])
            size[lst[0]] = size.get(lst[0], 1)
            size[lst[1]] = size.get(lst[1], 1)

edge_cost_sorted = sorted(edge.keys())
k = len(cluster)
i = 0
for edge_cost in edge_cost_sorted:  # Iterate from the smallest edge cost
    for j in edge[edge_cost]:  # Iterate over all edges with cost i
        if find[j[0]] != find[j[1]]:  # Check if two nodes in the edge are from the same cluster/component
            larger_cluster, smaller_cluster = find[j[0]], find[j[1]]
            if size[smaller_cluster] > size[larger_cluster]:
                larger_cluster, smaller_cluster = smaller_cluster, larger_cluster
            # Update cluster size
            size[larger_cluster] += size[smaller_cluster]
            size.pop(smaller_cluster)
            # Update Union-Find
            for node in cluster[smaller_cluster]:
                find[node] = larger_cluster
            cluster[larger_cluster] += cluster[smaller_cluster]
            cluster.pop(smaller_cluster)
            k -= 1
        if k == 3:
            break
    else:
        i += 1
        continue
    break

print(edge_cost_sorted[i])


text:
class Participant
  include MongoMapper::EmbeddedDocument

  key :score, Integer
  key :players, Set

end

redpajama_set_name: RedPajamaGithub


text:
var CommonPluginInfo = require('cordova-common').PluginInfo;
var AppxManifest = require('./AppxManifest');

/*
A class for holidng the information currently stored in plugin.xml
It's inherited from cordova-common's PluginInfo class
In addition it overrides getConfigFiles, getEditConfigs, getFrameworks methods to use windows-specific logic
 */
function PluginInfo (dirname) {
    //  We're not using `util.inherit' because original PluginInfo defines
    //  its' methods inside of constructor
    CommonPluginInfo.apply(this, arguments);
    var parentGetConfigFiles = this.getConfigFiles;
    var parentGetEditConfigs = this.getEditConfigs;

    this.getEditConfigs = function (platform) {
        var editConfigs = parentGetEditConfigs(platform);
        return AppxManifest.processChanges(editConfigs);
    };

    this.getConfigFiles = function (platform) {
        var configFiles = parentGetConfigFiles(platform);
        return AppxManifest.processChanges(configFiles);
    };
}

exports.PluginInfo = PluginInfo;


text:
from kivy.app import App

class HelloWorldApp(App):
    pass

if __name__ == '__main__':
    HelloWorldApp().run()


text:
namespace hlt {
    /// The states a ship can be in regarding docking.
    enum class ShipDockingStatus {
        Undocked = 0,
        Docking = 1,
        Docked = 2,
        Undocking = 3,
    };

    struct Ship : Entity {
        /// The turns left before the ship can fire again.
        int weapon_cooldown;

        ShipDockingStatus docking_status;

        /// The number of turns left to complete (un)docking.
        int docking_progress;

        /// The id of the planet this ship is docked to. Only valid if
        /// Ship::docking_status is -not- DockingStatus::Undocked.
        EntityId docked_planet;

        /// Check if this ship is close enough to dock to the given planet.
        bool can_dock(const Planet& planet) const {
            return location.get_distance_to(planet.location) <= (constants::DOCK_RADIUS + planet.radius);
        }
    };
}


text:
package consulo.util.dataholder.keyFMap;

import consulo.util.dataholder.Key;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * An immutable map optimized for storing few {@link Key} entries with relatively rare updates
 * To construct a map, start with {@link KeyFMap#EMPTY_MAP} and call {@link #plus} and {@link #minus}
 *
 * @author peter
 */
public interface KeyFMap {
  KeyFMap EMPTY_MAP = new EmptyFMap();

  @Nonnull
  <V> KeyFMap plus(@Nonnull Key<V> key, @Nonnull V value);
  @Nonnull
  KeyFMap minus(@Nonnull Key<?> key);

  @Nullable
  <V> V get(@Nonnull Key<V> key);

  @Nonnull
  Key[] getKeys();

  String toString();

  boolean isEmpty();
}


text:
package sun.security.pkcs11;

import java.io.*;
import java.util.*;

import java.security.*;
import java.security.interfaces.*;

import javax.crypto.interfaces.*;

import javax.security.auth.Subject;
import javax.security.auth.login.LoginException;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.ConfirmationCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.TextOutputCallback;

import sun.security.util.Debug;
import sun.security.util.ResourcesMgr;

import sun.security.pkcs11.Secmod.*;

import sun.security.pkcs11.wrapper.*;
import static sun.security.pkcs11.wrapper.PKCS11Constants.*;

/**
 * PKCS#11 provider main class.
 *
 * @author  Andreas Sterbenz
 * @since   1.5
 */
public final class SunPKCS11 extends AuthProvider {

    private static final long serialVersionUID = -1354835039035306505L;

    static final Debug debug = Debug.getInstance("sunpkcs11");

    private static int dummyConfigId;

    // the PKCS11 object through which we make the native calls
    final PKCS11 p11;

    // name of the configuration file
    private final String configName;

    // configuration information
    final Config config;

    // id of the PKCS#11 slot we are using
    final long slotID;

    private CallbackHandler pHandler;
    private final Object LOCK_HANDLER = new Object();

    final boolean removable;

    final Module nssModule;

    final boolean nssUseSecmodTrust;

    private volatile Token token;

    private TokenPoller poller;

    Token getToken() {
        return token;
    }

    public SunPKCS11() {
        super("SunPKCS11-Dummy", 1.7d, "SunPKCS11-Dummy");
        throw new ProviderException
            ("SunPKCS11 requires configuration file argument");
    }

    public SunPKCS11(String configName) {
        this(checkNull(configName), null);
    }

    public SunPKCS11(InputStream configStream) {
        this(getDummyConfigName(), checkNull(configStream));
    }

    private static <T> T checkNull(T obj) {
        if (obj == null) {
            throw new NullPointerException();
        }
        return obj;
    }

    private static synchronized String getDummyConfigName() {
        int id = ++dummyConfigId;
        return "---DummyConfig-" + id + "---";
    }

    /**
     * @deprecated use new SunPKCS11(String) or new SunPKCS11(InputStream) instead
     */
    @Deprecated
    public SunPKCS11(String configName, InputStream configStream) {
        super("SunPKCS11-" + Config.getConfig(configName, configStream).getName(),
            1.7d, Config.getConfig(configName, configStream).getDescription());
        this.configName = configName;
        this.config = Config.removeConfig(configName);

        if (debug != null) {
            System.out.println("SunPKCS11 loading " + configName);
        }

        String library = config.getLibrary();
        String functionList = config.getFunctionList();
        long slotID = config.getSlotID();
        int slotListIndex = config.getSlotListIndex();

        boolean useSecmod = config.getNssUseSecmod();
        boolean nssUseSecmodTrust = config.getNssUseSecmodTrust();
        Module nssModule = null;

        //
        // Initialization via Secmod. The way this works is as follows:
        // SunPKCS11 is either in normal mode or in NSS Secmod mode.
        // Secmod is activated by specifying one or more of the following
        // options in the config file:
        // nssUseSecmod, nssSecmodDirectory, nssLibrary, nssModule
        //
        // XXX add more explanation here
        //
        // If we are in Secmod mode and configured to use either the
        // nssKeyStore or the nssTrustAnchors module, we automatically
        // switch to using the NSS trust attributes for trusted certs (KeyStore).
        //

        if (useSecmod) {
            // note: Config ensures library/slot/slotListIndex not specified
            // in secmod mode.
            Secmod secmod = Secmod.getInstance();
            DbMode nssDbMode = config.getNssDbMode();
            try {
                String nssLibraryDirectory = config.getNssLibraryDirectory();
                String nssSecmodDirectory = config.getNssSecmodDirectory();

                if (secmod.isInitialized()) {
                    if (nssSecmodDirectory != null) {
                        String s = secmod.getConfigDir();
                        if ((s != null) && (s.equals(nssSecmodDirectory) == false)) {
                            throw new ProviderException("Secmod directory "
                                + nssSecmodDirectory
                                + " invalid, NSS already initialized with " + s);
                        }
                    }
                    if (nssLibraryDirectory != null) {
                        String s = secmod.getLibDir();
                        if ((s != null) && (s.equals(nssLibraryDirectory) == false)) {
                            throw new ProviderException("NSS library directory "
                                + nssLibraryDirectory
                                + " invalid, NSS already initialized with " + s);
                        }
                    }
                } else {
                    if (nssDbMode != DbMode.NO_DB) {
                        if (nssSecmodDirectory == null) {
                            throw new ProviderException("Secmod not initialized and "
                                + "nssSecmodDirectory not specified");
                        }
                    } else {
                        if (nssSecmodDirectory != null) {
                            throw new ProviderException
                            ("nssSecmodDirectory must not be specified in noDb mode");
                        }
                    }
                    secmod.initialize(nssDbMode, nssSecmodDirectory, nssLibraryDirectory);
                }
            } catch (IOException e) {
                // XXX which exception to throw
                throw new ProviderException("Could not initialize NSS", e);
            }
            List<Module> modules = secmod.getModules();
            if (config.getShowInfo()) {
                System.out.println("NSS modules: " + modules);
            }

            String moduleName = config.getNssModule();
            if (moduleName == null) {
                nssModule = secmod.getModule(ModuleType.FIPS);
                if (nssModule != null) {
                    moduleName = "fips";
                } else {
                    moduleName = (nssDbMode == DbMode.NO_DB) ? "crypto" : "keystore";
                }
            }
            if (moduleName.equals("fips")) {
                nssModule = secmod.getModule(ModuleType.FIPS);
                nssUseSecmodTrust = true;
                functionList = "FC_GetFunctionList";
            } else if (moduleName.equals("keystore")) {
                nssModule = secmod.getModule(ModuleType.KEYSTORE);
                nssUseSecmodTrust = true;
            } else if (moduleName.equals("crypto")) {
                nssModule = secmod.getModule(ModuleType.CRYPTO);
            } else if (moduleName.equals("trustanchors")) {
                // XXX should the option be called trustanchor or trustanchors??
                nssModule = secmod.getModule(ModuleType.TRUSTANCHOR);
                nssUseSecmodTrust = true;
            } else if (moduleName.startsWith("external-")) {
                int moduleIndex;
                try {
                    moduleIndex = Integer.parseInt
                            (moduleName.substring("external-".length()));
                } catch (NumberFormatException e) {
                    moduleIndex = -1;
                }
                if (moduleIndex < 1) {
                    throw new ProviderException
                            ("Invalid external module: " + moduleName);
                }
                int k = 0;
                for (Module module : modules) {
                    if (module.getType() == ModuleType.EXTERNAL) {
                        if (++k == moduleIndex) {
                            nssModule = module;
                            break;
                        }
                    }
                }
                if (nssModule == null) {
                    throw new ProviderException("Invalid module " + moduleName
                        + ": only " + k + " external NSS modules available");
                }
            } else {
                throw new ProviderException("Unknown NSS module: " + moduleName);
            }
            if (nssModule == null) {
                throw new ProviderException("NSS module not available: " + moduleName);
            }
            if (nssModule.hasInitializedProvider()) {
                throw new ProviderException("Secmod module already configured");
            }
            library = nssModule.libraryName;
            slotListIndex = nssModule.slot;
        }
        this.nssUseSecmodTrust = nssUseSecmodTrust;
        this.nssModule = nssModule;

        File libraryFile = new File(library);
        // if the filename is a simple filename without path
        // (e.g. "libpkcs11.so"), it may refer to a library somewhere on the
        // OS library search path. Omit the test for file existance as that
        // only looks in the current directory.
        if (libraryFile.getName().equals(library) == false) {
            if (new File(library).isFile() == false) {
                String msg = "Library " + library + " does not exist";
                if (config.getHandleStartupErrors() == Config.ERR_HALT) {
                    throw new ProviderException(msg);
                } else {
                    throw new UnsupportedOperationException(msg);
                }
            }
        }

        try {
            if (debug != null) {
                debug.println("Initializing PKCS#11 library " + library);
            }
            CK_C_INITIALIZE_ARGS initArgs = new CK_C_INITIALIZE_ARGS();
            String nssArgs = config.getNssArgs();
            if (nssArgs != null) {
                initArgs.pReserved = nssArgs;
            }
            // request multithreaded access first
            initArgs.flags = CKF_OS_LOCKING_OK;
            PKCS11 tmpPKCS11;
            try {
                tmpPKCS11 = PKCS11.getInstance
                    (library, functionList, initArgs, config.getOmitInitialize());
            } catch (PKCS11Exception e) {
                if (debug != null) {
                    debug.println("Multi-threaded initialization failed: " + e);
                }
                if (config.getAllowSingleThreadedModules() == false) {
                    throw e;
                }
                // fall back to single threaded access
                if (nssArgs == null) {
                    // if possible, use null initArgs for better compatibility
                    initArgs = null;
                } else {
                    initArgs.flags = 0;
                }
                tmpPKCS11 = PKCS11.getInstance
                    (library, functionList, initArgs, config.getOmitInitialize());
            }
            p11 = tmpPKCS11;

            CK_INFO p11Info = p11.C_GetInfo();
            if (p11Info.cryptokiVersion.major < 2) {
                throw new ProviderException("Only PKCS#11 v2.0 and later "
                + "supported, library version is v" + p11Info.cryptokiVersion);
            }
            boolean showInfo = config.getShowInfo();
            if (showInfo) {
                System.out.println("Information for provider " + getName());
                System.out.println("Library info:");
                System.out.println(p11Info);
            }
            if ((slotID < 0) || showInfo) {
                long[] slots = p11.C_GetSlotList(false);
                if (showInfo) {
                    System.out.println("All slots: " + toString(slots));
                    slots = p11.C_GetSlotList(true);
                    System.out.println("Slots with tokens: " + toString(slots));
                }
                if (slotID < 0) {
                    if ((slotListIndex < 0) || (slotListIndex >= slots.length)) {
                        throw new ProviderException("slotListIndex is " + slotListIndex
                            + " but token only has " + slots.length + " slots");
                    }
                    slotID = slots[slotListIndex];
                }
            }
            this.slotID = slotID;
            CK_SLOT_INFO slotInfo = p11.C_GetSlotInfo(slotID);
            removable = (slotInfo.flags & CKF_REMOVABLE_DEVICE) != 0;
            initToken(slotInfo);
            if (nssModule != null) {
                nssModule.setProvider(this);
            }
        } catch (Exception e) {
            if (config.getHandleStartupErrors() == Config.ERR_IGNORE_ALL) {
                throw new UnsupportedOperationException
                        ("Initialization failed", e);
            } else {
                throw new ProviderException
                        ("Initialization failed", e);
            }
        }
    }

    private static String toString(long[] longs) {
        if (longs.length == 0) {
            return "(none)";
        }
        StringBuilder sb = new StringBuilder();
        sb.append(longs[0]);
        for (int i = 1; i < longs.length; i++) {
            sb.append(", ");
            sb.append(longs[i]);
        }
        return sb.toString();
    }

    // set to true once self verification is complete
    private static volatile boolean integrityVerified;

    static void verifySelfIntegrity(Class c) {
        if (integrityVerified) {
            return;
        }
        doVerifySelfIntegrity(c);
    }

    private static synchronized void doVerifySelfIntegrity(Class c) {
        integrityVerified = JarVerifier.verify(c);
        if (integrityVerified == false) {
            throw new ProviderException
                ("The SunPKCS11 provider may have been tampered with.");
        }
    }

    public boolean equals(Object obj) {
        return this == obj;
    }

    public int hashCode() {
        return System.identityHashCode(this);
    }

    private static String[] s(String s1) {
        return new String[] {s1};
    }

    private static String[] s(String s1, String s2) {
        return new String[] {s1, s2};
    }

    private static final class Descriptor {
        final String type;
        final String algorithm;
        final String className;
        final String[] aliases;
        final int[] mechanisms;

        private Descriptor(String type, String algorithm, String className,
                String[] aliases, int[] mechanisms) {
            this.type = type;
            this.algorithm = algorithm;
            this.className = className;
            this.aliases = aliases;
            this.mechanisms = mechanisms;
        }
        private P11Service service(Token token, int mechanism) {
            return new P11Service
                (token, type, algorithm, className, aliases, mechanism);
        }
        public String toString() {
            return type + "." + algorithm;
        }
    }

    // Map from mechanism to List of Descriptors that should be
    // registered if the mechanism is supported
    private final static Map<Integer,List<Descriptor>> descriptors =
        new HashMap<Integer,List<Descriptor>>();

    private static int[] m(long m1) {
        return new int[] {(int)m1};
    }

    private static int[] m(long m1, long m2) {
        return new int[] {(int)m1, (int)m2};
    }

    private static int[] m(long m1, long m2, long m3) {
        return new int[] {(int)m1, (int)m2, (int)m3};
    }

    private static int[] m(long m1, long m2, long m3, long m4) {
        return new int[] {(int)m1, (int)m2, (int)m3, (int)m4};
    }

    private static void d(String type, String algorithm, String className,
            int[] m) {
        register(new Descriptor(type, algorithm, className, null, m));
    }

    private static void d(String type, String algorithm, String className,
            String[] aliases, int[] m) {
        register(new Descriptor(type, algorithm, className, aliases, m));
    }

    private static void register(Descriptor d) {
        for (int i = 0; i < d.mechanisms.length; i++) {
            int m = d.mechanisms[i];
            Integer key = Integer.valueOf(m);
            List<Descriptor> list = descriptors.get(key);
            if (list == null) {
                list = new ArrayList<Descriptor>();
                descriptors.put(key, list);
            }
            list.add(d);
        }
    }

    private final static String MD  = "MessageDigest";

    private final static String SIG = "Signature";

    private final static String KPG = "KeyPairGenerator";

    private final static String KG  = "KeyGenerator";

    private final static String AGP = "AlgorithmParameters";

    private final static String KF  = "KeyFactory";

    private final static String SKF = "SecretKeyFactory";

    private final static String CIP = "Cipher";

    private final static String MAC = "Mac";

    private final static String KA  = "KeyAgreement";

    private final static String KS  = "KeyStore";

    private final static String SR  = "SecureRandom";

    static {
        // names of all the implementation classes
        // use local variables, only used here
        String P11Digest           = "sun.security.pkcs11.P11Digest";
        String P11MAC              = "sun.security.pkcs11.P11MAC";
        String P11KeyPairGenerator = "sun.security.pkcs11.P11KeyPairGenerator";
        String P11KeyGenerator     = "sun.security.pkcs11.P11KeyGenerator";
        String P11RSAKeyFactory    = "sun.security.pkcs11.P11RSAKeyFactory";
        String P11DSAKeyFactory    = "sun.security.pkcs11.P11DSAKeyFactory";
        String P11DHKeyFactory     = "sun.security.pkcs11.P11DHKeyFactory";
        String P11KeyAgreement     = "sun.security.pkcs11.P11KeyAgreement";
        String P11SecretKeyFactory = "sun.security.pkcs11.P11SecretKeyFactory";
        String P11Cipher           = "sun.security.pkcs11.P11Cipher";
        String P11RSACipher        = "sun.security.pkcs11.P11RSACipher";
        String P11Signature        = "sun.security.pkcs11.P11Signature";

        // XXX register all aliases

        d(MD, "MD2",            P11Digest,
                m(CKM_MD2));
        d(MD, "MD5",            P11Digest,
                m(CKM_MD5));
        d(MD, "SHA1",           P11Digest,              s("SHA", "SHA-1"),
                m(CKM_SHA_1));
        d(MD, "SHA-256",        P11Digest,
                m(CKM_SHA256));
        d(MD, "SHA-384",        P11Digest,
                m(CKM_SHA384));
        d(MD, "SHA-512",        P11Digest,
                m(CKM_SHA512));

        d(MAC, "HmacMD5",       P11MAC,
                m(CKM_MD5_HMAC));
        d(MAC, "HmacSHA1",      P11MAC,
                m(CKM_SHA_1_HMAC));
        d(MAC, "HmacSHA256",    P11MAC,
                m(CKM_SHA256_HMAC));
        d(MAC, "HmacSHA384",    P11MAC,
                m(CKM_SHA384_HMAC));
        d(MAC, "HmacSHA512",    P11MAC,
                m(CKM_SHA512_HMAC));
        d(MAC, "SslMacMD5",     P11MAC,
                m(CKM_SSL3_MD5_MAC));
        d(MAC, "SslMacSHA1",    P11MAC,
                m(CKM_SSL3_SHA1_MAC));

        d(KPG, "RSA",           P11KeyPairGenerator,
                m(CKM_RSA_PKCS_KEY_PAIR_GEN));
        d(KPG, "DSA",           P11KeyPairGenerator,
                m(CKM_DSA_KEY_PAIR_GEN));
        d(KPG, "DH",            P11KeyPairGenerator,    s("DiffieHellman"),
                m(CKM_DH_PKCS_KEY_PAIR_GEN));
        d(KPG, "EC",            P11KeyPairGenerator,
                m(CKM_EC_KEY_PAIR_GEN));

        d(KG,  "ARCFOUR",       P11KeyGenerator,        s("RC4"),
                m(CKM_RC4_KEY_GEN));
        d(KG,  "DES",           P11KeyGenerator,
                m(CKM_DES_KEY_GEN));
        d(KG,  "DESede",        P11KeyGenerator,
                m(CKM_DES3_KEY_GEN, CKM_DES2_KEY_GEN));
        d(KG,  "AES",           P11KeyGenerator,
                m(CKM_AES_KEY_GEN));
        d(KG,  "Blowfish",      P11KeyGenerator,
                m(CKM_BLOWFISH_KEY_GEN));

        // register (Secret)KeyFactories if there are any mechanisms
        // for a particular algorithm that we support
        d(KF, "RSA",            P11RSAKeyFactory,
                m(CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS, CKM_RSA_X_509));
        d(KF, "DSA",            P11DSAKeyFactory,
                m(CKM_DSA_KEY_PAIR_GEN, CKM_DSA, CKM_DSA_SHA1));
        d(KF, "DH",             P11DHKeyFactory,        s("DiffieHellman"),
                m(CKM_DH_PKCS_KEY_PAIR_GEN, CKM_DH_PKCS_DERIVE));
        d(KF, "EC",             P11DHKeyFactory,
                m(CKM_EC_KEY_PAIR_GEN, CKM_ECDH1_DERIVE, CKM_ECDSA, CKM_ECDSA_SHA1));

        // AlgorithmParameters for EC.
        // Only needed until we have an EC implementation in the SUN provider.
        d(AGP, "EC",            "sun.security.ec.ECParameters", s("1.2.840.10045.2.1"),
                m(CKM_EC_KEY_PAIR_GEN, CKM_ECDH1_DERIVE, CKM_ECDSA, CKM_ECDSA_SHA1));

        d(KA, "DH",             P11KeyAgreement,        s("DiffieHellman"),
                m(CKM_DH_PKCS_DERIVE));
        d(KA, "ECDH",           "sun.security.pkcs11.P11ECDHKeyAgreement",
                m(CKM_ECDH1_DERIVE));

        d(SKF, "ARCFOUR",       P11SecretKeyFactory,    s("RC4"),
                m(CKM_RC4));
        d(SKF, "DES",           P11SecretKeyFactory,
                m(CKM_DES_CBC));
        d(SKF, "DESede",        P11SecretKeyFactory,
                m(CKM_DES3_CBC));
        d(SKF, "AES",           P11SecretKeyFactory,
                m(CKM_AES_CBC));
        d(SKF, "Blowfish",      P11SecretKeyFactory,
                m(CKM_BLOWFISH_CBC));

        // XXX attributes for Ciphers (supported modes, padding)
        d(CIP, "ARCFOUR",                       P11Cipher,      s("RC4"),
                m(CKM_RC4));
        // XXX only CBC/NoPadding for block ciphers
        d(CIP, "DES/CBC/NoPadding",             P11Cipher,
                m(CKM_DES_CBC));
        d(CIP, "DESede/CBC/NoPadding",          P11Cipher,
                m(CKM_DES3_CBC));
        d(CIP, "AES/CBC/NoPadding",             P11Cipher,
                m(CKM_AES_CBC));
        d(CIP, "Blowfish/CBC/NoPadding",        P11Cipher,
                m(CKM_BLOWFISH_CBC));

        // XXX RSA_X_509, RSA_OAEP not yet supported
        d(CIP, "RSA/ECB/PKCS1Padding",          P11RSACipher,
                m(CKM_RSA_PKCS));

        d(SIG, "RawDSA",        P11Signature,           s("NONEwithDSA"),
                m(CKM_DSA));
        d(SIG, "DSA",           P11Signature,           s("SHA1withDSA"),
                m(CKM_DSA_SHA1, CKM_DSA));
        d(SIG, "NONEwithECDSA", P11Signature,
                m(CKM_ECDSA));
        d(SIG, "SHA1withECDSA", P11Signature,           s("ECDSA"),
                m(CKM_ECDSA_SHA1, CKM_ECDSA));
        d(SIG, "SHA256withECDSA",       P11Signature,
                m(CKM_ECDSA));
        d(SIG, "SHA384withECDSA",       P11Signature,
                m(CKM_ECDSA));
        d(SIG, "SHA512withECDSA",       P11Signature,
                m(CKM_ECDSA));
        d(SIG, "MD2withRSA",    P11Signature,
                m(CKM_MD2_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
        d(SIG, "MD5withRSA",    P11Signature,
                m(CKM_MD5_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
        d(SIG, "SHA1withRSA",   P11Signature,
                m(CKM_SHA1_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
        d(SIG, "SHA256withRSA", P11Signature,
                m(CKM_SHA256_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
        d(SIG, "SHA384withRSA", P11Signature,
                m(CKM_SHA384_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
        d(SIG, "SHA512withRSA", P11Signature,
                m(CKM_SHA512_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));

        d(KG, "SunTlsRsaPremasterSecret", "sun.security.pkcs11.P11TlsRsaPremasterSecretGenerator",
                m(CKM_SSL3_PRE_MASTER_KEY_GEN, CKM_TLS_PRE_MASTER_KEY_GEN));
        d(KG, "SunTlsMasterSecret", "sun.security.pkcs11.P11TlsMasterSecretGenerator",
                m(CKM_SSL3_MASTER_KEY_DERIVE, CKM_TLS_MASTER_KEY_DERIVE,
                    CKM_SSL3_MASTER_KEY_DERIVE_DH, CKM_TLS_MASTER_KEY_DERIVE_DH));
        d(KG, "SunTlsKeyMaterial", "sun.security.pkcs11.P11TlsKeyMaterialGenerator",
                m(CKM_SSL3_KEY_AND_MAC_DERIVE, CKM_TLS_KEY_AND_MAC_DERIVE));
        d(KG, "SunTlsPrf", "sun.security.pkcs11.P11TlsPrfGenerator",
                m(CKM_TLS_PRF, CKM_NSS_TLS_PRF_GENERAL));
    }

    // background thread that periodically checks for token insertion
    // if no token is present. We need to do that in a separate thread because
    // the insertion check may block for quite a long time on some tokens.
    private static class TokenPoller implements Runnable {
        private final SunPKCS11 provider;
        private volatile boolean enabled;
        private TokenPoller(SunPKCS11 provider) {
            this.provider = provider;
            enabled = true;
        }
        public void run() {
            int interval = provider.config.getInsertionCheckInterval();
            while (enabled) {
                try {
                    Thread.sleep(interval);
                } catch (InterruptedException e) {
                    break;
                }
                if (enabled == false) {
                    break;
                }
                try {
                    provider.initToken(null);
                } catch (PKCS11Exception e) {
                    // ignore
                }
            }
        }
        void disable() {
            enabled = false;
        }
    }

    // create the poller thread, if not already active
    private void createPoller() {
        if (poller != null) {
            return;
        }
        TokenPoller poller = new TokenPoller(this);
        Thread t = new Thread(poller, "Poller " + getName());
        t.setDaemon(true);
        t.setPriority(Thread.MIN_PRIORITY);
        t.start();
        this.poller = poller;
    }

    // destroy the poller thread, if active
    private void destroyPoller() {
        if (poller != null) {
            poller.disable();
            poller = null;
        }
    }

    private boolean hasValidToken() {
        /* Commented out to work with Solaris softtoken impl which
           returns 0-value flags, e.g. both REMOVABLE_DEVICE and
           TOKEN_PRESENT are false, when it can't access the token.
        if (removable == false) {
            return true;
        }
        */
        Token token = this.token;
        return (token != null) && token.isValid();
    }

    // destroy the token. Called if we detect that it has been removed
    synchronized void uninitToken(Token token) {
        if (this.token != token) {
            // mismatch, our token must already be destroyed
            return;
        }
        destroyPoller();
        this.token = null;
        // unregister all algorithms
        AccessController.doPrivileged(new PrivilegedAction<Object>() {
            public Object run() {
                clear();
                return null;
            }
        });
        createPoller();
    }

    // test if a token is present and initialize this provider for it if so.
    // does nothing if no token is found
    // called from constructor and by poller
    private void initToken(CK_SLOT_INFO slotInfo) throws PKCS11Exception {
        if (slotInfo == null) {
            slotInfo = p11.C_GetSlotInfo(slotID);
        }
        if (removable && (slotInfo.flags & CKF_TOKEN_PRESENT) == 0) {
            createPoller();
            return;
        }
        destroyPoller();
        boolean showInfo = config.getShowInfo();
        if (showInfo) {
            System.out.println("Slot info for slot " + slotID + ":");
            System.out.println(slotInfo);
        }
        final Token token = new Token(this);
        if (showInfo) {
            System.out.println
                ("Token info for token in slot " + slotID + ":");
            System.out.println(token.tokenInfo);
        }
        long[] supportedMechanisms = p11.C_GetMechanismList(slotID);
        final Map<Descriptor,Integer> supportedAlgs =
                                        new HashMap<Descriptor,Integer>();
        for (int i = 0; i < supportedMechanisms.length; i++) {
            long longMech = supportedMechanisms[i];
            boolean isEnabled = config.isEnabled(longMech);
            if (showInfo) {
                CK_MECHANISM_INFO mechInfo =
                        p11.C_GetMechanismInfo(slotID, longMech);
                System.out.println("Mechanism " +
                        Functions.getMechanismName(longMech) + ":");
                if (isEnabled == false) {
                    System.out.println("DISABLED in configuration");
                }
                System.out.println(mechInfo);
            }
            if (isEnabled == false) {
                continue;
            }
            // we do not know of mechs with the upper 32 bits set
            if (longMech >>> 32 != 0) {
                continue;
            }
            int mech = (int)longMech;
            Integer integerMech = Integer.valueOf(mech);
            List<Descriptor> ds = descriptors.get(integerMech);
            if (ds == null) {
                continue;
            }
            for (Descriptor d : ds) {
                Integer oldMech = supportedAlgs.get(d);
                if (oldMech == null) {
                    supportedAlgs.put(d, integerMech);
                    continue;
                }
                int intOldMech = oldMech.intValue();
                for (int j = 0; j < d.mechanisms.length; j++) {
                    int nextMech = d.mechanisms[j];
                    if (mech == nextMech) {
                        supportedAlgs.put(d, integerMech);
                        break;
                    } else if (intOldMech == nextMech) {
                        break;
                    }
                }
            }

        }

        // register algorithms in provider
        AccessController.doPrivileged(new PrivilegedAction<Object>() {
            public Object run() {
                for (Map.Entry<Descriptor,Integer> entry
                        : supportedAlgs.entrySet()) {
                    Descriptor d = entry.getKey();
                    int mechanism = entry.getValue().intValue();
                    Service s = d.service(token, mechanism);
                    putService(s);
                }
                if (((token.tokenInfo.flags & CKF_RNG) != 0)
                        && config.isEnabled(PCKM_SECURERANDOM)
                        && !token.sessionManager.lowMaxSessions()) {
                    // do not register SecureRandom if the token does
                    // not support many sessions. if we did, we might
                    // run out of sessions in the middle of a
                    // nextBytes() call where we cannot fail over.
                    putService(new P11Service(token, SR, "PKCS11",
                        "sun.security.pkcs11.P11SecureRandom", null,
                        PCKM_SECURERANDOM));
                }
                if (config.isEnabled(PCKM_KEYSTORE)) {
                    putService(new P11Service(token, KS, "PKCS11",
                        "sun.security.pkcs11.P11KeyStore",
                        s("PKCS11-" + config.getName()),
                        PCKM_KEYSTORE));
                }
                return null;
            }
        });

        this.token = token;
    }

    private static final class P11Service extends Service {

        private final Token token;

        private final long mechanism;

        P11Service(Token token, String type, String algorithm,
                String className, String[] al, long mechanism) {
            super(token.provider, type, algorithm, className, toList(al), null);
            this.token = token;
            this.mechanism = mechanism & 0xFFFFFFFFL;
        }

        private static List<String> toList(String[] aliases) {
            return (aliases == null) ? null : Arrays.asList(aliases);
        }

        public Object newInstance(Object param) throws NoSuchAlgorithmException {
            if (token.isValid() == false) {
                throw new NoSuchAlgorithmException("Token has been removed");
            }
            try {
                return newInstance0(param);
            } catch (PKCS11Exception e) {
                throw new NoSuchAlgorithmException(e);
            }
        }

        public Object newInstance0(Object param) throws
                PKCS11Exception, NoSuchAlgorithmException {
            String algorithm = getAlgorithm();
            String type = getType();
            if (type == MD) {
                return new P11Digest(token, algorithm, mechanism);
            } else if (type == CIP) {
                verifySelfIntegrity(getClass());
                if (algorithm.startsWith("RSA")) {
                    return new P11RSACipher(token, algorithm, mechanism);
                } else {
                    return new P11Cipher(token, algorithm, mechanism);
                }
            } else if (type == SIG) {
                return new P11Signature(token, algorithm, mechanism);
            } else if (type == MAC) {
                verifySelfIntegrity(getClass());
                return new P11Mac(token, algorithm, mechanism);
            } else if (type == KPG) {
                return new P11KeyPairGenerator(token, algorithm, mechanism);
            } else if (type == KA) {
                verifySelfIntegrity(getClass());
                if (algorithm.equals("ECDH")) {
                    return new P11ECDHKeyAgreement(token, algorithm, mechanism);
                } else {
                    return new P11KeyAgreement(token, algorithm, mechanism);
                }
            } else if (type == KF) {
                return token.getKeyFactory(algorithm);
            } else if (type == SKF) {
                verifySelfIntegrity(getClass());
                return new P11SecretKeyFactory(token, algorithm);
            } else if (type == KG) {
                verifySelfIntegrity(getClass());

                // reference equality
                if (algorithm == "SunTlsRsaPremasterSecret") {
                    return new P11TlsRsaPremasterSecretGenerator(
                        token, algorithm, mechanism);
                } else if (algorithm == "SunTlsMasterSecret") {
                    return new P11TlsMasterSecretGenerator(
                        token, algorithm, mechanism);
                } else if (algorithm == "SunTlsKeyMaterial") {
                    return new P11TlsKeyMaterialGenerator(
                        token, algorithm, mechanism);
                } else if (algorithm == "SunTlsPrf") {
                    return new P11TlsPrfGenerator(token, algorithm, mechanism);
                } else {
                    return new P11KeyGenerator(token, algorithm, mechanism);
                }
            } else if (type == SR) {
                return token.getRandom();
            } else if (type == KS) {
                return token.getKeyStore();
            } else if (type == AGP) {
                return new sun.security.ec.ECParameters();
            } else {
                throw new NoSuchAlgorithmException("Unknown type: " + type);
            }
        }

        public boolean supportsParameter(Object param) {
            if ((param == null) || (token.isValid() == false)) {
                return false;
            }
            if (param instanceof Key == false) {
                throw new InvalidParameterException("Parameter must be a Key");
            }
            String algorithm = getAlgorithm();
            String type = getType();
            Key key = (Key)param;
            String keyAlgorithm = key.getAlgorithm();
            // RSA signatures and cipher
            if (((type == CIP) && algorithm.startsWith("RSA"))
                    || (type == SIG) && algorithm.endsWith("RSA")) {
                if (keyAlgorithm.equals("RSA") == false) {
                    return false;
                }
                return isLocalKey(key)
                        || (key instanceof RSAPrivateKey)
                        || (key instanceof RSAPublicKey);
            }
            // EC
            if (((type == KA) && algorithm.equals("ECDH"))
                    || ((type == SIG) && algorithm.endsWith("ECDSA"))) {
                if (keyAlgorithm.equals("EC") == false) {
                    return false;
                }
                return isLocalKey(key)
                        || (key instanceof ECPrivateKey)
                        || (key instanceof ECPublicKey);
            }
            // DSA signatures
            if ((type == SIG) && algorithm.endsWith("DSA")) {
                if (keyAlgorithm.equals("DSA") == false) {
                    return false;
                }
                return isLocalKey(key)
                        || (key instanceof DSAPrivateKey)
                        || (key instanceof DSAPublicKey);
            }
            // MACs and symmetric ciphers
            if ((type == CIP) || (type == MAC)) {
                // do not check algorithm name, mismatch is unlikely anyway
                return isLocalKey(key) || "RAW".equals(key.getFormat());
            }
            // DH key agreement
            if (type == KA) {
                if (keyAlgorithm.equals("DH") == false) {
                    return false;
                }
                return isLocalKey(key)
                        || (key instanceof DHPrivateKey)
                        || (key instanceof DHPublicKey);
            }
            // should not reach here,
            // unknown engine type or algorithm
            throw new AssertionError
                ("SunPKCS11 error: " + type + ", " + algorithm);
        }

        private boolean isLocalKey(Key key) {
            return (key instanceof P11Key) && (((P11Key)key).token == token);
        }

        public String toString() {
            return super.toString() +
                " (" + Functions.getMechanismName(mechanism) + ")";
        }

    }

    /**
     * Log in to this provider.
     *
     * <p> If the token expects a PIN to be supplied by the caller,
     * the <code>handler</code> implementation must support
     * a <code>PasswordCallback</code>.
     *
     * <p> To determine if the token supports a protected authentication path,
     * the CK_TOKEN_INFO flag, CKF_PROTECTED_AUTHENTICATION_PATH, is consulted.
     *
     * @param subject this parameter is ignored
     * @param handler the <code>CallbackHandler</code> used by
     *  this provider to communicate with the caller
     *
     * @exception LoginException if the login operation fails
     * @exception SecurityException if the does not pass a security check for
     *  <code>SecurityPermission("authProvider.<i>name</i>")</code>,
     *  where <i>name</i> is the value returned by
     *  this provider's <code>getName</code> method
     */
    public void login(Subject subject, CallbackHandler handler)
        throws LoginException {

        // security check

        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            if (debug != null) {
                debug.println("checking login permission");
            }
            sm.checkPermission(new SecurityPermission
                        ("authProvider." + this.getName()));
        }

        if (hasValidToken() == false) {
            throw new LoginException("No token present");
        }

        // see if a login is required

        if ((token.tokenInfo.flags & CKF_LOGIN_REQUIRED) == 0) {
            if (debug != null) {
                debug.println("login operation not required for token - " +
                                "ignoring login request");
            }
            return;
        }

        // see if user already logged in

        try {
            if (token.isLoggedInNow(null)) {
                // user already logged in
                if (debug != null) {
                    debug.println("user already logged in");
                }
                return;
            }
        } catch (PKCS11Exception e) {
            // ignore - fall thru and attempt login
        }

        // get the pin if necessary

        char[] pin = null;
        if ((token.tokenInfo.flags & CKF_PROTECTED_AUTHENTICATION_PATH) == 0) {

            // get password

            CallbackHandler myHandler = getCallbackHandler(handler);
            if (myHandler == null) {
                // XXX PolicyTool is dependent on this message text
                throw new LoginException
                        ("no password provided, and no callback handler " +
                        "available for retrieving password");
            }

            java.text.MessageFormat form = new java.text.MessageFormat
                        (ResourcesMgr.getString
                        ("PKCS11 Token [providerName] Password: "));
            Object[] source = { getName() };

            PasswordCallback pcall = new PasswordCallback(form.format(source),
                                                        false);
            Callback[] callbacks = { pcall };
            try {
                myHandler.handle(callbacks);
            } catch (Exception e) {
                LoginException le = new LoginException
                        ("Unable to perform password callback");
                le.initCause(e);
                throw le;
            }

            pin = pcall.getPassword();
            pcall.clearPassword();
            if (pin == null) {
                if (debug != null) {
                    debug.println("caller passed NULL pin");
                }
            }
        }

        // perform token login

        Session session = null;
        try {
            session = token.getOpSession();

            // pin is NULL if using CKF_PROTECTED_AUTHENTICATION_PATH
            p11.C_Login(session.id(), CKU_USER, pin);
            if (debug != null) {
                debug.println("login succeeded");
            }
        } catch (PKCS11Exception pe) {
            if (pe.getErrorCode() == CKR_USER_ALREADY_LOGGED_IN) {
                // let this one go
                if (debug != null) {
                    debug.println("user already logged in");
                }
                return;
            } else if (pe.getErrorCode() == CKR_PIN_INCORRECT) {
                FailedLoginException fle = new FailedLoginException();
                fle.initCause(pe);
                throw fle;
            } else {
                LoginException le = new LoginException();
                le.initCause(pe);
                throw le;
            }
        } finally {
            token.releaseSession(session);
            if (pin != null) {
                Arrays.fill(pin, ' ');
            }
        }

        // we do not store the PIN in the subject for now
    }

    /**
     * Log out from this provider
     *
     * @exception LoginException if the logout operation fails
     * @exception SecurityException if the does not pass a security check for
     *  <code>SecurityPermission("authProvider.<i>name</i>")</code>,
     *  where <i>name</i> is the value returned by
     *  this provider's <code>getName</code> method
     */
    public void logout() throws LoginException {

        // security check

        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission
                (new SecurityPermission("authProvider." + this.getName()));
        }

        if (hasValidToken() == false) {
            // app may call logout for cleanup, allow
            return;
        }

        if ((token.tokenInfo.flags & CKF_LOGIN_REQUIRED) == 0) {
            if (debug != null) {
                debug.println("logout operation not required for token - " +
                                "ignoring logout request");
            }
            return;
        }

        try {
            if (token.isLoggedInNow(null) == false) {
                if (debug != null) {
                    debug.println("user not logged in");
                }
                return;
            }
        } catch (PKCS11Exception e) {
            // ignore
        }

        // perform token logout

        Session session = null;
        try {
            session = token.getOpSession();
            p11.C_Logout(session.id());
            if (debug != null) {
                debug.println("logout succeeded");
            }
        } catch (PKCS11Exception pe) {
            if (pe.getErrorCode() == CKR_USER_NOT_LOGGED_IN) {
                // let this one go
                if (debug != null) {
                    debug.println("user not logged in");
                }
                return;
            }
            LoginException le = new LoginException();
            le.initCause(pe);
            throw le;
        } finally {
            token.releaseSession(session);
        }
    }

    /**
     * Set a <code>CallbackHandler</code>
     *
     * <p> The provider uses this handler if one is not passed to the
     * <code>login</code> method.  The provider also uses this handler
     * if it invokes <code>login</code> on behalf of callers.
     * In either case if a handler is not set via this method,
     * the provider queries the
     * <i>auth.login.defaultCallbackHandler</i> security property
     * for the fully qualified class name of a default handler implementation.
     * If the security property is not set,
     * the provider is assumed to have alternative means
     * for obtaining authentication information.
     *
     * @param handler a <code>CallbackHandler</code> for obtaining
     *          authentication information, which may be <code>null</code>
     *
     * @exception SecurityException if the caller does not pass a
     *  security check for
     *  <code>SecurityPermission("authProvider.<i>name</i>")</code>,
     *  where <i>name</i> is the value returned by
     *  this provider's <code>getName</code> method
     */
    public void setCallbackHandler(CallbackHandler handler) {

        // security check

        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission
                (new SecurityPermission("authProvider." + this.getName()));
        }

        synchronized (LOCK_HANDLER) {
            pHandler = handler;
        }
    }

    private CallbackHandler getCallbackHandler(CallbackHandler handler) {

        // get default handler if necessary

        if (handler != null) {
            return handler;
        }

        if (debug != null) {
            debug.println("getting provider callback handler");
        }

        synchronized (LOCK_HANDLER) {
            // see if handler was set via setCallbackHandler
            if (pHandler != null) {
                return pHandler;
            }

            try {
                if (debug != null) {
                    debug.println("getting default callback handler");
                }

                CallbackHandler myHandler = AccessController.doPrivileged
                    (new PrivilegedExceptionAction<CallbackHandler>() {
                    public CallbackHandler run() throws Exception {

                        String defaultHandler =
                                java.security.Security.getProperty
                                ("auth.login.defaultCallbackHandler");

                        if (defaultHandler == null ||
                            defaultHandler.length() == 0) {

                            // ok
                            if (debug != null) {
                                debug.println("no default handler set");
                            }
                            return null;
                        }

                        Class c = Class.forName
                                (defaultHandler,
                                true,
                                Thread.currentThread().getContextClassLoader());
                        return (CallbackHandler)c.newInstance();
                    }
                });

                // save it
                pHandler = myHandler;
                return myHandler;

            } catch (PrivilegedActionException pae) {
                // ok
                if (debug != null) {
                    debug.println("Unable to load default callback handler");
                    pae.printStackTrace();
                }
            }
        }
        return null;
    }

    private Object writeReplace() throws ObjectStreamException {
        return new SunPKCS11Rep(this);
    }

    /**
     * Serialized representation of the SunPKCS11 provider.
     */
    private static class SunPKCS11Rep implements Serializable {

        static final long serialVersionUID = -2896606995897745419L;

        private final String providerName;

        private final String configName;

        SunPKCS11Rep(SunPKCS11 provider) throws NotSerializableException {
            providerName = provider.getName();
            configName = provider.configName;
            if (Security.getProvider(providerName) != provider) {
                throw new NotSerializableException("Only SunPKCS11 providers "
                    + "installed in java.security.Security can be serialized");
            }
        }

        private Object readResolve() throws ObjectStreamException {
            SunPKCS11 p = (SunPKCS11)Security.getProvider(providerName);
            if ((p == null) || (p.configName.equals(configName) == false)) {
                throw new NotSerializableException("Could not find "
                        + providerName + " in installed providers");
            }
            return p;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NETGeographicLib;

namespace Projections
{
    public partial class LocalCartesianPanel : UserControl
    {
        LocalCartesian m_lc = null;
        enum Functions
        {
            Forward,
            Reverse
        };
        Functions m_function = Functions.Forward;

        public LocalCartesianPanel()
        {
            InitializeComponent();

            Geocentric g = new Geocentric();
            m_majorRadiusTextBox.Text = g.MajorRadius.ToString();
            m_flatteningTextBox.Text = g.Flattening.ToString();
            m_lc = new LocalCartesian(g);
            m_functionComboBox.SelectedIndex = (int)m_function;
        }

        private void OnSetEllipsoid(object sender, EventArgs e)
        {
            double a, f;
            try
            {
                a = Double.Parse(m_majorRadiusTextBox.Text);
                f = Double.Parse(m_flatteningTextBox.Text);
            }
            catch (Exception xcpt)
            {
                MessageBox.Show(xcpt.Message, "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                m_lc = new LocalCartesian(new Geocentric(a, f));
            }
            catch (GeographicErr err)
            {
                MessageBox.Show(err.Message, "GeographicLib error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void OnSetReference(object sender, EventArgs e)
        {
            double lat, lon, alt;
            try
            {
                lat = Double.Parse(m_latitudeTextBox.Text);
                lon = Double.Parse(m_longitudeTextBox.Text);
                alt = Double.Parse(m_altitudeTextBox.Text);
            }
            catch (Exception xcpt)
            {
                MessageBox.Show(xcpt.Message, "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            m_lc.Reset(lat, lon, alt);
        }

        private void OnConvert(object sender, EventArgs e)
        {
            try
            {
                double lat, lon, alt, x, y, z;
                double[,] rot = null;
                switch (m_function)
                {
                    case Functions.Forward:
                        lat = Double.Parse(m_latTextBox.Text);
                        lon = Double.Parse(m_lonTextBox.Text);
                        alt = Double.Parse(m_altTextBox.Text);
                        m_lc.Forward(lat, lon, alt, out x, out y, out z, out rot);
                        m_XTextBox.Text = x.ToString("0.00###");
                        m_YTextBox.Text = y.ToString("0.00###");
                        m_ZTextBox.Text = z.ToString("0.00###");
                        break;
                    case Functions.Reverse:
                        x = Double.Parse(m_XTextBox.Text);
                        y = Double.Parse(m_YTextBox.Text);
                        z = Double.Parse(m_ZTextBox.Text);
                        m_lc.Reverse(x, y, z, out lat, out lon, out alt, out rot);
                        m_latTextBox.Text = lat.ToString();
                        m_lonTextBox.Text = lon.ToString();
                        m_altTextBox.Text = alt.ToString();
                        break;
                }
                m_textBox00.Text = rot[0, 0].ToString("#.000000000000");
                m_textBox01.Text = rot[0, 1].ToString("#.000000000000");
                m_textBox02.Text = rot[0, 2].ToString("#.000000000000");
                m_textBox10.Text = rot[1, 0].ToString("#.000000000000");
                m_textBox11.Text = rot[1, 1].ToString("#.000000000000");
                m_textBox12.Text = rot[1, 2].ToString("#.000000000000");
                m_textBox20.Text = rot[2, 0].ToString("#.000000000000");
                m_textBox21.Text = rot[2, 1].ToString("#.000000000000");
                m_textBox22.Text = rot[2, 2].ToString("#.000000000000");
            }
            catch (Exception xcpt)
            {
                MessageBox.Show(xcpt.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void OnNewFunction(object sender, EventArgs e)
        {
            m_function = (Functions)m_functionComboBox.SelectedIndex;
            switch (m_function)
            {
                case Functions.Forward:
                    m_latTextBox.ReadOnly = m_lonTextBox.ReadOnly = m_altTextBox.ReadOnly = false;
                    m_XTextBox.ReadOnly = m_YTextBox.ReadOnly = m_ZTextBox.ReadOnly = true;
                    break;
                case Functions.Reverse:
                    m_latTextBox.ReadOnly = m_lonTextBox.ReadOnly = m_altTextBox.ReadOnly = true;
                    m_XTextBox.ReadOnly = m_YTextBox.ReadOnly = m_ZTextBox.ReadOnly = false;
                    break;
            }
        }

        private void OnValidate(object sender, EventArgs e)
        {
            try
            {
                LocalCartesian p = new LocalCartesian();
                p = new LocalCartesian(new Geocentric());
                p = new LocalCartesian(32.0, -86.0, 45.0);
                p = new LocalCartesian(32.0, -86.0, 45.0, new Geocentric());
                double x, y, z, x1, y1, z1;
                double[,] rot;
                p.Forward(32.0, -86.0, 45.0, out x, out y, out z, out rot);
                p.Forward(32.0, -86.0, 45.0, out x1, out y1, out z1);
                if (x != x1 || y != y1 || z != z1)
                    throw new Exception("Error in Forward");
                double lat, lon, alt;
                p.Reverse(x, y, z, out lat, out lon, out alt, out rot);
                p.Reverse(x, y, z, out x1, out y1, out z1);
                if (lat != x1 || lon != y1 || alt != z1)
                    throw new Exception("Error in Reverse");
            }
            catch (Exception xcpt)
            {
                MessageBox.Show(xcpt.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            MessageBox.Show("No errors detected", "OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}


text:
require File.dirname(__FILE__) + '/../spec_helper_mongoid'

#
# Test model
class User
  include Mongoid::Document
  include Mongoid::Symbolize

  symbolize :other
  symbolize :language, :in => [:pt, :en]
#  symbolize :sex, :in => [true, false], :scopes => true
  symbolize :status , :in => [:active, :inactive], :i18n => false, :capitalize => true, :scopes => true
  symbolize :so, :allow_blank => true, :in => {
    :linux => 'Linux',
    :mac   => 'Mac OS X',
    :win   => 'Videogame'
  }, :scopes => true
  symbolize :gui, :allow_blank => true, :in => [:cocoa, :qt, :gtk], :i18n => false
  symbolize :karma, :in => %w{ good bad ugly}, :methods => true, :i18n => false, :allow_nil => true
 # symbolize :cool, :in => [true, false], :scopes => true

  has_many :extras, :dependent => :destroy, :class_name => "UserExtra"
  embeds_many :skills, :class_name => "UserSkill"
end

class UserSkill
  include Mongoid::Document
  include Mongoid::Symbolize

  symbolize :kind, :in => [:agility, :magic]
end

class UserExtra
  include Mongoid::Document
  include Mongoid::Symbolize

  symbolize :key, :in => [:one, :another]
end

class Permission
  include Mongoid::Document
  include Mongoid::Symbolize

  validates_presence_of :name
  symbolize :kind, :in => [:temp, :perm], :default => :perm
end

[User, UserExtra, UserSkill, Permission].each { |k| k.destroy_all }

# Test records
User.create(:name => 'Anna', :other => :fo, :status => :active  , :so => :linux, :gui => :qt, :language => :pt, :sex => true, :cool => true)
User.create!(:name => 'Bob' , :other => :bar,:status => :inactive, :so => :mac, :gui => :gtk, :language => :en, :sex => false, :cool => false)

describe "Symbolize" do

  it "should be a module" do
    Mongoid.const_defined?("Symbolize").should be_true
  end

  describe "User Instantiated" do
    before(:each) do
      @user = User.first
    end

    it "test_symbolize_string" do
      @user.status = 'inactive'
      @user.status.should eql(:inactive)
      #      @user.status_before_type_cast.should eql(:inactive)
      # @user.read_attribute(:status).should eql('inactive')
    end

    it "test_symbolize_symbol" do
      @user.status = :active
      @user.status.should eql(:active)
      @user.save
      @user.status.should eql(:active)
      @user[:status].should eql(:active)
    end

    # it "should work nice with numbers" do
    #   pending
    #   @user.status = 43
    #   @user.status.should_not be_nil
    #   # @user.status_before_type_cast.should be_nil
    #   # @user.read_attribute(:status).should be_nil
    # end

    # it "should acts nice with nil" do
    #   @user.status = nil
    #   @user.status.should be_nil
    #   @user.status_before_type_cast.should be_nil
    #   @user.read_attribute(:status).should be_nil
    # end

    # it "should acts nice with blank" do
    #   @user.status = ""
    #   @user.status.should be_nil
    #   @user.status_before_type_cast.should be_nil
    #   @user.read_attribute(:status).should be_nil
    # end

    it "should not validates other" do
      @user.other = nil
      @user.should be_valid
      @user.other = ""
      @user.should be_valid
    end

    it "should get the correct values" do
      User.get_status_values.should eql([["Active", :active],["Inactive", :inactive]])
      User::STATUS_VALUES.should eql({:inactive=>"Inactive", :active=>"Active"})
    end

    it "test_symbolize_humanize" do
      @user.status_text.should eql("Active")
    end

    it "should get the correct values" do
      User.get_gui_values.should =~ [["cocoa", :cocoa], ["qt", :qt], ["gtk", :gtk]]
      User::GUI_VALUES.should eql({:cocoa=>"cocoa", :qt=>"qt", :gtk=>"gtk"})
    end

    it "test_symbolize_humanize" do
      @user.gui_text.should eql("qt")
    end

    it "should get the correct values" do
      User.get_so_values.should =~ [["Linux", :linux], ["Mac OS X", :mac], ["Videogame", :win]]
      User::SO_VALUES.should eql({:linux => "Linux", :mac => "Mac OS X", :win => "Videogame"})
    end

    it "test_symbolize_humanize" do
      @user.so_text.should eql("Linux")
    end

    it "test_symbolize_humanize" do
      @user.so = :mac
      @user.so_text.should eql("Mac OS X")
    end

    it "should stringify" do
      @user.other_text.should eql("fo")
      @user.other = :foo
      @user.other_text.should eql("foo")
    end

    it "should validate status" do
      @user.status = nil
      @user.should_not be_valid
      @user.should have(1).errors
    end

    it "should not validate so" do
      @user.so = nil
      @user.should be_valid
    end

    it "test_symbols_with_weird_chars_quoted_id" do
      @user.status = :"weird'; chars"
      @user.status.should eql(:"weird'; chars")
    end

    it "should work fine through relations" do
      @user.extras.create(:key => :one)
      UserExtra.first.key.should eql(:one)
    end

    # it "should play fine with null db columns" do
    #   new_extra = @user.extras.build
    #   new_extra.should_not be_valid
    # end

    # it "should play fine with null db columns" do
    #   new_extra = @user.extras.build
    #   new_extra.should_not be_valid
    # end

    # describe "View helpers" do
    #   include ActionView::Helpers::FormHelper
    #   include ActionView::Helpers::FormOptionsHelper

    #   before(:each) do
    #     @options_status = [['Active', :active], ['Inactive', :inactive]]
    #     @options_gui    = [["cocoa", :cocoa], ["qt", :qt], ["gtk", :gtk]]
    #     @options_so     = [["Linux", :linux]  , ["Mac OS X", :mac], ["Videogame", :win]]
    #   end

    #   it "test_helper_select_sym" do
    #     @user.status = :inactive
    #     output = "<select id=\"user_status\" name=\"user[status]\">#{options_for_select(@options_status, @user.status)}</select>"
    #     output.should eql(select_sym("user", "status", nil))

    #     output = "<select id=\"user_status\" name=\"user[status]\">#{options_for_select(@options_status, @user.status)}</select>"
    #     output.should eql(select_sym("user", "status", nil))
    #   end

    #   def test_helper_select_sym_order
    #     output_so     = "<select id=\"user_so\" name=\"user[so]\">#{options_for_select(@options_so, @user.so)}</select>"
    #     output_office = "<select id=\"user_office\" name=\"user[office]\">#{options_for_select(@options_office, @user.office)}</select>"

    #     assert_equal output_so.should, select_sym("user", "so", nil)
    #     assert_equal output_office, select_sym("user", "office", nil)
    #   end

    #   def test_helper_radio_sym
    #     output = radio_sym("user", "status", nil)
    #     assert_equal("Active: <input checked=\"checked\" id=\"user_status_active\" name=\"user[status]\" type=\"radio\" value=\"active\" />Inactive: <input id=\"user_status_inactive\" name=\"user[status]\" type=\"radio\" value=\"inactive\" />", output)
    #   end

    # end

    describe "i18n" do

      it "should test i18n ones" do
        @user.language_text.should eql("Português")
      end

      it "should get the correct values" do
        User.get_language_values.should =~ [["Português", :pt], ["Inglês", :en]]
      end

      it "should get the correct values" do
        User::LANGUAGE_VALUES.should eql({:pt=>"pt", :en=>"en"})
      end

      # it "should test boolean" do
      #   @user.sex_text.should eql("Feminino")
      # end

      # it "should get the correct values" do
      #   User.get_sex_values.should eql([["Feminino", true],["Masculino", false]])
      # end

      # it "should get the correct values" do
      #   User::SEX_VALUES.should eql({true=>"true", false=>"false"})
      # end

      it "should translate a multiword class" do
        @skill = UserSkill.create(:kind => :magic)
        @skill.kind_text.should eql("Mágica")
      end

      it "should return nil if there's no value" do
        @skill = UserSkill.create(:kind => nil)
        @skill.kind_text.should be_nil
      end

    end

    describe "Methods" do

      it "should play nice with other stuff" do
        @user.karma.should be_nil
        User::KARMA_VALUES.should eql({:bad => "bad", :ugly => "ugly", :good => "good"})
      end

      it "should provide a boolean method" do
        @user.should_not be_good
        @user.karma = :ugly
        @user.should be_ugly
      end

      it "should work" do
        @user.karma = "good"
        @user.should be_good
        @user.should_not be_bad
      end

    end

  end

  describe "more tests on Permission" do

    it "should use default value on object build" do
      Permission.new.kind.should eql(:perm)
    end

    it "should not interfer on create" do
      Permission.create!(:name => "p7", :kind => :temp)
      Permission.where(name: "p7").first.kind.should eql(:temp)
    end

    it "should work on create" do
      pm = Permission.new(:name => "p7")
      pm.should be_valid
      pm.save.should be_true
    end

    it "should work on create" do
      Permission.create(:name => "p8")
      Permission.first(conditions: { name: "p8" }).kind.should eql(:perm)
    end

    it "should work on edit" do
      pm = Permission.where(name: "p8").first
      pm.kind = :temp
      pm.save
      Permission.where(name: "p8").first.kind.should eql(:temp)
    end

  end

  describe "Mongoid stuff" do

    it "test_symbolized_finder" do
      User.where({ :status => :inactive }).all.map(&:name).should eql(['Bob'])
      User.where(status: :inactive).map(&:name).should eql(['Bob'])
    end

    # it "test_symabolized_with_scope" do
    #   User.with_scope({ :status => :inactive }) do
    #     User.all.map(&:name).should eql(['Bob'])
    #   end
    # end

    describe "dirty tracking / changed flag" do
      before do
        @anna = User.where(name: 'Anna').first
      end

      it "is dirty if you change the attribute value" do
        @anna.language.should == :pt
        @anna.language_changed?.should be_false

        return_value = @anna.language = :en
        return_value.should == :en
        @anna.language_changed?.should be_true
      end

      it "is not dirty if you set the attribute value to the same value it was originally" do
        @anna.language.should == :pt
        @anna.language_changed?.should be_false

        return_value = @anna.language = :pt
        return_value.should == :pt
        @anna.language_changed?.should be_false
      end
    end

  end

end


text:
id: 1741
title: 'Prueba de posteo desde #orgmode usando #Org2blog'
date: 2012-10-05T10:47:34+00:00
author: Alvar
layout: post
guid: http://www.acercadelaeducacion.com.ar/?p=1741
permalink: /2012/10/prueba-de-posteo-desde-orgmode-usando-org2blog-2/
dsq_thread_id:
  - "1955417995"
bitly_url:
  - http://bit.ly/1Otm3LA
bitly_hash:
  - 1Otm3LA
bitly_long_url:
  - http://www.acercadelaeducacion.com.ar/2012/10/prueba-de-posteo-desde-orgmode-usando-org2blog-2/
categories:
  - Cultura Libre
  - Destacados
  - microblog
tags:
  - Software Libre
---

 Esta es una pruebita que estoy haciendo desde Org: Tu vida en texto plano como vengo usando mucho Emacs pensé que postear desde el editor sería interesante, además integré el editor de texto con el Firefox, de manera que pueda capturar enlaces rápidamente. Si anda, en el próximo post les explico como hacerlo.


text:
import * as ko from "knockout";
import { find, max, sortBy } from "lodash";
import * as React from "react";

import _ = require("lodash");
import { CombatStats } from "../../common/CombatStats";
import { CombatantState } from "../../common/CombatantState";
import { EncounterState } from "../../common/EncounterState";
import { PersistentCharacter } from "../../common/PersistentCharacter";
import { PlayerViewCombatantState } from "../../common/PlayerViewCombatantState";
import { StatBlock } from "../../common/StatBlock";
import { probablyUniqueString } from "../../common/Toolbox";
import { Combatant } from "../Combatant/Combatant";
import {
  GetOrRollMaximumHP,
  VariantMaximumHP
} from "../Combatant/GetOrRollMaximumHP";
import { ToPlayerViewCombatantState } from "../Combatant/ToPlayerViewCombatantState";
import { env } from "../Environment";
import { PlayerViewClient } from "../PlayerView/PlayerViewClient";
import { IRules } from "../Rules/Rules";
import { CurrentSettings } from "../Settings/Settings";
import { LegacySynchronousLocalStore } from "../Utility/LegacySynchronousLocalStore";
import {
  DifficultyCalculator,
  EncounterDifficulty
} from "../Widgets/DifficultyCalculator";
import { EncounterFlow } from "./EncounterFlow";
import { UpdatePersistentCharacter } from "../Library/Libraries";
import { Library } from "../Library/useLibrary";
import axios from "axios";

export class Encounter {
  public TemporaryBackgroundImageUrl = ko.observable<string>(null);

  private lastVisibleActiveCombatantId: string | null = null;

  constructor(
    private playerViewClient: PlayerViewClient,
    private promptEditCombatantInitiative: (combatantId: string) => void,
    public Rules: IRules
  ) {
    this.Difficulty = ko.pureComputed(() => {
      const enemyChallengeRatings = this.combatants()
        .filter(c => !c.IsPlayerCharacter())
        .filter(c => c.StatBlock().Challenge)
        .map(c => c.StatBlock().Challenge.toString());
      const playerLevels = this.combatants()
        .filter(c => c.IsPlayerCharacter())
        .filter(c => c.StatBlock().Challenge)
        .map(c => c.StatBlock().Challenge.toString());
      return DifficultyCalculator.Calculate(
        enemyChallengeRatings,
        playerLevels
      );
    });

    this.GetPlayerView.subscribe(newPlayerView => {
      if (!this.playerViewClient) {
        return;
      }
      this.playerViewClient.UpdateEncounter(env.EncounterId, newPlayerView);
    });
  }

  private combatants = ko.observableArray<Combatant>([]);
  public Combatants = ko.pureComputed(() => this.combatants());
  public CombatantCountsByName: KnockoutObservable<{
    [name: string]: number;
  }> = ko.observable({});
  public ActiveCombatantStatBlock: KnockoutComputed<React.ReactElement<any>>;
  public Difficulty: ko.PureComputed<EncounterDifficulty>;

  public EncounterFlow = new EncounterFlow(this);

  private getGroupBonusForCombatant(combatant: Combatant) {
    if (combatant.InitiativeGroup() == null) {
      return combatant.InitiativeBonus();
    }

    const groupBonuses = this.combatants()
      .filter(c => c.InitiativeGroup() == combatant.InitiativeGroup())
      .map(c => c.InitiativeBonus());

    return max(groupBonuses) || combatant.InitiativeBonus();
  }

  private getCombatantSortIteratees(
    stable: boolean
  ): ((c: Combatant) => number | string)[] {
    if (stable) {
      return [c => -c.Initiative()];
    } else {
      return [
        c => -c.Initiative(),
        c => -this.getGroupBonusForCombatant(c),
        c => -c.InitiativeBonus(),
        c => (c.IsPlayerCharacter() ? 0 : 1),
        c => c.InitiativeGroup(),
        c => c.StatBlock().Name,
        c => c.IndexLabel()
      ];
    }
  }

  public SortByInitiative = (stable = false) => {
    const sortedCombatants = sortBy(
      this.combatants(),
      this.getCombatantSortIteratees(stable)
    );
    this.combatants(sortedCombatants);
  };

  public ImportEncounter = encounter => {
    const deepMerge = (a, b) => _.extend(true, {}, a, b);
    const defaultAdd = c => {
      if (c.TotalInitiativeModifier !== undefined) {
        c.InitiativeModifier = c.TotalInitiativeModifier;
      }
      this.AddCombatantFromStatBlock(deepMerge(StatBlock.Default(), c));
    };
    if (encounter.Combatants) {
      encounter.Combatants.forEach(c => {
        if (c.Player == "npc") {
          c.Player = "";
        }

        if (c.Id) {
          axios
            .get(`/statblocks/${c.Id}`)
            .then(r => r.data)
            .then(statBlockFromLibrary => {
              const modifiedStatBlockFromLibrary = deepMerge(
                statBlockFromLibrary,
                c
              );
              this.AddCombatantFromStatBlock(modifiedStatBlockFromLibrary);
            })
            .catch(_ => defaultAdd(c));
        } else {
          defaultAdd(c);
        }
      });
    }
  };

  public AddCombatantFromState = (combatantState: CombatantState) => {
    if (this.combatants().some(c => c.Id == combatantState.Id)) {
      combatantState.Id = probablyUniqueString();
    }

    const combatant = new Combatant(combatantState, this);
    this.combatants.push(combatant);

    combatant.UpdateIndexLabel();

    if (this.EncounterFlow.State() === "active") {
      this.promptEditCombatantInitiative(combatant.Id);
    }

    combatant.Tags().forEach(tag => {
      if (tag.HasDuration) {
        this.EncounterFlow.AddDurationTag(tag);
      }
    });

    return combatant;
  };

  public AddCombatantFromStatBlock = (
    statBlockJson: {},
    hideOnAdd = false,
    variantMaximumHP: VariantMaximumHP = VariantMaximumHP.DEFAULT
  ) => {
    const statBlock: StatBlock = { ...StatBlock.Default(), ...statBlockJson };
    statBlock.HP = {
      ...statBlock.HP,
      Value: GetOrRollMaximumHP(statBlock, variantMaximumHP)
    };

    const initialState: CombatantState = {
      Id: probablyUniqueString(),
      StatBlock: statBlock,
      Alias: "",
      IndexLabel: null,
      CurrentHP: statBlock.HP.Value,
      CurrentNotes: this.AutoPopulatedNotes(statBlock),
      TemporaryHP: 0,
      Hidden: hideOnAdd,
      RevealedAC: false,
      Initiative: 0,
      Tags: [],
      RoundCounter: 0,
      ElapsedSeconds: 0,
      InterfaceVersion: process.env.VERSION || "unknown"
    };

    const combatant = this.AddCombatantFromState(initialState);

    return combatant;
  };

  public CanAddCombatant = (persistentCharacterId: string) => {
    return !this.combatants().some(
      c => c.PersistentCharacterId == persistentCharacterId
    );
  };

  public AddCombatantFromPersistentCharacter(
    persistentCharacter: PersistentCharacter,
    updatePersistentCharacter: UpdatePersistentCharacter,
    hideOnAdd = false
  ): Combatant | null {
    if (!this.CanAddCombatant(persistentCharacter.Id)) {
      return null;
    }

    const initialState: CombatantState = {
      Id: probablyUniqueString(),
      PersistentCharacterId: persistentCharacter.Id,
      StatBlock: persistentCharacter.StatBlock,
      Alias: "",
      IndexLabel: null,
      CurrentHP: persistentCharacter.CurrentHP,
      CurrentNotes: persistentCharacter.Notes,
      TemporaryHP: 0,
      Hidden: hideOnAdd,
      RevealedAC: false,
      Initiative: 0,
      Tags: [],
      RoundCounter: 0,
      ElapsedSeconds: 0,
      InterfaceVersion: persistentCharacter.Version
    };

    const combatant = this.AddCombatantFromState(initialState);

    combatant.AttachToPersistentCharacterLibrary(updatePersistentCharacter);

    return combatant;
  }

  public RemoveCombatant = (combatant: Combatant) => {
    this.combatants.remove(combatant);

    const removedCombatantName = combatant.StatBlock().Name;
    const remainingCombatants = this.combatants();

    const allMyFriendsAreGone = remainingCombatants.every(
      c => c.StatBlock().Name != removedCombatantName
    );

    if (allMyFriendsAreGone) {
      const combatantCountsByName = this.CombatantCountsByName();
      delete combatantCountsByName[removedCombatantName];
      this.CombatantCountsByName(combatantCountsByName);
    }

    if (this.combatants().length == 0) {
      this.EncounterFlow.EndEncounter();
    }
  };

  public UpdatePersistentCharacterStatBlock(
    persistentCharacterId: string,
    newStatBlock: StatBlock
  ) {
    const combatant = find(
      this.combatants(),
      c => c.PersistentCharacterId == persistentCharacterId
    );
    if (!combatant) {
      return;
    }
    combatant.StatBlock(newStatBlock);
  }

  public MoveCombatant(combatant: Combatant, index: number) {
    combatant.InitiativeGroup(null);
    this.CleanInitiativeGroups();
    const currentPosition = this.combatants().indexOf(combatant);
    const passedCombatant = this.combatants()[index];
    const initiative = combatant.Initiative();
    let newInitiative = initiative;
    if (
      index > currentPosition &&
      passedCombatant &&
      passedCombatant.Initiative() < initiative
    ) {
      newInitiative = passedCombatant.Initiative();
    }
    if (
      index < currentPosition &&
      passedCombatant &&
      passedCombatant.Initiative() > initiative
    ) {
      newInitiative = passedCombatant.Initiative();
    }

    this.combatants.remove(combatant);
    this.combatants.splice(index, 0, combatant);
    combatant.Initiative(newInitiative);
    return newInitiative;
  }

  public CleanInitiativeGroups() {
    const combatants = this.combatants();
    combatants.forEach(combatant => {
      const group = combatant.InitiativeGroup();
      if (
        group &&
        combatants.filter(c => c.InitiativeGroup() === group).length < 2
      ) {
        combatant.InitiativeGroup(null);
      }
    });
  }

  public StartEncounterAutosaves = () => {
    this.ObservableEncounterState.subscribe(_ => {
      //Short circuit this observable so we don't save when seconds update
      const newState = this.FullEncounterState();

      LegacySynchronousLocalStore.Save<EncounterState<CombatantState>>(
        LegacySynchronousLocalStore.AutoSavedEncounters,
        LegacySynchronousLocalStore.DefaultSavedEncounterId,
        newState
      );
    });
  };

  public ObservableEncounterState = ko.computed(
    (): EncounterState<CombatantState> => {
      const activeCombatant = this.EncounterFlow.ActiveCombatant();

      return {
        ActiveCombatantId: activeCombatant ? activeCombatant.Id : null,
        RoundCounter: this.EncounterFlow.CombatTimer.ElapsedRounds(),
        //ElapsedSeconds: omitted to avoid repeated re-renders,
        Combatants: this.combatants().map<CombatantState>(c => c.GetState()),
        BackgroundImageUrl: this.TemporaryBackgroundImageUrl()
      };
    }
  );

  public FullEncounterState = ko.computed(
    (): EncounterState<CombatantState> => {
      return {
        ...this.ObservableEncounterState(),
        ElapsedSeconds: this.EncounterFlow.TurnTimer.ElapsedSeconds(),
        Combatants: this.combatants().map<CombatantState>(c => {
          const combatantState = c.GetState();
          combatantState.ElapsedSeconds = c.CombatTimer.ElapsedSeconds();
          return combatantState;
        })
      };
    }
  );

  public GetPlayerView = ko.computed(
    (): EncounterState<PlayerViewCombatantState> => {
      const activeCombatantId = this.getPlayerViewActiveCombatantId();
      const defaultBackgroundUrl = CurrentSettings().PlayerView.CustomStyles
        .backgroundUrl;
      return {
        ActiveCombatantId: activeCombatantId,
        RoundCounter: this.EncounterFlow.CombatTimer.ElapsedRounds(),
        Combatants: this.getCombatantsForPlayerView(activeCombatantId),
        BackgroundImageUrl:
          this.TemporaryBackgroundImageUrl() || defaultBackgroundUrl
      };
    }
  );

  public LoadEncounterState = (
    encounterState: EncounterState<CombatantState>,
    updatePersistentCharacter: UpdatePersistentCharacter,
    persistentCharacterLibrary: Library<PersistentCharacter>
  ) => {
    const combatantsInLabelOrder = _.sortBy(
      encounterState.Combatants,
      c => c.IndexLabel
    );
    combatantsInLabelOrder.forEach(async savedCombatant => {
      const combatant = this.AddCombatantFromState(savedCombatant);

      if (combatant.PersistentCharacterId !== null) {
        const fallback = PersistentCharacter.Initialize(combatant.StatBlock());
        const persistentCharacterListing = await persistentCharacterLibrary.GetOrCreateListingById(
          combatant.PersistentCharacterId,
          fallback
        );
        const persistentCharacter = await persistentCharacterListing.GetWithTemplate(
          fallback
        );

        combatant.StatBlock(persistentCharacter.StatBlock);
        combatant.CurrentHP(persistentCharacter.CurrentHP);
        combatant.CurrentNotes(persistentCharacter.Notes);
        combatant.AttachToPersistentCharacterLibrary(updatePersistentCharacter);
      }
    });

    const activeCombatant = _.find(
      this.combatants(),
      c => c.Id == encounterState.ActiveCombatantId
    );

    if (activeCombatant !== undefined) {
      this.EncounterFlow.State("active");
      this.EncounterFlow.ActiveCombatant(activeCombatant);
      this.EncounterFlow.ActiveCombatant().CombatTimer.Start();
      this.EncounterFlow.TurnTimer.Start();
      this.EncounterFlow.CombatTimer.Start();
      this.SortByInitiative();
    }

    this.EncounterFlow.CombatTimer.SetElapsedRounds(
      encounterState.RoundCounter || 1
    );
    this.EncounterFlow.CombatTimer.SetElapsedSeconds(
      encounterState.ElapsedSeconds || 0
    );
    this.TemporaryBackgroundImageUrl(encounterState.BackgroundImageUrl || null);
  };

  public ClearEncounter = () => {
    this.combatants([]);
    this.CombatantCountsByName({});
    this.EncounterFlow.EndEncounter();
  };

  private getPlayerViewActiveCombatantId() {
    const activeCombatant = this.EncounterFlow.ActiveCombatant();
    if (!activeCombatant) {
      this.lastVisibleActiveCombatantId = null;
      return this.lastVisibleActiveCombatantId;
    }

    if (activeCombatant.Hidden()) {
      return this.lastVisibleActiveCombatantId;
    }

    this.lastVisibleActiveCombatantId = activeCombatant.Id;

    return this.lastVisibleActiveCombatantId;
  }

  private getCombatantsForPlayerView(activeCombatantId: string | null) {
    const hideMonstersOutsideEncounter = CurrentSettings().PlayerView
      .HideMonstersOutsideEncounter;

    const combatants = this.combatants().slice();

    const activeCombatantOnTop = CurrentSettings().PlayerView
      .ActiveCombatantOnTop;
    if (activeCombatantOnTop && activeCombatantId && combatants.length > 0) {
      let combatantsMoved = 0;
      while (
        combatants[0].Id != activeCombatantId &&
        combatantsMoved < combatants.length //prevent infinite loop in case we can't find active combatant
      ) {
        combatants.push(combatants.shift() as Combatant);
        combatantsMoved++;
      }
    }

    const visibleCombatants = combatants.filter(c => {
      if (c.Hidden()) {
        return false;
      }
      if (
        hideMonstersOutsideEncounter &&
        this.EncounterFlow.State() == "inactive" &&
        !c.IsPlayerCharacter()
      ) {
        return false;
      }
      return true;
    });

    return visibleCombatants.map<PlayerViewCombatantState>(c =>
      ToPlayerViewCombatantState(c)
    );
  }

  public DisplayPlayerViewCombatStats(stats: CombatStats) {
    this.playerViewClient.DisplayCombatStats(env.EncounterId, stats);
  }

  private AutoPopulatedNotes(statBlock: StatBlock) {
    const notes = [];
    let match = [];

    const spellcasting = statBlock.Traits.find(t => t.Name === "Spellcasting");
    if (spellcasting) {
      notes.push("Spellcasting Slots");
      const content = spellcasting.Content;

      const spellPattern = /([1-9])(st|nd|rd|th) level \(([1-9])/gm;
      while ((match = spellPattern.exec(content))) {
        notes.push(`${match[1]}${match[2]} Level [${match[3]}/${match[3]}]`);
      }
    }

    const innateSpellcasting = statBlock.Traits.find(
      t => t.Name === "Innate Spellcasting"
    );

    if (innateSpellcasting) {
      notes.push("Innate Spellcasting Slots");

      const content = innateSpellcasting.Content;

      const innatePattern = /(\d)\/day/gim;
      while ((match = innatePattern.exec(content))) {
        notes.push(`[${match[1]}/${match[1]}]`);
      }
    }

    if (statBlock.LegendaryActions.length > 0) {
      notes.push("Legendary Actions [3/3]");
    }

    const perDayPattern = /\((\d)\/day\)/gim;

    statBlock.Traits.filter(t => t.Name.match(perDayPattern)).forEach(t =>
      notes.push(`${t.Name.replace(perDayPattern, "[$1/$1]")}`)
    );

    perDayPattern.lastIndex = 0;

    statBlock.Actions.filter(t => t.Name.match(perDayPattern)).forEach(t =>
      notes.push(`${t.Name.replace(perDayPattern, "[$1/$1]")}`)
    );

    statBlock.Traits.filter(t => t.Name.includes("(Recharge")).forEach(t =>
      notes.push(`${t.Name.replace(/\(.*?\)/, "")}[1/1]`)
    );
    statBlock.Actions.filter(t => t.Name.includes("(Recharge")).forEach(t =>
      notes.push(`${t.Name.replace(/\(.*?\)/, "")}[1/1]`)
    );

    return notes.join("\n\n");
  }
}


text:
package ${packageName};

import org.astivetoolkit.agi.AgiException;
import org.astivetoolkit.astivlet.Astivlet;
import org.astivetoolkit.astivlet.AstivletRequest;
import org.astivetoolkit.astivlet.AstivletResponse;

public class App extends Astivlet {

    public void service(AstivletRequest request, AstivletResponse response) {
        try {
            response.answer();
            response.streamFile("tt-monkeys");
            response.hangup();
        } catch (AgiException ex) {
            // Do something intersting here !
        }
    }
}


text:
layout: page
title: Donald Palmer's 73rd Birthday
date: 2016-05-24
author: Johnny Wolfe
tags: weekly links, java
status: published
summary: Curabitur ac est eget erat cursus suscipit. Vestibulum finibus bibendum.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 03/28/2016
  endDate: 03/29/2016
  ctyhocn: WBUGBHX
  groupCode: DP7B
published: true
---
Aliquam viverra turpis tortor, eu egestas quam fermentum et. Duis lacinia diam sodales elit cursus, vitae ultricies ligula aliquam. Vivamus elementum ex non tempus blandit. Aliquam suscipit non dolor a interdum. Nam lobortis lorem vel nisl facilisis, eu dictum lorem efficitur. Aenean massa metus, mattis nec efficitur vel, porttitor et enim. Etiam finibus, orci at laoreet vulputate, justo felis faucibus turpis, id varius risus arcu nec nisi.

1 Cras et eros in dolor tempus rhoncus
1 Vestibulum pretium mi vitae consectetur lobortis
1 Aliquam commodo tellus sed sem molestie consequat.

Cras pretium, erat sit amet porta ultrices, ante enim consequat quam, non dapibus lacus massa nec magna. Phasellus tincidunt leo sit amet bibendum rutrum. Pellentesque dictum leo vitae nisi consectetur, eu rutrum turpis laoreet. Praesent rutrum augue at fermentum mattis. Duis condimentum scelerisque sapien, sed fermentum ex rhoncus sed. In congue vehicula ex, sit amet sodales sem lobortis id. Morbi vel condimentum odio, bibendum sagittis tortor. Phasellus id placerat eros, ut posuere sem. Vivamus facilisis eu massa sit amet volutpat. Curabitur suscipit bibendum nunc, eu lobortis turpis egestas pulvinar. Integer porta vestibulum ipsum a volutpat. Etiam erat eros, tincidunt aliquet ultricies non, porta eget libero. Etiam ultricies sem sit amet rutrum bibendum.
Vestibulum vitae nisl at nibh rutrum rhoncus eu eu ipsum. Duis eleifend eros et facilisis placerat. Sed quis dapibus nisi, eget aliquet sapien. Aenean malesuada turpis ut sodales convallis. Morbi semper eget ante sed bibendum. Cras ac semper ipsum. Ut pellentesque vulputate felis a rhoncus. Donec tristique augue non tristique placerat. Sed ullamcorper, eros sit amet efficitur mattis, felis urna posuere sem, a tincidunt arcu est id ligula. Etiam id lacus urna. Maecenas pharetra blandit aliquam. Vivamus rhoncus ante nibh, ut viverra turpis ultricies non.