text:
/*
 * @test
 * @bug 8010122 8004518 8024331 8024688
 * @summary Test Map default methods
 * @author Mike Duigou
 * @run testng Defaults
 */
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.function.BiFunction;
import java.util.function.Supplier;

import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
import static org.testng.Assert.fail;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertSame;

public class Defaults {

    @Test(dataProvider = "Map<IntegerEnum,String> rw=all keys=withNull values=withNull")
    public void testGetOrDefaultNulls(String description, Map<IntegerEnum, String> map) {
        assertTrue(map.containsKey(null), description + ": null key absent");
        assertNull(map.get(null), description + ": value not null");
        assertSame(map.get(null), map.getOrDefault(null, EXTRA_VALUE), description + ": values should match");
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=all keys=all values=all")
    public void testGetOrDefault(String description, Map<IntegerEnum, String> map) {
        assertTrue(map.containsKey(KEYS[1]), "expected key missing");
        assertSame(map.get(KEYS[1]), map.getOrDefault(KEYS[1], EXTRA_VALUE), "values should match");
        assertFalse(map.containsKey(EXTRA_KEY), "expected absent key");
        assertSame(map.getOrDefault(EXTRA_KEY, EXTRA_VALUE), EXTRA_VALUE, "value not returned as default");
        assertNull(map.getOrDefault(EXTRA_KEY, null), "null not returned as default");
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull")
    public void testPutIfAbsentNulls(String description, Map<IntegerEnum, String> map) {
        // null -> null
        assertTrue(map.containsKey(null), "null key absent");
        assertNull(map.get(null), "value not null");
        assertNull(map.putIfAbsent(null, EXTRA_VALUE), "previous not null");
        // null -> EXTRA_VALUE
        assertTrue(map.containsKey(null), "null key absent");
        assertSame(map.get(null), EXTRA_VALUE, "unexpected value");
        assertSame(map.putIfAbsent(null, null), EXTRA_VALUE, "previous not expected value");
        assertTrue(map.containsKey(null), "null key absent");
        assertSame(map.get(null), EXTRA_VALUE, "unexpected value");
        assertSame(map.remove(null), EXTRA_VALUE, "removed unexpected value");
        // null -> <absent>

        assertFalse(map.containsKey(null), description + ": key present after remove");
        assertNull(map.putIfAbsent(null, null), "previous not null");
        // null -> null
        assertTrue(map.containsKey(null), "null key absent");
        assertNull(map.get(null), "value not null");
        assertNull(map.putIfAbsent(null, EXTRA_VALUE), "previous not null");
        assertSame(map.get(null), EXTRA_VALUE, "value not expected");
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")
    public void testPutIfAbsent(String description, Map<IntegerEnum, String> map) {
        // 1 -> 1
        assertTrue(map.containsKey(KEYS[1]));
        Object expected = map.get(KEYS[1]);
        assertTrue(null == expected || expected == VALUES[1]);
        assertSame(map.putIfAbsent(KEYS[1], EXTRA_VALUE), expected);
        assertSame(map.get(KEYS[1]), expected);

        // EXTRA_KEY -> <absent>
        assertFalse(map.containsKey(EXTRA_KEY));
        assertSame(map.putIfAbsent(EXTRA_KEY, EXTRA_VALUE), null);
        assertSame(map.get(EXTRA_KEY), EXTRA_VALUE);
        assertSame(map.putIfAbsent(EXTRA_KEY, VALUES[2]), EXTRA_VALUE);
        assertSame(map.get(EXTRA_KEY), EXTRA_VALUE);
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=all keys=all values=all")
    public void testForEach(String description, Map<IntegerEnum, String> map) {
        IntegerEnum[] EACH_KEY = new IntegerEnum[map.size()];

        map.forEach((k, v) -> {
            int idx = (null == k) ? 0 : k.ordinal(); // substitute for index.
            assertNull(EACH_KEY[idx]);
            EACH_KEY[idx] = (idx == 0) ? KEYS[0] : k; // substitute for comparison.
            assertSame(v, map.get(k));
        });

        assertEquals(KEYS, EACH_KEY, description);
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")
    public static void testReplaceAll(String description, Map<IntegerEnum, String> map) {
        IntegerEnum[] EACH_KEY = new IntegerEnum[map.size()];
        Set<String> EACH_REPLACE = new HashSet<>(map.size());

        map.replaceAll((k,v) -> {
            int idx = (null == k) ? 0 : k.ordinal(); // substitute for index.
            assertNull(EACH_KEY[idx]);
            EACH_KEY[idx] = (idx == 0) ? KEYS[0] : k; // substitute for comparison.
            assertSame(v, map.get(k));
            String replacement = v + " replaced";
            EACH_REPLACE.add(replacement);
            return replacement;
        });

        assertEquals(KEYS, EACH_KEY, description);
        assertEquals(map.values().size(), EACH_REPLACE.size(), description + EACH_REPLACE);
        assertTrue(EACH_REPLACE.containsAll(map.values()), description + " : " + EACH_REPLACE + " != " + map.values());
        assertTrue(map.values().containsAll(EACH_REPLACE), description + " : " + EACH_REPLACE + " != " + map.values());
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=nonNull values=nonNull")
    public static void testReplaceAllNoNullReplacement(String description, Map<IntegerEnum, String> map) {
        assertThrows(
            () -> { map.replaceAll(null); },
            NullPointerException.class,
            description);
        assertThrows(
            () -> { map.replaceAll((k,v) -> null); },
            NullPointerException.class,
            description + " should not allow replacement with null value");
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull")
    public static void testRemoveNulls(String description, Map<IntegerEnum, String> map) {
        assertTrue(map.containsKey(null), "null key absent");
        assertNull(map.get(null), "value not null");
        assertFalse(map.remove(null, EXTRA_VALUE), description);
        assertTrue(map.containsKey(null));
        assertNull(map.get(null));
        assertTrue(map.remove(null, null));
        assertFalse(map.containsKey(null));
        assertNull(map.get(null));
        assertFalse(map.remove(null, null));
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")
    public static void testRemove(String description, Map<IntegerEnum, String> map) {
        assertTrue(map.containsKey(KEYS[1]));
        Object expected = map.get(KEYS[1]);
        assertTrue(null == expected || expected == VALUES[1]);
        assertFalse(map.remove(KEYS[1], EXTRA_VALUE), description);
        assertSame(map.get(KEYS[1]), expected);
        assertTrue(map.remove(KEYS[1], expected));
        assertNull(map.get(KEYS[1]));
        assertFalse(map.remove(KEYS[1], expected));

        assertFalse(map.containsKey(EXTRA_KEY));
        assertFalse(map.remove(EXTRA_KEY, EXTRA_VALUE));
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull")
    public void testReplaceKVNulls(String description, Map<IntegerEnum, String> map) {
        assertTrue(map.containsKey(null), "null key absent");
        assertNull(map.get(null), "value not null");
        assertSame(map.replace(null, EXTRA_VALUE), null);
        assertSame(map.get(null), EXTRA_VALUE);
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=nonNull values=nonNull")
    public void testReplaceKVNoNulls(String description, Map<IntegerEnum, String> map) {
        assertTrue(map.containsKey(FIRST_KEY), "expected key missing");
        assertSame(map.get(FIRST_KEY), FIRST_VALUE, "found wrong value");
        assertThrows( () -> {map.replace(FIRST_KEY, null);}, NullPointerException.class, description + ": should throw NPE");
        assertSame(map.replace(FIRST_KEY, EXTRA_VALUE), FIRST_VALUE, description + ": replaced wrong value");
        assertSame(map.get(FIRST_KEY), EXTRA_VALUE, "found wrong value");
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")
    public void testReplaceKV(String description, Map<IntegerEnum, String> map) {
        assertTrue(map.containsKey(KEYS[1]));
        Object expected = map.get(KEYS[1]);
        assertTrue(null == expected || expected == VALUES[1]);
        assertSame(map.replace(KEYS[1], EXTRA_VALUE), expected);
        assertSame(map.get(KEYS[1]), EXTRA_VALUE);

        assertFalse(map.containsKey(EXTRA_KEY));
        assertNull(map.replace(EXTRA_KEY, EXTRA_VALUE));
        assertFalse(map.containsKey(EXTRA_KEY));
        assertNull(map.get(EXTRA_KEY));
        assertNull(map.put(EXTRA_KEY, EXTRA_VALUE));
        assertSame(map.get(EXTRA_KEY), EXTRA_VALUE);
        assertSame(map.replace(EXTRA_KEY, (String)expected), EXTRA_VALUE);
        assertSame(map.get(EXTRA_KEY), expected);
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull")
    public void testReplaceKVVNulls(String description, Map<IntegerEnum, String> map) {
        assertTrue(map.containsKey(null), "null key absent");
        assertNull(map.get(null), "value not null");
        assertFalse(map.replace(null, EXTRA_VALUE, EXTRA_VALUE));
        assertNull(map.get(null));
        assertTrue(map.replace(null, null, EXTRA_VALUE));
        assertSame(map.get(null), EXTRA_VALUE);
        assertTrue(map.replace(null, EXTRA_VALUE, EXTRA_VALUE));
        assertSame(map.get(null), EXTRA_VALUE);
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=nonNull values=nonNull")
    public void testReplaceKVVNoNulls(String description, Map<IntegerEnum, String> map) {
        assertTrue(map.containsKey(FIRST_KEY), "expected key missing");
        assertSame(map.get(FIRST_KEY), FIRST_VALUE, "found wrong value");
        assertThrows( () -> {map.replace(FIRST_KEY, FIRST_VALUE, null);}, NullPointerException.class, description + ": should throw NPE");
        assertThrows( () -> {if (!map.replace(FIRST_KEY, null, EXTRA_VALUE)) throw new NullPointerException("default returns false rather than throwing");}, NullPointerException.class,  description + ": should throw NPE");
        assertTrue(map.replace(FIRST_KEY, FIRST_VALUE, EXTRA_VALUE), description + ": replaced wrong value");
        assertSame(map.get(FIRST_KEY), EXTRA_VALUE, "found wrong value");
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")
    public void testReplaceKVV(String description, Map<IntegerEnum, String> map) {
        assertTrue(map.containsKey(KEYS[1]));
        Object expected = map.get(KEYS[1]);
        assertTrue(null == expected || expected == VALUES[1]);
        assertFalse(map.replace(KEYS[1], EXTRA_VALUE, EXTRA_VALUE));
        assertSame(map.get(KEYS[1]), expected);
        assertTrue(map.replace(KEYS[1], (String)expected, EXTRA_VALUE));
        assertSame(map.get(KEYS[1]), EXTRA_VALUE);
        assertTrue(map.replace(KEYS[1], EXTRA_VALUE, EXTRA_VALUE));
        assertSame(map.get(KEYS[1]), EXTRA_VALUE);

        assertFalse(map.containsKey(EXTRA_KEY));
        assertFalse(map.replace(EXTRA_KEY, EXTRA_VALUE, EXTRA_VALUE));
        assertFalse(map.containsKey(EXTRA_KEY));
        assertNull(map.get(EXTRA_KEY));
        assertNull(map.put(EXTRA_KEY, EXTRA_VALUE));
        assertTrue(map.containsKey(EXTRA_KEY));
        assertSame(map.get(EXTRA_KEY), EXTRA_VALUE);
        assertTrue(map.replace(EXTRA_KEY, EXTRA_VALUE, EXTRA_VALUE));
        assertSame(map.get(EXTRA_KEY), EXTRA_VALUE);
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull")
    public void testComputeIfAbsentNulls(String description, Map<IntegerEnum, String> map) {
        // null -> null
        assertTrue(map.containsKey(null), "null key absent");
        assertNull(map.get(null), "value not null");
        assertSame(map.computeIfAbsent(null, (k) -> null), null,  "not expected result");
        assertTrue(map.containsKey(null), "null key absent");
        assertNull(map.get(null), "value not null");
        assertSame(map.computeIfAbsent(null, (k) -> EXTRA_VALUE), EXTRA_VALUE, "not mapped to result");
        // null -> EXTRA_VALUE
        assertTrue(map.containsKey(null), "null key absent");
        assertSame(map.get(null), EXTRA_VALUE,  "not expected value");
        assertSame(map.remove(null), EXTRA_VALUE, "removed unexpected value");
        // null -> <absent>
        assertFalse(map.containsKey(null), "null key present");
        assertSame(map.computeIfAbsent(null, (k) -> EXTRA_VALUE), EXTRA_VALUE, "not mapped to result");
        // null -> EXTRA_VALUE
        assertTrue(map.containsKey(null), "null key absent");
        assertSame(map.get(null), EXTRA_VALUE,  "not expected value");
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")
    public void testComputeIfAbsent(String description, Map<IntegerEnum, String> map) {
        // 1 -> 1
        assertTrue(map.containsKey(KEYS[1]));
        Object expected = map.get(KEYS[1]);
        assertTrue(null == expected || expected == VALUES[1], description + String.valueOf(expected));
        expected = (null == expected) ? EXTRA_VALUE : expected;
        assertSame(map.computeIfAbsent(KEYS[1], (k) -> EXTRA_VALUE), expected, description);
        assertSame(map.get(KEYS[1]), expected, description);

        // EXTRA_KEY -> <absent>
        assertFalse(map.containsKey(EXTRA_KEY));
        assertNull(map.computeIfAbsent(EXTRA_KEY, (k) -> null));
        assertFalse(map.containsKey(EXTRA_KEY));
        assertSame(map.computeIfAbsent(EXTRA_KEY, (k) -> EXTRA_VALUE), EXTRA_VALUE);
        // EXTRA_KEY -> EXTRA_VALUE
        assertSame(map.get(EXTRA_KEY), EXTRA_VALUE);
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")
    public void testComputeIfAbsentNullFunction(String description, Map<IntegerEnum, String> map) {
        assertThrows( () -> { map.computeIfAbsent(KEYS[1], null);},
                NullPointerException.class,
                "Should throw NPE");
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull")
    public void testComputeIfPresentNulls(String description, Map<IntegerEnum, String> map) {
        assertTrue(map.containsKey(null), description + ": null key absent");
        assertNull(map.get(null), description + ": value not null");
        assertSame(map.computeIfPresent(null, (k, v) -> {
            fail(description + ": null value is not deemed present");
            return EXTRA_VALUE;
        }), null, description);
        assertTrue(map.containsKey(null));
        assertNull(map.get(null), description);
        assertNull(map.remove(EXTRA_KEY), description + ": unexpected mapping");
        assertNull(map.put(EXTRA_KEY, null), description + ": unexpected value");
        assertSame(map.computeIfPresent(EXTRA_KEY, (k, v) -> {
            fail(description + ": null value is not deemed present");
            return EXTRA_VALUE;
        }), null, description);
        assertNull(map.get(EXTRA_KEY), description + ": null mapping gone");
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")
    public void testComputeIfPresent(String description, Map<IntegerEnum, String> map) {
        assertTrue(map.containsKey(KEYS[1]));
        Object value = map.get(KEYS[1]);
        assertTrue(null == value || value == VALUES[1], description + String.valueOf(value));
        Object expected = (null == value) ? null : EXTRA_VALUE;
        assertSame(map.computeIfPresent(KEYS[1], (k, v) -> {
            assertSame(v, value);
            return EXTRA_VALUE;
        }), expected, description);
        assertSame(map.get(KEYS[1]), expected, description);

        assertFalse(map.containsKey(EXTRA_KEY));
        assertSame(map.computeIfPresent(EXTRA_KEY, (k, v) -> {
            fail();
            return EXTRA_VALUE;
        }), null);
        assertFalse(map.containsKey(EXTRA_KEY));
        assertSame(map.get(EXTRA_KEY), null);
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")
    public void testComputeIfPresentNullFunction(String description, Map<IntegerEnum, String> map) {
        assertThrows( () -> { map.computeIfPresent(KEYS[1], null);},
                NullPointerException.class,
                "Should throw NPE");
    }

     @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull")
    public void testComputeNulls(String description, Map<IntegerEnum, String> map) {
        assertTrue(map.containsKey(null), "null key absent");
        assertNull(map.get(null), "value not null");
        assertSame(map.compute(null, (k, v) -> {
            assertNull(k);
            assertNull(v);
            return null;
        }), null, description);
        assertFalse(map.containsKey(null), description + ": null key present.");
        assertSame(map.compute(null, (k, v) -> {
            assertSame(k, null);
            assertNull(v);
            return EXTRA_VALUE;
        }), EXTRA_VALUE, description);
        assertTrue(map.containsKey(null));
        assertSame(map.get(null), EXTRA_VALUE, description);
        assertSame(map.remove(null), EXTRA_VALUE, description + ": removed value not expected");
        // no mapping before and after
        assertFalse(map.containsKey(null), description + ": null key present");
        assertSame(map.compute(null, (k, v) -> {
            assertNull(k);
            assertNull(v);
            return null;
        }), null, description + ": expected null result" );
        assertFalse(map.containsKey(null), description + ": null key present");
        // compute with map not containing value
        assertNull(map.remove(EXTRA_KEY),  description + ": unexpected mapping");
        assertFalse(map.containsKey(EXTRA_KEY),  description + ": key present");
        assertSame(map.compute(EXTRA_KEY, (k, v) -> {
            assertSame(k, EXTRA_KEY);
            assertNull(v);
            return null;
        }), null, description);
        assertFalse(map.containsKey(EXTRA_KEY),  description + ": null key present");
        // ensure removal.
        assertNull(map.put(EXTRA_KEY, EXTRA_VALUE));
        assertSame(map.compute(EXTRA_KEY, (k, v) -> {
            assertSame(k, EXTRA_KEY);
            assertSame(v, EXTRA_VALUE);
            return null;
        }), null, description + ": null resulted expected");
        assertFalse(map.containsKey(EXTRA_KEY),  description + ": null key present");
       // compute with map containing null value
        assertNull(map.put(EXTRA_KEY, null),  description + ": unexpected value");
        assertSame(map.compute(EXTRA_KEY, (k, v) -> {
            assertSame(k, EXTRA_KEY);
            assertNull(v);
            return null;
        }), null, description);
        assertFalse(map.containsKey(EXTRA_KEY),  description + ": null key present");
        assertNull(map.put(EXTRA_KEY, null),  description + ": unexpected value");
        assertSame(map.compute(EXTRA_KEY, (k, v) -> {
            assertSame(k, EXTRA_KEY);
            assertNull(v);
            return EXTRA_VALUE;
        }), EXTRA_VALUE, description);
        assertTrue(map.containsKey(EXTRA_KEY), "null key present");
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")
    public void testCompute(String description, Map<IntegerEnum, String> map) {
        assertTrue(map.containsKey(KEYS[1]));
        Object value = map.get(KEYS[1]);
        assertTrue(null == value || value == VALUES[1], description + String.valueOf(value));
        assertSame(map.compute(KEYS[1], (k, v) -> {
            assertSame(k, KEYS[1]);
            assertSame(v, value);
            return EXTRA_VALUE;
        }), EXTRA_VALUE, description);
        assertSame(map.get(KEYS[1]), EXTRA_VALUE, description);
        assertNull(map.compute(KEYS[1], (k, v) -> {
            assertSame(v, EXTRA_VALUE);
            return null;
        }), description);
        assertFalse(map.containsKey(KEYS[1]));

        assertFalse(map.containsKey(EXTRA_KEY));
        assertSame(map.compute(EXTRA_KEY, (k, v) -> {
            assertNull(v);
            return EXTRA_VALUE;
        }), EXTRA_VALUE);
        assertTrue(map.containsKey(EXTRA_KEY));
        assertSame(map.get(EXTRA_KEY), EXTRA_VALUE);
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")
    public void testComputeNullFunction(String description, Map<IntegerEnum, String> map) {
        assertThrows( () -> { map.compute(KEYS[1], null);},
                NullPointerException.class,
                "Should throw NPE");
    }

    @Test(dataProvider = "MergeCases")
    private void testMerge(String description, Map<IntegerEnum, String> map, Merging.Value oldValue, Merging.Value newValue, Merging.Merger merger, Merging.Value put, Merging.Value result) {
            // add and check initial conditions.
            switch(oldValue) {
                case ABSENT :
                    map.remove(EXTRA_KEY);
                    assertFalse(map.containsKey(EXTRA_KEY), "key not absent");
                    break;
                case NULL :
                    map.put(EXTRA_KEY, null);
                    assertTrue(map.containsKey(EXTRA_KEY), "key absent");
                    assertNull(map.get(EXTRA_KEY), "wrong value");
                    break;
                case OLDVALUE :
                    map.put(EXTRA_KEY, VALUES[1]);
                    assertTrue(map.containsKey(EXTRA_KEY), "key absent");
                    assertSame(map.get(EXTRA_KEY), VALUES[1], "wrong value");
                    break;
                default:
                    fail("unexpected old value");
            }

            String returned = map.merge(EXTRA_KEY,
                newValue == Merging.Value.NULL ? (String) null : VALUES[2],
                merger
                );

            // check result

            switch(result) {
                case NULL :
                    assertNull(returned, "wrong value");
                    break;
                case NEWVALUE :
                    assertSame(returned, VALUES[2], "wrong value");
                    break;
                case RESULT :
                    assertSame(returned, VALUES[3], "wrong value");
                    break;
                default:
                    fail("unexpected new value");
            }

            // check map
            switch(put) {
                case ABSENT :
                    assertFalse(map.containsKey(EXTRA_KEY), "key not absent");
                    break;
                case NULL :
                    assertTrue(map.containsKey(EXTRA_KEY), "key absent");
                    assertNull(map.get(EXTRA_KEY), "wrong value");
                    break;
                case NEWVALUE :
                    assertTrue(map.containsKey(EXTRA_KEY), "key absent");
                    assertSame(map.get(EXTRA_KEY), VALUES[2], "wrong value");
                    break;
                case RESULT :
                    assertTrue(map.containsKey(EXTRA_KEY), "key absent");
                    assertSame(map.get(EXTRA_KEY), VALUES[3], "wrong value");
                    break;
                default:
                    fail("unexpected new value");
            }
    }

    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")
    public void testMergeNullMerger(String description, Map<IntegerEnum, String> map) {
        assertThrows( () -> { map.merge(KEYS[1], VALUES[1], null);},
                NullPointerException.class,
                "Should throw NPE");
    }

    public enum IntegerEnum {

        e0, e1, e2, e3, e4, e5, e6, e7, e8, e9,
        e10, e11, e12, e13, e14, e15, e16, e17, e18, e19,
        e20, e21, e22, e23, e24, e25, e26, e27, e28, e29,
        e30, e31, e32, e33, e34, e35, e36, e37, e38, e39,
        e40, e41, e42, e43, e44, e45, e46, e47, e48, e49,
        e50, e51, e52, e53, e54, e55, e56, e57, e58, e59,
        e60, e61, e62, e63, e64, e65, e66, e67, e68, e69,
        e70, e71, e72, e73, e74, e75, e76, e77, e78, e79,
        e80, e81, e82, e83, e84, e85, e86, e87, e88, e89,
        e90, e91, e92, e93, e94, e95, e96, e97, e98, e99,
        EXTRA_KEY;
        public static final int SIZE = values().length;
    };
    private static final int TEST_SIZE = IntegerEnum.SIZE - 1;
    /**
     * Realized keys ensure that there is always a hard ref to all test objects.
     */
    private static final IntegerEnum[] KEYS = new IntegerEnum[TEST_SIZE];
    /**
     * Realized values ensure that there is always a hard ref to all test
     * objects.
     */
    private static final String[] VALUES = new String[TEST_SIZE];

    static {
        IntegerEnum[] keys = IntegerEnum.values();
        for (int each = 0; each < TEST_SIZE; each++) {
            KEYS[each] = keys[each];
            VALUES[each] = String.valueOf(each);
        }
    }

    private static final IntegerEnum FIRST_KEY = KEYS[0];
    private static final String FIRST_VALUE = VALUES[0];
    private static final IntegerEnum EXTRA_KEY = IntegerEnum.EXTRA_KEY;
    private static final String EXTRA_VALUE = String.valueOf(TEST_SIZE);

    @DataProvider(name = "Map<IntegerEnum,String> rw=all keys=all values=all", parallel = true)
    public static Iterator<Object[]> allMapProvider() {
        return makeAllMaps().iterator();
    }

    @DataProvider(name = "Map<IntegerEnum,String> rw=all keys=withNull values=withNull", parallel = true)
    public static Iterator<Object[]> allMapWithNullsProvider() {
        return makeAllMapsWithNulls().iterator();
    }

    @DataProvider(name = "Map<IntegerEnum,String> rw=true keys=nonNull values=nonNull", parallel = true)
    public static Iterator<Object[]> rwNonNullMapProvider() {
        return makeRWNoNullsMaps().iterator();
    }

    @DataProvider(name = "Map<IntegerEnum,String> rw=true keys=nonNull values=all", parallel = true)
    public static Iterator<Object[]> rwNonNullKeysMapProvider() {
        return makeRWMapsNoNulls().iterator();
    }

    @DataProvider(name = "Map<IntegerEnum,String> rw=true keys=all values=all", parallel = true)
    public static Iterator<Object[]> rwMapProvider() {
        return makeAllRWMaps().iterator();
    }

    @DataProvider(name = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull", parallel = true)
    public static Iterator<Object[]> rwNullsMapProvider() {
        return makeAllRWMapsWithNulls().iterator();
    }

    private static Collection<Object[]> makeAllRWMapsWithNulls() {
        Collection<Object[]> all = new ArrayList<>();

        all.addAll(makeRWMaps(true, true));

        return all;
    }

    private static Collection<Object[]> makeRWMapsNoNulls() {
        Collection<Object[]> all = new ArrayList<>();

        all.addAll(makeRWNoNullKeysMaps(false));
        all.addAll(makeRWNoNullsMaps());

        return all;
    }

    private static Collection<Object[]> makeAllROMaps() {
        Collection<Object[]> all = new ArrayList<>();

        all.addAll(makeROMaps(false));
        all.addAll(makeROMaps(true));

        return all;
    }

    private static Collection<Object[]> makeAllRWMaps() {
        Collection<Object[]> all = new ArrayList<>();

        all.addAll(makeRWNoNullsMaps());
        all.addAll(makeRWMaps(false,true));
        all.addAll(makeRWMaps(true,true));
        all.addAll(makeRWNoNullKeysMaps(true));
        return all;
    }

    private static Collection<Object[]> makeAllMaps() {
        Collection<Object[]> all = new ArrayList<>();

        all.addAll(makeAllROMaps());
        all.addAll(makeAllRWMaps());

        return all;
    }

    private static Collection<Object[]> makeAllMapsWithNulls() {
        Collection<Object[]> all = new ArrayList<>();

        all.addAll(makeROMaps(true));
        all.addAll(makeRWMaps(true,true));

        return all;
    }
    /**
     *
     * @param nullKeys include null keys
     * @param nullValues include null values
     * @return
     */
    private static Collection<Object[]> makeRWMaps(boolean nullKeys, boolean nullValues) {
        return Arrays.asList(
            new Object[]{"HashMap", makeMap(HashMap::new, nullKeys, nullValues)},
            new Object[]{"IdentityHashMap", makeMap(IdentityHashMap::new, nullKeys, nullValues)},
            new Object[]{"LinkedHashMap", makeMap(LinkedHashMap::new, nullKeys, nullValues)},
            new Object[]{"WeakHashMap", makeMap(WeakHashMap::new, nullKeys, nullValues)},
            new Object[]{"Collections.checkedMap(HashMap)", Collections.checkedMap(makeMap(HashMap::new, nullKeys, nullValues), IntegerEnum.class, String.class)},
            new Object[]{"Collections.synchronizedMap(HashMap)", Collections.synchronizedMap(makeMap(HashMap::new, nullKeys, nullValues))},
            new Object[]{"ExtendsAbstractMap", makeMap(ExtendsAbstractMap::new, nullKeys, nullValues)});
    }

    /**
     *
     * @param nulls include null values
     * @return
     */
    private static Collection<Object[]> makeRWNoNullKeysMaps(boolean nulls) {
        return Arrays.asList(
                // null key hostile
                new Object[]{"EnumMap", makeMap(() -> new EnumMap(IntegerEnum.class), false, nulls)},
                new Object[]{"TreeMap", makeMap(TreeMap::new, false, nulls)},
                new Object[]{"ExtendsAbstractMap(TreeMap)", makeMap(() -> {return new ExtendsAbstractMap(new TreeMap());}, false, nulls)},
                new Object[]{"Collections.synchronizedMap(EnumMap)", Collections.synchronizedMap(makeMap(() -> new EnumMap(IntegerEnum.class), false, nulls))}
                );
    }

    private static Collection<Object[]> makeRWNoNullsMaps() {
        return Arrays.asList(
            // null key and value hostile
            new Object[]{"Hashtable", makeMap(Hashtable::new, false, false)},
            new Object[]{"ConcurrentHashMap", makeMap(ConcurrentHashMap::new, false, false)},
            new Object[]{"ConcurrentSkipListMap", makeMap(ConcurrentSkipListMap::new, false, false)},
            new Object[]{"Collections.synchronizedMap(ConcurrentHashMap)", Collections.synchronizedMap(makeMap(ConcurrentHashMap::new, false, false))},
            new Object[]{"Collections.checkedMap(ConcurrentHashMap)", Collections.checkedMap(makeMap(ConcurrentHashMap::new, false, false), IntegerEnum.class, String.class)},
            new Object[]{"ExtendsAbstractMap(ConcurrentHashMap)", makeMap(() -> {return new ExtendsAbstractMap(new ConcurrentHashMap());}, false, false)},
            new Object[]{"ImplementsConcurrentMap", makeMap(ImplementsConcurrentMap::new, false, false)}
            );
    }

    /**
     *
     * @param nulls include nulls
     * @return
     */
    private static Collection<Object[]> makeROMaps(boolean nulls) {
        return Arrays.asList(new Object[][]{
            new Object[]{"Collections.unmodifiableMap(HashMap)", Collections.unmodifiableMap(makeMap(HashMap::new, nulls, nulls))}
        });
    }

     /**
     *
     * @param supplier a supplier of mutable map instances.
     *
     * @param nullKeys   include null keys
     * @param nullValues include null values
     * @return
     */
    private static Map<IntegerEnum, String> makeMap(Supplier<Map<IntegerEnum, String>> supplier, boolean nullKeys, boolean nullValues) {
        Map<IntegerEnum, String> result = supplier.get();

        for (int each = 0; each < TEST_SIZE; each++) {
            IntegerEnum key = nullKeys ? (each == 0) ? null : KEYS[each] : KEYS[each];
            String value = nullValues ? (each == 0) ? null : VALUES[each] : VALUES[each];

            result.put(key, value);
        }

        return result;
    }

    static class Merging {
        public enum Value {
            ABSENT,
            NULL,
            OLDVALUE,
            NEWVALUE,
            RESULT
        }

        public enum Merger implements BiFunction<String,String,String> {
            UNUSED {
                public String apply(String oldValue, String newValue) {
                    fail("should not be called");
                    return null;
                }
            },
            NULL {
                public String apply(String oldValue, String newValue) {
                    return null;
                }
            },
            RESULT {
                public String apply(String oldValue, String newValue) {
                    return VALUES[3];
                }
            },
        }
    }

    @DataProvider(name = "MergeCases", parallel = true)
    public Iterator<Object[]> mergeCasesProvider() {
        Collection<Object[]> cases = new ArrayList<>();

        cases.addAll(makeMergeTestCases());

        return cases.iterator();
    }

    static Collection<Object[]> makeMergeTestCases() {
        Collection<Object[]> cases = new ArrayList<>();

        for( Object[] mapParams : makeAllRWMaps() ) {
            cases.add(new Object[] { mapParams[0], mapParams[1], Merging.Value.ABSENT, Merging.Value.NEWVALUE, Merging.Merger.UNUSED, Merging.Value.NEWVALUE, Merging.Value.NEWVALUE });
        }

        for( Object[] mapParams : makeAllRWMaps() ) {
            cases.add(new Object[] { mapParams[0], mapParams[1], Merging.Value.OLDVALUE, Merging.Value.NEWVALUE, Merging.Merger.NULL, Merging.Value.ABSENT, Merging.Value.NULL });
        }

        for( Object[] mapParams : makeAllRWMaps() ) {
            cases.add(new Object[] { mapParams[0], mapParams[1], Merging.Value.OLDVALUE, Merging.Value.NEWVALUE, Merging.Merger.RESULT, Merging.Value.RESULT, Merging.Value.RESULT });
        }

        return cases;
    }

    public interface Thrower<T extends Throwable> {

        public void run() throws T;
    }

    public static <T extends Throwable> void assertThrows(Thrower<T> thrower, Class<T> throwable) {
        assertThrows(thrower, throwable, null);
    }

    public static <T extends Throwable> void assertThrows(Thrower<T> thrower, Class<T> throwable, String message) {
        Throwable thrown;
        try {
            thrower.run();
            thrown = null;
        } catch (Throwable caught) {
            thrown = caught;
        }

        assertInstance(thrown, throwable,
            ((null != message) ? message : "") +
            " Failed to throw " + throwable.getCanonicalName());
    }

    public static <T extends Throwable> void assertThrows(Class<T> throwable, String message, Thrower<T>... throwers) {
        for(Thrower<T> thrower : throwers) {
            assertThrows(thrower, throwable, message);
        }
    }

    public static void assertInstance(Object actual, Class<?> expected) {
        assertInstance(expected.isInstance(actual), null);
    }

    public static void assertInstance(Object actual, Class<?> expected, String message) {
        assertTrue(expected.isInstance(actual), message);
    }

    /**
     * A simple mutable map implementation that provides only default
     * implementations of all methods. ie. none of the Map interface default
     * methods have overridden implementations.
     *
     * @param <K> Type of keys
     * @param <V> Type of values
     */
    public static class ExtendsAbstractMap<M extends Map<K,V>, K, V> extends AbstractMap<K, V> {

        protected final M map;

        public ExtendsAbstractMap() { this( (M) new HashMap<K,V>()); }

        protected ExtendsAbstractMap(M map) { this.map = map; }

        public Set<Map.Entry<K, V>> entrySet() {
            return new AbstractSet<Map.Entry<K, V>>() {
                public int size() {
                    return map.size();
                }

                public Iterator<Map.Entry<K,V>> iterator() {
                    final Iterator<Map.Entry<K,V>> source = map.entrySet().iterator();
                    return new Iterator<Map.Entry<K,V>>() {
                       public boolean hasNext() { return source.hasNext(); }
                       public Map.Entry<K,V> next() { return source.next(); }
                       public void remove() { source.remove(); }
                    };
                }

                public boolean add(Map.Entry<K,V> e) {
                    return map.entrySet().add(e);
                }
            };
        }

        public V put(K key, V value) {
            return map.put(key, value);
        }
    }

    /**
     * A simple mutable concurrent map implementation that provides only default
     * implementations of all methods. ie. none of the ConcurrentMap interface
     * default methods have overridden implementations.
     *
     * @param <K> Type of keys
     * @param <V> Type of values
     */
    public static class ImplementsConcurrentMap<K, V> extends ExtendsAbstractMap<ConcurrentMap<K,V>, K, V> implements ConcurrentMap<K,V> {
        public ImplementsConcurrentMap() { super(new ConcurrentHashMap<K,V>()); }

        // ConcurrentMap reabstracts these methods

        public V replace(K k, V v) { return map.replace(k, v); };

        public boolean replace(K k, V v, V vv) { return map.replace(k, v, vv); };

        public boolean remove(Object k, Object v) { return map.remove(k, v); }

        public V putIfAbsent(K k, V v) { return map.putIfAbsent(k, v); }
    }
}


text:
@interface OrientationsVC ()

@end

@implementation OrientationsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"99页";
}

//【注意】如果项目中 应用级 没有勾选支持的方向,那么下面返回任何方向都是无效的
//所以要优先在 项目中进行配置 选择项目[即 导航栏中的第一项]->General->Dployment Info -> Device Orientation
//- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
//    //支持 纵向 和 左旋转
//    return (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft);
//}

@end

redpajama_set_name: RedPajamaGithub


text:
using System;
using TrueCraft.API.Logic;
using TrueCraft.API;
using TrueCraft.Core.Logic.Blocks;
using TrueCraft.API.World;
using TrueCraft.API.Networking;

namespace TrueCraft.Core.Logic.Items
{
    public class SignItem : ItemProvider, ICraftingRecipe
    {
        public static readonly short ItemID = 0x143;

        public override short ID { get { return 0x143; } }

        public override Tuple<int, int> GetIconTexture(byte metadata)
        {
            return new Tuple<int, int>(10, 2);
        }

        public override sbyte MaximumStack { get { return 1; } }

        public override string DisplayName { get { return "Sign"; } }

        public ItemStack[,] Pattern
        {
            get
            {
                return new[,]
                {
                    { new ItemStack(WoodenPlanksBlock.BlockID), new ItemStack(WoodenPlanksBlock.BlockID), new ItemStack(WoodenPlanksBlock.BlockID) },
                    { new ItemStack(WoodenPlanksBlock.BlockID), new ItemStack(WoodenPlanksBlock.BlockID), new ItemStack(WoodenPlanksBlock.BlockID) },
                    { ItemStack.EmptyStack, new ItemStack(StickItem.ItemID), ItemStack.EmptyStack }
                };
            }
        }

        public ItemStack Output
        {
            get
            {
                return new ItemStack(ItemID);
            }
        }

        public bool SignificantMetadata
        {
            get
            {
                return true;
            }
        }

        public override void ItemUsedOnBlock(Coordinates3D coordinates, ItemStack item, BlockFace face, IWorld world, IRemoteClient user)
        {
            if (face == BlockFace.PositiveY)
            {
                var provider = user.Server.BlockRepository.GetBlockProvider(UprightSignBlock.BlockID);
                (provider as IItemProvider).ItemUsedOnBlock(coordinates, item, face, world, user);
            }
            else
            {
                var provider = user.Server.BlockRepository.GetBlockProvider(WallSignBlock.BlockID);
                (provider as IItemProvider).ItemUsedOnBlock(coordinates, item, face, world, user);
            }
        }
    }
}


text:
import OpenGL
OpenGL.ERROR_CHECKING = False


text:
int main()
{
    const auto myfile {"myfile"};
    if (std::filesystem::exists(myfile)) {
        const auto bigFileSize {std::filesystem::file_size(myfile)};
        std::filesystem::path tmpPath {"/tmp"};
        if (std::filesystem::space(tmpPath).available > bigFileSize) {
            std::filesystem::create_directory(tmpPath.append("example"));
            std::filesystem::copy_file(myfile, tmpPath.append("newFile"));
        }
    }

    std::string const& inputFile = "../inputfile.txt";
    std::fstream fileStream(inputFile, std::ios::in);
    std::string fileLine;

    if(!fileStream)
    {
        throw std::runtime_error(inputFile + ": " + std::strerror(errno));
    }

    while(getline(fileStream, fileLine))
    {
        std::cout << "Contents:" << fileLine << std::endl;
    }

    fileStream.close();

    return 0;
}


text:
package datastructures;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class Fingerprint {
	private String sampleSetID;

	private String allHeaders;

	private Integer contrastLevel;

	private String user_agent;
	private String accept_headers;

	private String platform;
	private String platformFlash;
	private String pluginDetails;
	private String timeZone;
	private String screenDetails;
	private String screenDetailsFlash;
	private String screenDetailsCSS;
	private String languageFlash;
	private String fonts;
	private String fontsJS_CSS;
	private String fontsCSS;
	private String charSizes;

	private boolean cookiesEnabled;

	private Boolean superCookieLocalStorage;
	private Boolean superCookieSessionStorage;
	private Boolean superCookieUserData;
	private Boolean hstsEnabled;
	private Boolean indexedDBEnabled;
	private String doNotTrack;

	private Long clockDifference;

	private String dateTime;
	private String mathTan;

	private boolean usingTor;
	private String tbbVersion;
	private String ipAddress;

	private Boolean adsBlockedGoogle;
	private Boolean adsBlockedBanner;
	private Boolean adsBlockedScript;

	private Integer likeShareFacebook;
	private Integer likeShareTwitter;
	private Integer likeShareReddit;

	private String canvas;
	private String webGLVendor;
	private String webGLRenderer;

	private Integer touchPoints;
	private Boolean touchEvent;
	private Boolean touchStart;

	private String audioFingerprintPXI;
	private String audioFingerprintPXIFullBuffer;
	private String audioFingerprintNtVc;
	private String audioFingerprintCC;
	private String audioFingerprintHybrid;

	public Fingerprint() {
		sampleSetID = null;
		allHeaders = null;
		contrastLevel = null;
		user_agent = null;
		accept_headers = null;
		platform = null;
		platformFlash = null;
		pluginDetails = null;
		timeZone = null;
		screenDetails = null;
		screenDetailsFlash = null;
		screenDetailsCSS = null;
		languageFlash = null;
		fonts = null;
		fontsJS_CSS = null;
		fontsCSS = null;
		charSizes = null;
		cookiesEnabled = false;
		superCookieLocalStorage = null;
		superCookieSessionStorage = null;
		superCookieUserData = null;
		hstsEnabled = null;
		indexedDBEnabled = null;
		doNotTrack = null;
		clockDifference = null;
		dateTime = null;
		mathTan = null;
		usingTor = false;
		tbbVersion = null;
		ipAddress = null;
		adsBlockedGoogle = null;
		adsBlockedBanner = null;
		adsBlockedScript = null;
		likeShareFacebook = null;
		likeShareTwitter = null;
		likeShareReddit = null;
		canvas = null;
		webGLVendor = null;
		webGLRenderer = null;
		touchPoints = null;
		touchEvent = null;
		touchStart = null;
		audioFingerprintPXI = null;
		audioFingerprintPXIFullBuffer = null;
		audioFingerprintNtVc = null;
		audioFingerprintCC = null;
		audioFingerprintHybrid = null;
	}

	/**
	 * Get the hash of this fingerprint.
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public String getFingerprintHash() throws NoSuchAlgorithmException{
		MessageDigest digest = MessageDigest.getInstance("SHA-1");
		digest.reset();
		if(this.getContrastLevel() != null){
			digest.update(this.getContrastLevel().byteValue());
		}
		if(this.getUser_agent() != null){
			digest.update(this.getUser_agent().getBytes());
		}
		if(this.getAccept_headers() != null){
			digest.update(this.getAccept_headers().getBytes());
		}
		if(this.getPlatform() != null){
			digest.update(this.getPlatform().getBytes());
		}
		if(this.getPlatformFlash() != null){
			digest.update(this.getPlatformFlash().getBytes());
		}
		if(this.getPluginDetails() != null){
			digest.update(this.getPluginDetails().getBytes());
		}
		if(this.getTimeZone() != null){
			digest.update(this.getTimeZone().getBytes());
		}
		/*if(this.getScreenDetails() != null){
			digest.update(this.getScreenDetails().getBytes());
		}*/
		if(this.getScreenDetailsFlash() != null){
			digest.update(this.getScreenDetailsFlash().getBytes());
		}
		/*if(this.getScreenDetailsCSS() != null){
			digest.update(this.getScreenDetailsCSS().getBytes());
		}*/
		if(this.getLanguageFlash() != null){
			digest.update(this.getLanguageFlash().getBytes());
		}
		if(this.getFonts() != null){
			digest.update(this.getFonts().getBytes());
		}
		if(this.getFontsJS_CSS() != null){
			digest.update(this.getFontsJS_CSS().getBytes());
		}
		if(this.getFontsCSS() != null){
			digest.update(this.getFontsCSS().getBytes());
		}
		/*if(this.getCharSizes() != null){
			digest.update(this.getCharSizes().getBytes());
		}*/
		digest.update(Boolean.toString(this.isCookiesEnabled()).getBytes());
		if(this.getSuperCookieLocalStorage() != null){
			digest.update(Boolean.toString(this.getSuperCookieLocalStorage()).getBytes());
		}
		if(this.getSuperCookieSessionStorage() != null){
			digest.update(Boolean.toString(this.getSuperCookieSessionStorage()).getBytes());
		}
		if(this.getSuperCookieUserData() != null){
			digest.update(Boolean.toString(this.getSuperCookieUserData()).getBytes());
		}
		if(this.getIndexedDBEnabled() != null){
			digest.update(Boolean.toString(this.getIndexedDBEnabled()).getBytes());
		}
		if(this.getHstsEnabled() != null){
			digest.update(Boolean.toString(this.getHstsEnabled()).getBytes());
		}
		if(this.getDoNotTrack() != null){
			digest.update(this.getDoNotTrack().getBytes());
		}
		if(this.getClockDifference() != null){
			digest.update(Long.toString(this.getClockDifference()).getBytes());
		}
		if(this.getDateTime() != null){
			digest.update(this.getDateTime().getBytes());
		}
		if(this.getMathTan() != null){
			digest.update(this.getMathTan().getBytes());
		}
		digest.update(Boolean.toString(this.isUsingTor()).getBytes());
		if(this.getTbbVersion() != null){
			digest.update(this.getTbbVersion().getBytes());
		}
		if(this.getAdsBlockedGoogle() != null){
			digest.update(Boolean.toString(this.getAdsBlockedGoogle()).getBytes());
		}
		if(this.getAdsBlockedBanner() != null){
			digest.update(Boolean.toString(this.getAdsBlockedBanner()).getBytes());
		}
		if(this.getAdsBlockedScript() != null){
			digest.update(Boolean.toString(this.getAdsBlockedScript()).getBytes());
		}
		if(this.getLikeShareFacebook() != null){
			digest.update(Integer.toString(this.getLikeShareFacebook()).getBytes());
		}
		if(this.getLikeShareTwitter() != null){
			digest.update(Integer.toString(this.getLikeShareTwitter()).getBytes());
		}
		if(this.getLikeShareReddit() != null){
			digest.update(Integer.toString(this.getLikeShareReddit()).getBytes());
		}
		/*if(this.getCanvas() != null){
			digest.update(this.getCanvas().getBytes());
		}*/
		if(this.getWebGLVendor() != null){
			digest.update(this.getWebGLVendor().getBytes());
		}
		if(this.getWebGLRenderer() != null){
			digest.update(this.getWebGLRenderer().getBytes());
		}
		if(this.getTouchPoints() != null){
			digest.update(Integer.toString(this.getTouchPoints()).getBytes());
		}
		if(this.getTouchEvent() != null){
			digest.update(Boolean.toString(this.getTouchEvent()).getBytes());
		}
		if(this.getTouchStart() != null){
			digest.update(Boolean.toString(this.getTouchStart()).getBytes());
		}
		/*if(this.getAudioFingerprintPXI() != null){
			digest.update(this.getAudioFingerprintPXI().getBytes());
		}*/
		/*if(this.getAudioFingerprintPXIFullBuffer() != null){
			digest.update(this.getAudioFingerprintPXIFullBuffer().getBytes());
		}*/
		/*if(this.getAudioFingerprintNtVc() != null){
			digest.update(this.getAudioFingerprintNtVc().getBytes());
		}*/
		/*if(this.getAudioFingerprintCC() != null){
			digest.update(this.getAudioFingerprintCC().getBytes());
		}*/
		/*if(this.getAudioFingerprintHybrid() != null){
			digest.update(this.getAudioFingerprintHybrid().getBytes());
		}*/
		return Base64.getEncoder().encodeToString(digest.digest());
	}

	public String getSampleSetID() {
		return sampleSetID;
	}

	public void setSampleSetID(String sampleSetID) {
		this.sampleSetID = sampleSetID;
	}

	public String getAllHeaders() {
		return allHeaders;
	}

	public void setAllHeaders(String allHeaders) {
		this.allHeaders = allHeaders;
	}

	public Integer getContrastLevel() {
		return contrastLevel;
	}

	public void setContrastLevel(Integer contrastLevel) {
		this.contrastLevel = contrastLevel;
	}

	public String getUser_agent() {
		return user_agent;
	}

	public void setUser_agent(String user_agent) {
		this.user_agent = user_agent;
	}

	public String getAccept_headers() {
		return accept_headers;
	}

	public void setAccept_headers(String accept_headers) {
		this.accept_headers = accept_headers;
	}

	public String getPlatform() {
		return platform;
	}

	public void setPlatform(String platform) {
		this.platform = platform;
	}

	public String getPlatformFlash() {
		return platformFlash;
	}

	public void setPlatformFlash(String platformFlash) {
		this.platformFlash = platformFlash;
	}

	public String getPluginDetails() {
		return pluginDetails;
	}

	public void setPluginDetails(String pluginDetails) {
		this.pluginDetails = pluginDetails;
	}

	public String getTimeZone() {
		return timeZone;
	}

	public void setTimeZone(String timeZone) {
		this.timeZone = timeZone;
	}

	public String getScreenDetails() {
		return screenDetails;
	}

	public void setScreenDetails(String screenDetails) {
		this.screenDetails = screenDetails;
	}

	public String getScreenDetailsFlash() {
		return screenDetailsFlash;
	}

	public void setScreenDetailsFlash(String screenDetailsFlash) {
		this.screenDetailsFlash = screenDetailsFlash;
	}

	public String getScreenDetailsCSS() {
		return screenDetailsCSS;
	}

	public void setScreenDetailsCSS(String screenDetailsCSS) {
		this.screenDetailsCSS = screenDetailsCSS;
	}

	public String getLanguageFlash() {
		return languageFlash;
	}

	public void setLanguageFlash(String languageFlash) {
		this.languageFlash = languageFlash;
	}

	public String getFonts() {
		return fonts;
	}

	public void setFonts(String fonts) {
		this.fonts = fonts;
	}

	public String getFontsJS_CSS() {
		return fontsJS_CSS;
	}

	public void setFontsJS_CSS(String fontsJS_CSS) {
		this.fontsJS_CSS = fontsJS_CSS;
	}

	public String getFontsCSS() {
		return fontsCSS;
	}

	public void setFontsCSS(String fontsCSS) {
		this.fontsCSS = fontsCSS;
	}

	public String getCharSizes() {
		return charSizes;
	}

	public void setCharSizes(String charSizes) {
		this.charSizes = charSizes;
	}

	public boolean isCookiesEnabled() {
		return cookiesEnabled;
	}

	public void setCookiesEnabled(boolean cookiesEnabled) {
		this.cookiesEnabled = cookiesEnabled;
	}

	public Boolean getSuperCookieLocalStorage() {
		return superCookieLocalStorage;
	}

	public void setSuperCookieLocalStorage(Boolean superCookieLocalStorage) {
		this.superCookieLocalStorage = superCookieLocalStorage;
	}

	public Boolean getSuperCookieSessionStorage() {
		return superCookieSessionStorage;
	}

	public void setSuperCookieSessionStorage(Boolean superCookieSessionStorage) {
		this.superCookieSessionStorage = superCookieSessionStorage;
	}

	public Boolean getSuperCookieUserData() {
		return superCookieUserData;
	}

	public void setSuperCookieUserData(Boolean superCookieUserData) {
		this.superCookieUserData = superCookieUserData;
	}

	public Boolean getHstsEnabled() {
		return hstsEnabled;
	}

	public void setHstsEnabled(Boolean hstsEnabled) {
		this.hstsEnabled = hstsEnabled;
	}

	public Boolean getIndexedDBEnabled() {
		return indexedDBEnabled;
	}

	public void setIndexedDBEnabled(Boolean indexedDBEnabled) {
		this.indexedDBEnabled = indexedDBEnabled;
	}

	public String getDoNotTrack() {
		return doNotTrack;
	}

	public void setDoNotTrack(String doNotTrack) {
		this.doNotTrack = doNotTrack;
	}

	public Long getClockDifference() {
		return clockDifference;
	}

	public void setClockDifference(Long clockDifference) {
		this.clockDifference = clockDifference;
	}

	public String getDateTime() {
		return dateTime;
	}

	public void setDateTime(String dateTime) {
		this.dateTime = dateTime;
	}

	public String getMathTan() {
		return mathTan;
	}

	public void setMathTan(String mathTan) {
		this.mathTan = mathTan;
	}

	public boolean isUsingTor() {
		return usingTor;
	}

	public void setUsingTor(boolean usingTor) {
		this.usingTor = usingTor;
	}

	public String getTbbVersion() {
		return tbbVersion;
	}

	public void setTbbVersion(String tbbVersion) {
		this.tbbVersion = tbbVersion;
	}

	public String getIpAddress() {
		return ipAddress;
	}

	public void setIpAddress(String ipAddress) {
		this.ipAddress = ipAddress;
	}

	public Boolean getAdsBlockedGoogle() {
		return adsBlockedGoogle;
	}

	public void setAdsBlockedGoogle(Boolean adsBlockedGoogle) {
		this.adsBlockedGoogle = adsBlockedGoogle;
	}

	public Boolean getAdsBlockedBanner() {
		return adsBlockedBanner;
	}

	public void setAdsBlockedBanner(Boolean adsBlockedBanner) {
		this.adsBlockedBanner = adsBlockedBanner;
	}

	public Boolean getAdsBlockedScript() {
		return adsBlockedScript;
	}

	public void setAdsBlockedScript(Boolean adsBlockedScript) {
		this.adsBlockedScript = adsBlockedScript;
	}

	public Integer getLikeShareFacebook() {
		return likeShareFacebook;
	}

	public void setLikeShareFacebook(Integer likeShareFacebook) {
		this.likeShareFacebook = likeShareFacebook;
	}

	public Integer getLikeShareTwitter() {
		return likeShareTwitter;
	}

	public void setLikeShareTwitter(Integer likeShareTwitter) {
		this.likeShareTwitter = likeShareTwitter;
	}

	public Integer getLikeShareReddit() {
		return likeShareReddit;
	}

	public void setLikeShareReddit(Integer likeShareReddit) {
		this.likeShareReddit = likeShareReddit;
	}

	public String getCanvas() {
		return canvas;
	}

	public void setCanvas(String canvas) {
		this.canvas = canvas;
	}

	public String getWebGLVendor() {
		return webGLVendor;
	}

	public void setWebGLVendor(String webGLVendor) {
		this.webGLVendor = webGLVendor;
	}

	public String getWebGLRenderer() {
		return webGLRenderer;
	}

	public void setWebGLRenderer(String webGLRenderer) {
		this.webGLRenderer = webGLRenderer;
	}

	public Integer getTouchPoints() {
		return touchPoints;
	}

	public void setTouchPoints(Integer touchPoints) {
		this.touchPoints = touchPoints;
	}

	public Boolean getTouchEvent() {
		return touchEvent;
	}

	public void setTouchEvent(Boolean touchEvent) {
		this.touchEvent = touchEvent;
	}

	public Boolean getTouchStart() {
		return touchStart;
	}

	public void setTouchStart(Boolean touchStart) {
		this.touchStart = touchStart;
	}

	public String getAudioFingerprintPXI() {
		return audioFingerprintPXI;
	}

	public void setAudioFingerprintPXI(String audioFingerprintPXI) {
		this.audioFingerprintPXI = audioFingerprintPXI;
	}

	public String getAudioFingerprintPXIFullBuffer() {
		return audioFingerprintPXIFullBuffer;
	}

	public void setAudioFingerprintPXIFullBuffer(String audioFingerprintPXIFullBuffer) {
		this.audioFingerprintPXIFullBuffer = audioFingerprintPXIFullBuffer;
	}

	public String getAudioFingerprintNtVc() {
		return audioFingerprintNtVc;
	}

	public void setAudioFingerprintNtVc(String audioFingerprintNtVc) {
		this.audioFingerprintNtVc = audioFingerprintNtVc;
	}

	public String getAudioFingerprintCC() {
		return audioFingerprintCC;
	}

	public void setAudioFingerprintCC(String audioFingerprintCC) {
		this.audioFingerprintCC = audioFingerprintCC;
	}

	public String getAudioFingerprintHybrid() {
		return audioFingerprintHybrid;
	}

	public void setAudioFingerprintHybrid(String audioFingerprintHybrid) {
		this.audioFingerprintHybrid = audioFingerprintHybrid;
	}
}


text:
from setuptools import setup

setup(name='MarconiDashboard',
      version='0.1',
      description='Simple dashboard for Marconi',
      author='Flavio Percoco',
      author_email='flaper87@flaper87.org',
      url='http://www.python.org/sigs/distutils-sig/',
      install_requires=['pbr', 'setuptools-git',
                        'Flask==0.10.1', 'Flask-Bootstrap',
                        'flask-appconfig', 'flask-wtf',
                        'python-marconiclient>=0.0.1a1'])


text:
"""
mh.py - A single myosin head

Created by Dave Williams on 2010-01-04.
"""

import numpy.random as random
random.seed() # Ensure proper seeding
from numpy import pi, sqrt, log, radians
import math as m
import warnings

class Spring:
    """A generic spring, from which we make the myosin heads"""
    def __init__(self, config):
        ## Passed variables
        self.r_w = config['rest_weak']
        self.r_s = config['rest_strong']
        self.k_w = config['konstant_weak']
        self.k_s = config['konstant_strong']
        ## Diffusion governors
        # k_T = Boltzmann constant * temperature = (1.381E-23 J/K * 288 K)
        k_t = 1.381*10**-23 * 288 * 10**21 #10**21 converts J to pN*nM
        # Normalize: a factor used to normalize the PDF of the segment values
        self.normalize = sqrt(2*pi*k_t/self.k_w)
        self.stand_dev = sqrt(k_t/self.k_w) # of segment values

    def to_dict(self):
        """Create a JSON compatible representation of the spring """
        return self.__dict__.copy()

    def from_dict(self, sd):
        """ Load values from a spring dict. Values read in correspond
        to the current output documented in to_dict.
        """
        self.r_w = sd['r_w']
        self.r_s = sd['r_s']
        self.k_w = sd['k_w']
        self.k_s = sd['k_s']
        self.normalize = sd['normalize']
        self.stand_dev = sd['stand_dev']

    def rest(self, state):
        """Return the rest value of the spring in state state

        Takes:
            state: the state of the spring, ['free'|'loose'|'tight']
        Returns:
            length/angle: rest length/angle of the spring in the given state
        """
        if state in ("free", "loose"):
            return self.r_w
        elif state == "tight":
            return self.r_s
        else:
            warnings.warn("Improper value for spring state")

    def constant(self, state):
        """Return the spring constant of the spring in state state

        Takes:
            state: the state of the spring, ['free'|'loose'|'tight']
        Returns:
            spring constant: for the spring in the given state
        """
        if state in ("free", "loose"):
            return self.k_w
        elif state == "tight":
            return self.k_s
        else:
            warnings.warn("Improper value for spring state")

    def energy(self, spring_val, state):
        """Given a current length/angle, return stored energy

        Takes:
            spring_val: a spring length or angle
            state: a spring state, ['free'|'loose'|'tight']
        Returns:
            energy: the energy required to achieve the given value
        """
        if state in ("free", "loose"):
            return (0.5 * self.k_w * m.pow((spring_val-self.r_w), 2))
        elif state == "tight":
            return (0.5 * self.k_s * m.pow((spring_val-self.r_s), 2))
        else:
            warnings.warn("Improper value for spring state")

    def bop(self):
        """Bop for a new value, given an exponential energy dist

        A longer explanation is in singlexb/Crossbridge.py
        Takes:
            nothing: assumes the spring to be in the unbound state
        Returns:
            spring_value: the length or angle of the spring after diffusion"""
        return (random.normal(self.r_w, self.stand_dev))

class SingleSpringHead:
    """A single-spring myosin head, as in days of yore"""
    def __init__(self):
        """Create the spring that makes up the head and set energy values"""
        self.state = "free"
        self.g = Spring({
            'rest_weak': 5,
            'rest_strong': 0,
            'konstant_weak': 5 / 3.976,
            'konstant_strong': 5 / 3.976})
        # Free energy calculation helpers
        g_atp = 13 # In units of RT
        atp = 5  * 10**-3
        adp = 30 * 10**-6
        phos  = 3  * 10**-3
        self.deltaG = abs(-g_atp - log(atp / (adp * phos)))
        self.alpha = 0.28
        self.eta = 0.68
        # The time-step, master of all time
        self.timestep = 1 # ms

    def transition(self, bs):
        """Transition to a new state (or not)

        Takes:
            bs: relative Crown to Actin distance (x,y)
        Returns:
            boolean: transition that occurred (as string) or None
        """
        ## Transitions rates are checked against a random number
        check = random.rand()
        ## Check for transitions depending on the current state
        if self.state == "free":
            if self._r12(bs) > check:
                self.state = "loose"
                return '12'
        elif self.state == "loose":
            if self._r23(bs) > check:
                self.state = "tight"
                return '23'
            elif (1-self._r21(bs)) < check:
                self.state = "free"
                return '21'
        elif self.state == "tight":
            if self._r31(bs) > check:
                self.state = "free"
                return '31'
            elif (1-self._r32(bs)) < check:
                self.state = "loose"
                return '32'
        # Got this far? Than no transition occurred!
        return None

    def axialforce(self, tip_location):
        """Find the axial force a Head generates at a given location

        Takes:
            tip_location: relative Crown to Actin distance (x,y)
        Returns:
            f_x: the axial force generated by the Head
        """
        ## Get the Head length
        g_len = tip_location[0]
        ## Write all needed values to local variables
        g_s = self.g.rest(self.state)
        g_k = self.g.constant(self.state)
        ## Find and return force
        f_x = g_k * (g_len - g_s)
        return f_x

    def radialforce(self, tip_location):
        """Find the radial force a Head generates at a given location

        Takes:
            tip_location: relative Crown to Actin distance (x,y)
        Returns:
            f_y: the radial force generated by the Head
        """
        return 0.0

    def energy(self, tip_location, state=None):
        """Return the energy in the xb with the given parameters

        Takes:
            tip_location: relative Crown to Actin distance (x,y)
            state: kinetic state of the cross-bridge, ['free'|'loose'|'tight']
        Returns:
            xb_energy: the energy stored in the cross-bridge"""
        if state is None:
            state = self.state
        return self.g.energy(tip_location[0], state)

    @property
    def numeric_state(self):
        """Return the numeric state (0, 1, or 2) of the head"""
        lookup_state = {"free":0, "loose":1, "tight":2}
        return lookup_state[self.state]

    def _set_timestep(self, timestep):
        """Set the length of time step used to calculate transitions"""
        self.timestep = timestep

    def _r12(self, bs):
        """Binding rate, based on the distance from the Head tip to a Actin

        Takes:
            bs: relative Crown to Actin distance (x,y)
        Returns:
            probability: chance of binding occurring
        """
        ## Get needed values
        k_xb = self.g.constant("free")
        xb_0 = self.g.rest("free")
        A = 2000  # From Tanner, 2008 Pg 1209
        ## Calculate the binding probability
        rate = (A * sqrt(k_xb / (2 * pi)) *
                m.exp(-.5 * k_xb * (bs[0] - xb_0)**2)) * self.timestep
        return float(rate)

    def _r21(self, bs):
        """The reverse transition, from loosely bound to unbound

        Takes:
            bs: relative Crown to Actin distance (x,y)
        Returns:
            rate: probability of transition occurring this timestep
        """
        ## The rate depends on the states' free energies
        g_1 = self._free_energy(bs, "free")
        g_2 = self._free_energy(bs, "loose")
        ## Rate, as in pg 1209 of Tanner et al, 2007
        try:
            rate = self._r12(bs) / m.exp(g_1 - g_2)
        except ZeroDivisionError:
            rate = 1
        return float(rate)

    def _r23(self, bs):
        """Probability of becoming tightly bound if loosely bound

        Takes:
            bs: relative Crown to Actin distance (x,y)
        Returns:
            rate: probability of becoming tightly bound
        """
        ## Get other needed values
        k_xb = self.g.constant("loose")
        xb_0 = self.g.rest("loose")
        B = 100   # From Tanner, 2008 Pg 1209
        C = 1
        D = 1
        ## Rate taken from single cross-bridge work
        rate = (B / sqrt(k_xb) * (1 - m.tanh(C * sqrt(k_xb) *
                (bs[0] - xb_0))) + D) * self.timestep
        return float(rate)

    def _r32(self, bs):
        """The reverse transition, from tightly to loosely bound

        Takes:
            bs: relative Crown to Actin distance (x,y)
        Returns:
            rate: probability of becoming loosely bound
        """
        ## Governed as in self_r21
        g_2 = self._free_energy(bs, "loose")
        g_3 = self._free_energy(bs, "tight")
        try:
            rate = self._r23(bs) / m.exp(g_2 - g_3)
        except ZeroDivisionError:
            rate = 1
        return float(rate)

    def _r31(self, bs):
        """Probability of unbinding if tightly bound

        Takes:
            bs: relative Crown to Actin distance (x,y)
        Returns:
            rate: probability of detaching from the binding site
        """
        ## Get needed values
        k_xb = self.g.constant("tight")
        M = 3600 # From Tanner, 2008 Pg 1209
        N = 40
        P = 20
        ## Based on the energy in the tight state
        rate = (sqrt(k_xb) * (sqrt(M * (bs[0]-4.76)**2) -
                N * (bs[0]-4.76)) + P) * self.timestep
        return float(rate)

    def _free_energy(self, tip_location, state):
        """Free energy of the Head

        Takes:
            tip_location: relative Crown to Actin distance (x,y)
            state: kinetic state of the cross-bridge, ['free'|'loose'|'tight']
        Returns:
            energy: free energy of the head in the given state
        """
        if state == "free":
            return 0
        elif state == "loose":
            k_xb = self.g.constant(state)
            xb_0 = self.g.rest(state)
            x = tip_location[0]
            return self.alpha * -self.deltaG + k_xb * (x - xb_0)**2
        elif state == "tight":
            k_xb = self.g.constant(state)
            x = tip_location[0]
            return self.eta * -self.deltaG + k_xb * x**2

class Head:
    """Head implements a single myosin head"""
    def __init__(self):
        """Create the springs that make up the head and set energy values
        Values are choosen for consistancy with single spring rest lengths
        and rest lattice spacings. More documentaion in the single spring
        code. All numerical values referenced are discussed in single
        crossbridge PLOS paper.
        """
        # Remember thine kinetic state
        self.state = "free"
        # Create the springs which make up the head
        self.c = Spring({   # the converter domain
            'rest_weak': radians(47.16),
            'rest_strong': radians(73.20),
            'konstant_weak': 40,
            'konstant_strong': 40})
        self.g = Spring({   # the globular domain
            'rest_weak': 19.93,
            'rest_strong': 16.47,
            'konstant_weak': 2,
            'konstant_strong': 2})
        # Free energy calculation helpers
        g_atp = 13 # In units of RT
        atp = 5  * 10**-3
        adp = 30 * 10**-6
        phos  = 3  * 10**-3
        deltaG = abs(-g_atp - log(atp / (adp * phos)))
        self.alphaDG = 0.28 * -deltaG
        self.etaDG = 0.68 * -deltaG
        # The time-step, master of all time
        self._timestep = 1 # ms

    def transition(self, bs, ap):
        """Transition to a new state (or not)

        Takes:
            bs: relative Crown to Actin distance (x,y)
            ap: Actin binding permissiveness, from 0 to 1
        Returns:
            boolean: transition that occurred (as string) or None
        """
        ## Transitions rates are checked against a random number
        check = random.rand()
        ## Check for transitions depending on the current state
        if self.state == "free":
            if self._prob(self._bind(bs))*ap > check:
                self.state = "loose"
                return '12'
        elif self.state == "loose":
            if self._prob(self._r23(bs)) > check:
                self.state = "tight"
                return '23'
            elif (1 - self._prob(self._r21(bs))) < check:
                self.state = "free"
                return '21'
        elif self.state == "tight":
            if self._prob(self._r31(bs)) > check:
                self.state = "free"
                return '31'
            elif (1 - self._prob(self._r32(bs))) < check:
                self.state = "loose"
                return '32'
        # Got this far? Than no transition occurred!
        return None

    def axialforce(self, tip_location):
        """Find the axial force a Head generates at a given location

        Takes:
            tip_location: relative Crown to Actin distance (x,y)
        Returns:
            f_x: the axial force generated by the Head
        """
        ## Get the Head length and angle
        (c_ang, g_len) = self._seg_values(tip_location)
        ## Write all needed values to local variables
        c_s = self.c.rest(self.state)
        g_s = self.g.rest(self.state)
        c_k = self.c.constant(self.state)
        g_k = self.g.constant(self.state)
        ## Find and return force
        f_x = (g_k * (g_len - g_s) * m.cos(c_ang) +
               1/g_len * c_k * (c_ang - c_s) * m.sin(c_ang))
        return f_x

    def radialforce(self, tip_location):
        """Find the radial force a Head generates at a given location

        Takes:
            tip_location: relative Crown to Actin distance (x,y)
        Returns:
            f_y: the radial force generated by the Head
        """
        ## Get the Head length and angle
        (c_ang, g_len) = self._seg_values(tip_location)
        ## Write all needed values to local variables
        c_s = self.c.rest(self.state)
        g_s = self.g.rest(self.state)
        c_k = self.c.constant(self.state)
        g_k = self.g.constant(self.state)
        ## Find and return force
        f_y = (g_k * (g_len - g_s) * m.sin(c_ang) +
               1/g_len * c_k * (c_ang - c_s) * m.cos(c_ang))
        return f_y

    def energy(self, tip_location, state=None):
        """Return the energy in the xb with the given parameters

        Takes:
            tip_location: relative Crown to Actin distance (x,y)
            state: kinetic state of the cross-bridge, ['free'|'loose'|'tight']
        Returns:
            xb_energy: the energy stored in the cross-bridge"""
        if state == None:
            state = self.state
        (ang, dist) = self._seg_values(tip_location)
        xb_energy = self.c.energy(ang, state) + self.g.energy(dist, state)
        return xb_energy

    @property
    def numeric_state(self):
        """Return the numeric state (0, 1, or 2) of the head"""
        lookup_state = {"free":0, "loose":1, "tight":2}
        return lookup_state[self.state]

    @property
    def timestep(self):
        return self._timestep

    @timestep.setter
    def timestep(self, timestep):
        """Set the length of time step used to calculate transitions"""
        self._timestep = timestep

    def _prob(self, rate):
        """Convert a rate to a probability, based on the current timestep
        length and the assumption that the rate is for a Poisson process.
        We are asking, what is the probability that at least one Poisson
        distributed value would occur during the timestep.

        Takes:
            rate: a per ms rate to convert to probability
        Returns:
            probability: the probability the event occurs during a timestep
                of length determined by self.timestep
        """
        return 1 - m.exp(-rate*self.timestep)

    def _bind(self, bs):
        """Bind (or don't) based on the distance from the Head tip to a Actin

        Takes:
            bs: relative Crown to Actin distance (x,y)
        Returns:
            probability: chance of binding occurring during a timestep
        """
        ## Flag indicates successful diffusion
        bop_right = False
        while bop_right is False:
            ## Bop the springs to get new values
            c_ang = self.c.bop()
            g_len = self.g.bop()
            ## Translate those values to an (x,y) position
            tip = (g_len * m.cos(c_ang), g_len * m.sin(c_ang))
            ## Only a bop that lands short of the thin fil is valid
            bop_right = bs[1] >= tip[1]
        ## Find the distance to the binding site
        distance = m.hypot(bs[0]-tip[0], bs[1]-tip[1])

        ## The binding rate is dependent on the exp of the dist
        # Rate = \tau * \exp^{-dist^2}
        rate = 72 * m.exp(-distance**2)
        ## Return the rate
        return rate

    def _r21(self, bs):
        """The reverse transition, from loosely bound to unbound

        This depends on the prob r12, the binding prob, which is given
        in a stochastic manner. Thus _p21 is returning not the prob of
        going from loosely bound to tightly bound, but the change that
        occurs in one particular timestep, the stochastic probability.
        Takes:
            bs: relative Crown to Actin distance (x,y)
            ap: Actin binding permissiveness, from 0 to 1
        Returns:
            prob: probability of transition
        """
        ## The rate depends on the states' free energies
        unbound_free_energy = self._free_energy(bs, "free")
        loose_free_energy = self._free_energy(bs, "loose")
        ## Rate, as in pg 1209 of Tanner et al, 2007
        ## With added reduced-detachment factor, increases dwell time
        try:
            rate = self._bind(bs) / m.exp(
                unbound_free_energy - loose_free_energy)
        except ZeroDivisionError:

            rate = 1
        return float(rate)

    def _r23(self, bs):
        """Rate of becoming tightly bound if loosely bound

        Takes:
            bs: relative Crown to Actin distance (x,y)
        Returns:
            rate: per ms rate of becoming tightly bound
        """
        ## The transition rate depends on state energies
        loose_energy = self.energy(bs, "loose")
        tight_energy = self.energy(bs, "tight")
        ## Powerstroke rate, per ms
        rate = (0.6 * # reduce overall rate
                (1 +  # shift rate up to avoid negative rate
                m.tanh(6 + # move center of transition to right
                       0.2 * (loose_energy - tight_energy))))
        return float(rate)

    def _r32(self, bs):
        """The reverse transition, from tightly to loosely bound

        Takes:
            bs: relative Crown to Actin distance (x,y)
        Returns:
            rate: per ms rate of transition
        """
        ## Governed as in self_p21
        loose_free_energy = self._free_energy(bs, "loose")
        tight_free_energy = self._free_energy(bs, "tight")
        try:
            rate = self._r23(bs)/ m.exp(loose_free_energy - tight_free_energy)
        except ZeroDivisionError:
            rate = 1
        return float(rate)

    def _r31(self, bs):
        """Per ms rate of unbinding if tightly bound

        Takes:
            bs: relative Crown to Actin distance (x,y)
        Returns
            rate: per ms rate of detaching from the binding site
        """
        ## Based on the energy in the tight state
        loose_energy = self.energy(bs, "loose")
        tight_energy = self.energy(bs, "tight")
        rate = m.sqrt(0.01*tight_energy) + 0.02
        return float(rate)

    def _free_energy(self, tip_location, state):
        """Free energy of the Head

        Takes:
            tip_location: relative Crown to Actin distance (x,y)
            state: kinetic state of the cross-bridge, ['free'|'loose'|'tight']
        Returns:
            energy: free energy of the head in the given state
        """
        if state == "free":
            return 0
        elif state == "loose":
            return self.alphaDG + self.energy(tip_location, state)
        elif state == "tight":
            return self.etaDG + self.energy(tip_location, state)

    @staticmethod
    def _seg_values(tip_location):
        """Return the length and angle to the Head tip

        Takes:
            tip_location: relative Crown to Actin distance (x,y)
        Returns:
            (c_ang, g_len): the angle and length of the Head's springs
        """
        c_ang = m.atan2(tip_location[1], tip_location[0])
        g_len = m.hypot(tip_location[1], tip_location[0])
        return (c_ang, g_len)

class Crossbridge(Head):
    """A cross-bridge, including status of links to actin sites"""
    def __init__(self, index, parent_face, thin_face):
        """Set up the cross-bridge

        Parameters:
            index: the cross-bridge's index on the parent face
            parent_face: the associated thick filament face
            thin_face: the face instance opposite this cross-bridge
        """
        # Do that super() voodoo that instantiates the parent Head
        super(Crossbridge, self).__init__()
        # What is your name, where do you sit on the parent face?
        self.index = index
        # What log are you a bump upon?
        self.parent_face = parent_face
        # Remember who thou art squaring off against
        self.thin_face = thin_face
        # How can I ever find you?
        self.address = ('xb', self.parent_face.parent_filament.index,
                        self.parent_face.index, self.index)
        # Remember if thou art bound unto an actin
        self.bound_to = None # None if unbound, BindingSite object otherwise

    def __str__(self):
        """String representation of the cross-bridge"""
        out = '__XB_%02d__State_%s__Forces_%d_%d__'%(
            self.index, self.state,
            self.axialforce(), self.radialforce())
        return out

    def to_dict(self):
        """Create a JSON compatible representation of the crown

        Example usage: json.dumps(crown.to_dict(), indent=1)

        Current output includes:
            address: largest to most local, indices for finding this
            state: the free, loose, strong state of binding
            thin_face: the address of the opposing thin face
            bound_to: None or the address of the bound binding site
        """
        xbd = self.__dict__.copy()
        xbd.pop('_timestep')
        xbd.pop('index')
        xbd.pop('c')
        xbd.pop('g')
        xbd.pop('parent_face')
        if xbd['bound_to'] is not None:
            xbd['bound_to'] = xbd['bound_to'].address
        xbd['thin_face'] = xbd['thin_face'].address
        return xbd

    def from_dict(self, xbd):
        """ Load values from a crossbridge dict. Values read in correspond
        to the current output documented in to_dict.
        """
        # Check for index mismatch
        read, current = tuple(xbd['address']), self.address
        assert read==current, "index mismatch at %s/%s"%(read, current)
        # Local keys
        self.state = xbd['state']
        self.etaDG = xbd['etaDG']
        self.alphaDG = xbd['alphaDG']
        # Sub-structure and remote keys
        self.thin_face = self.parent_face.parent_filament.parent_lattice.\
                resolve_address(xbd['thin_face'])
        if xbd['bound_to'] is None:
            self.bound_to = None
        else:
            self.bound_to = self.parent_face.parent_filament.parent_lattice.\
                resolve_address(xbd['bound_to'])

    @property
    def timestep(self):
        """Timestep size is stored at the half-sarcomere level"""
        return self.parent_face.parent_filament.parent_lattice.timestep_len

    def transition(self):
        """Gather the needed information and try a transition

        Parameters:
            None
        Returns:
            transition: string of transition ('12', '32', etc.) or None
        """
        # When unbound, try to bind, otherwise just try a transition
        if self.bound_to is None:
            # Find the lattice spacing
            lattice_spacing = self._get_lattice_spacing()
            # Find this cross-bridge's axial location
            xb_axial_loc = self.axial_location
            # Find the potential binding site
            actin_site = self.thin_face.nearest(xb_axial_loc)
            actin_axial_loc = actin_site.axial_location
            actin_state = actin_site.permissiveness
            # Find the axial separation
            axial_sep = actin_axial_loc - xb_axial_loc
            # Combine the two distances
            distance_to_site = (axial_sep, lattice_spacing)
            # Allow the myosin head to take it from here
            trans = super(Crossbridge, self).transition(distance_to_site,
                                                        actin_state)
            # Process changes to bound state
            if trans == '12':
                self.bound_to = actin_site
                actin_site.bind_to(self)
            else:
                assert (trans is None), 'Bound state mismatch'
        else:
            # Get the distance to the actin site
            distance_to_site = self._dist_to_bound_actin()
            actin_state = self.bound_to.permissiveness
            # Allow the myosin head to take it from here
            trans = super(Crossbridge, self).transition(distance_to_site,
                                                        actin_state)
            # Process changes to the bound state
            if trans in set(('21', '31')):
                self.bound_to.bind_to(None)
                self.bound_to = None
            else:
                assert (trans in set(('23', '32', None))) , 'State mismatch'
        return trans

    def axialforce(self, base_axial_loc=None, tip_axial_loc = None):
        """Gather needed information and return the axial force

        Parameters:
            base_axial_location: location of the crown (optional)
            tip_axial_loc: location of an attached actin node (optional)
        Returns:
            f_x: the axial force generated by the cross-bridge
        """
        # Unbound? No force!
        if self.bound_to is None:
            return 0.0
        # Else, get the distance to the bound site and run with it
        distance = self._dist_to_bound_actin(base_axial_loc, tip_axial_loc)
        # Allow the myosin head to take it from here
        return super(Crossbridge, self).axialforce(distance)

    def radialforce(self):
        """Gather needed information and return the radial force

        Parameters:
            None
        Returns:
            f_y: the radial force generated by the cross-bridge
        """
        # Unbound? No force!
        if self.bound_to is None:
            return 0.0
        # Else, get the distance to the bound site and run with it
        distance_to_site = self._dist_to_bound_actin()
        # Allow the myosin head to take it from here
        return super(Crossbridge, self).radialforce(distance_to_site)

    @property
    def axial_location(self):
        """Find the axial location of the thick filament attachment point

        Parameters:
            None
        Returns:
            axial: the axial location of the cross-bridge base
        """
        axial = self.parent_face.get_axial_location(self.index)
        return axial

    def _dist_to_bound_actin(self, xb_axial_loc=None, tip_axial_loc=None):

        """Find the (x,y) distance to the bound actin
        This is the distance format used by the myosin head.
        Parameters:
            xb_axial_loc: current axial location of the crown (optional)
            tip_axial_loc: location of an attached actin node (optional)
        Returns:
            (x,y): the axial distance between the cross-bridge base and
                   the actin site (x), and the lattice spacing (y)
        """
        # Are you really bound?
        assert (self.bound_to is not None) , "Lies, you're unbound!"
        # Find the lattice spacing
        lattice_spacing = self._get_lattice_spacing()
        # Find this cross-bridge's axial location if need be
        if xb_axial_loc is None:
            xb_axial_loc = self.axial_location
        # Find the distance to the bound actin site if need be
        if tip_axial_loc is None:
            tip_axial_loc = self.bound_to.axial_location
        # Combine the two distances
        return (tip_axial_loc - xb_axial_loc, lattice_spacing)

    def _get_lattice_spacing(self):
        """Ask our superiors for lattice spacing data"""
        return self.parent_face.lattice_spacing

if __name__ == '__main__':
    print("mh.py is really meant to be called as a supporting module")


text:
package org.neo4j.graphalgo.algo;

import com.carrotsearch.hppc.IntIntScatterMap;
import com.carrotsearch.hppc.IntSet;
import com.carrotsearch.hppc.ObjectArrayList;
import com.carrotsearch.hppc.cursors.IntIntCursor;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.neo4j.graphalgo.StronglyConnectedComponentsProc;
import org.neo4j.graphalgo.api.Graph;
import org.neo4j.graphalgo.core.GraphLoader;
import org.neo4j.graphalgo.core.heavyweight.HeavyGraphFactory;
import org.neo4j.graphalgo.impl.SCCIterativeTarjan;
import org.neo4j.graphalgo.impl.SCCTunedTarjan;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
import org.neo4j.kernel.api.exceptions.KernelException;
import org.neo4j.kernel.impl.proc.Procedures;
import org.neo4j.kernel.internal.GraphDatabaseAPI;
import org.neo4j.test.TestGraphDatabaseFactory;

import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;

/**        _______
 *        /       \
 *      (0)--(1) (3)--(4)
 *        \  /     \ /
 *        (2)  (6) (5)
 *             / \
 *           (7)-(8)
 *
 * @author mknblch
 */
public class IterativeTarjanSCCTest {

    private static GraphDatabaseAPI api;

    private static Graph graph;

    @BeforeClass
    public static void setup() throws KernelException {
        final String cypher =
                "CREATE (a:Node {name:'a'})\n" +
                        "CREATE (b:Node {name:'b'})\n" +
                        "CREATE (c:Node {name:'c'})\n" +
                        "CREATE (d:Node {name:'d'})\n" +
                        "CREATE (e:Node {name:'e'})\n" +
                        "CREATE (f:Node {name:'f'})\n" +
                        "CREATE (g:Node {name:'g'})\n" +
                        "CREATE (h:Node {name:'h'})\n" +
                        "CREATE (i:Node {name:'i'})\n" +
                        "CREATE" +
                        " (a)-[:TYPE {cost:5}]->(b),\n" +
                        " (b)-[:TYPE {cost:5}]->(c),\n" +
                        " (c)-[:TYPE {cost:5}]->(a),\n" +

                        " (d)-[:TYPE {cost:2}]->(e),\n" +
                        " (e)-[:TYPE {cost:2}]->(f),\n" +
                        " (f)-[:TYPE {cost:2}]->(d),\n" +

                        " (a)-[:TYPE {cost:2}]->(d),\n" +

                        " (g)-[:TYPE {cost:3}]->(h),\n" +
                        " (h)-[:TYPE {cost:3}]->(i),\n" +
                        " (i)-[:TYPE {cost:3}]->(g)";

        api = (GraphDatabaseAPI)
                new TestGraphDatabaseFactory()
                        .newImpermanentDatabaseBuilder()
                        .newGraphDatabase();

        api.getDependencyResolver()
                .resolveDependency(Procedures.class)
                .registerProcedure(StronglyConnectedComponentsProc.class);

        try (Transaction tx = api.beginTx()) {
            api.execute(cypher);
            tx.success();
        }

        graph = new GraphLoader(api)
                .withLabel("Node")
                .withRelationshipType("TYPE")
                .withRelationshipWeightsFromProperty("cost", Double.MAX_VALUE)
                .load(HeavyGraphFactory.class);
    }

    @AfterClass
    public static void shutdownGraph() throws Exception {
        api.shutdown();
    }

    public static int getMappedNodeId(String name) {
        final Node[] node = new Node[1];
        api.execute("MATCH (n:Node) WHERE n.name = '" + name + "' RETURN n").accept(row -> {
            node[0] = row.getNode("n");
            return false;
        });
        return graph.toMappedNodeId(node[0].getId());
    }

    @Test
    public void testDirect() throws Exception {

        final SCCIterativeTarjan tarjan = new SCCIterativeTarjan(graph)
                .compute();

        assertCC(tarjan.getConnectedComponents());
        assertEquals(3, tarjan.getMaxSetSize());
        assertEquals(3, tarjan.getMinSetSize());
        assertEquals(3, tarjan.getSetCount());
    }

    @Test
    public void testCypher() throws Exception {

        String cypher = "CALL algo.scc.iterative('', '', {write:true}) YIELD loadMillis, computeMillis, writeMillis";

        api.execute(cypher).accept(row -> {
            final long loadMillis = row.getNumber("loadMillis").longValue();
            final long computeMillis = row.getNumber("computeMillis").longValue();
            final long writeMillis = row.getNumber("writeMillis").longValue();
            assertNotEquals(-1, loadMillis);
            assertNotEquals(-1, computeMillis);
            assertNotEquals(-1, writeMillis);
            return true;
        });

        String cypher2 = "MATCH (n) RETURN n.partition as c";
        final IntIntScatterMap testMap = new IntIntScatterMap();
        api.execute(cypher2).accept(row -> {
            testMap.addTo(row.getNumber("c").intValue(), 1);
            return true;
        });

        // 3 sets with 3 elements each
        assertEquals(3, testMap.size());
        for (IntIntCursor cursor : testMap) {
            assertEquals(3, cursor.value);
        }
    }

    @Test
    public void testCypherStream() throws Exception {

        final IntIntScatterMap testMap = new IntIntScatterMap();

        String cypher = "CALL algo.scc.iterative.stream() YIELD nodeId, partition";

        api.execute(cypher).accept(row -> {
            testMap.addTo(row.getNumber("partition").intValue(), 1);
            return true;
        });

        // 3 sets with 3 elements each
        assertEquals(3, testMap.size());
        for (IntIntCursor cursor : testMap) {
            assertEquals(3, cursor.value);
        }
    }

    private void assertCC(int[] connectedComponents) {
        assertBelongSameSet(connectedComponents,
                getMappedNodeId("a"),
                getMappedNodeId("b"),
                getMappedNodeId("c"));
        assertBelongSameSet(connectedComponents,
                getMappedNodeId("d"),
                getMappedNodeId("e"),
                getMappedNodeId("f"));
        assertBelongSameSet(connectedComponents,
                getMappedNodeId("g"),
                getMappedNodeId("h"),
                getMappedNodeId("i"));
    }

    private static void assertBelongSameSet(int[] data, Integer... expected) {
        // check if all belong to same set
        final int needle = data[expected[0]];
        for (int i : expected) {
            assertEquals(needle, data[i]);
        }

        final List<Integer> exp = Arrays.asList(expected);
        // check no other element belongs to this set
        for (int i = 0; i < data.length; i++) {
            if (exp.contains(i)) {
                continue;
            }
            assertNotEquals(needle, data[i]);
        }

    }
}


text:
// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

namespace MartinCostello.AdventOfCode.Puzzles.Y2019;

/// <summary>
/// A class representing the puzzle for <c>https://adventofcode.com/2019/day/13</c>. This class cannot be inherited.
/// </summary>
[Puzzle(2019, 13, "Care Package", RequiresData = true)]
public sealed class Day13 : Puzzle
{
    /// <summary>
    /// Gets the number of block tiles on the screen.
    /// </summary>
    public long BlockTileCount { get; private set; }

    /// <summary>
    /// Gets the score when the game ends.
    /// </summary>
    public long Score { get; private set; }

    /// <summary>
    /// Gets the number of block tiles on the screen after the game is run.
    /// </summary>
    /// <param name="program">The Intcode program to run.</param>
    /// <param name="cancellationToken">The cancellation token to use.</param>
    /// <returns>
    /// The number of block tiles on the screen.
    /// </returns>
    public static async Task<(long BlockTileCount, long Score)> PlayGameAsync(
        string program,
        CancellationToken cancellationToken)
    {
        long[] instructions = IntcodeVM.ParseProgram(program);

        var vm = new IntcodeVM(instructions, 10_000)
        {
            Input = await ChannelHelpers.CreateReaderAsync(new[] { 2L }, cancellationToken),
        };

        if (!await vm.RunAsync(cancellationToken))
        {
            throw new PuzzleException("Failed to run program.");
        }

        var outputs = await vm.Output.ToListAsync(cancellationToken);

        var grid = new Dictionary<Point, int>(outputs.Count);

        long score = 0;

        for (int i = 0; i < outputs.Count; i += 3)
        {
            long x = outputs[i];
            long y = outputs[i + 1];
            long tileId = outputs[i + 2];

            if (x == 1 && y == 0)
            {
                score = tileId;
            }
            else
            {
                grid[new((int)x, (int)y)] = (int)tileId;
            }
        }

        int initialBlockCount = grid.Values.Count((p) => p == 2);

        return (initialBlockCount, score);
    }

    /// <inheritdoc />
    protected override async Task<PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        string program = await ReadResourceAsStringAsync();

        (BlockTileCount, Score) = await PlayGameAsync(program, cancellationToken);

        if (Verbose)
        {
            Logger.WriteLine("There are {0} block tiles on the screen when the game exits.", BlockTileCount);
            Logger.WriteLine("The score after the last block is broken is {0}", Score);
        }

        return PuzzleResult.Create(BlockTileCount/*, Score*/);
    }
}


text:
<?php

final class ArcanistDynamicDefineXHPASTLinterRule
  extends ArcanistXHPASTLinterRule {

  const ID = 12;

  public function getLintName() {
    return pht('Dynamic %s', 'define()');
  }

  public function process(XHPASTNode $root) {
    $calls = $this->getFunctionCalls($root, array('define'));

    foreach ($calls as $call) {
      $parameter_list = $call->getChildOfType(1, 'n_CALL_PARAMETER_LIST');
      $defined = $parameter_list->getChildByIndex(0);

      if (!$defined->isStaticScalar()) {
        $this->raiseLintAtNode(
          $defined,
          pht(
            'First argument to %s must be a string literal.',
            'define()'));
      }
    }
  }

}


text:
from __future__ import unicode_literals

import django.core.validators
from django.db import migrations, models

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Token',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('public_name', models.CharField(max_length=200)),
                ('symbol', models.CharField(max_length=4)),
                ('decimals', models.IntegerField(default=18, validators=[django.core.validators.MaxValueValidator(20), django.core.validators.MinValueValidator(0)])),
                ('phase', models.CharField(choices=[('PHASE_01', 'In review'), ('PHASE_02', 'Active'), ('PHASE_02', 'Inactive')], default='PHASE_01', max_length=8)),
            ],
        ),
    ]


text:
<?php

declare(strict_types=1);

namespace JMS\Serializer\Tests\Fixtures\TypedProperties;

use JMS\Serializer\Annotation as Serializer;

class User
{
    public int $id;
    public Role $role;
    public Vehicle $vehicle;
    public \DateTime $created;

    /**
     * @Serializer\ReadOnlyProperty()
     */
    #[Serializer\ReadOnlyProperty]
    public ?\DateTimeInterface $updated = null;

    /**
     * @Serializer\ReadOnlyProperty()
     */
    #[Serializer\ReadOnlyProperty]
    public iterable $tags = [];
}