text:
"""
Implements the `LockManager` object that provides the locking functionality.

The LockManager requires a LockStorageDict object to implement persistence.
Two alternative lock storage classes are defined in the lock_storage module:

- wsgidav.lock_man.lock_storage.LockStorageDict
- wsgidav.lock_man.lock_storage.LockStorageShelve

The lock data model is a dictionary with these fields:

    root:
        Resource URL.
    principal:
        Name of the authenticated user that created the lock.
    type:
        Must be 'write'.
    scope:
        Must be 'shared' or 'exclusive'.
    depth:
        Must be '0' or 'infinity'.
    owner:
        String identifying the owner.
    timeout:
        Seconds remaining until lock expiration.
        This value is passed to create() and refresh()
    expire:
        Converted timeout for persistence: expire = time() + timeout.
    token:
        Automatically generated unique token.

"""
import random
import time
from pprint import pformat

from wsgidav import util
from wsgidav.dav_error import (
    HTTP_LOCKED,
    DAVError,
    DAVErrorCondition,
    PRECONDITION_CODE_LockConflict,
)
from wsgidav.rw_lock import ReadWriteLock

__docformat__ = "reStructuredText"

_logger = util.get_module_logger("wsgidav.lock_man")

# ========================================================================
# Tool functions
# ========================================================================

def generate_lock_token():
    return "opaquelocktoken:" + util.to_str(hex(random.getrandbits(256)))

def normalize_lock_root(path):
    # Normalize root: /foo/bar
    assert path
    path = util.to_str(path)
    path = "/" + path.strip("/")
    return path

def is_lock_expired(lock):
    expire = float(lock["expire"])
    return expire >= 0 and expire < time.time()

def lock_string(lock_dict):
    """Return readable rep."""
    if not lock_dict:
        return "Lock: None"

    if lock_dict["expire"] < 0:
        expire = "Infinite ({})".format(lock_dict["expire"])
    else:
        expire = "{} (in {} seconds)".format(
            util.get_log_time(lock_dict["expire"]), lock_dict["expire"] - time.time()
        )

    return "Lock(<{}..>, '{}', {}, {}, depth-{}, until {}".format(
        # first 4 significant token characters
        lock_dict.get("token", "?" * 30)[18:22],
        lock_dict.get("root"),
        lock_dict.get("principal"),
        lock_dict.get("scope"),
        lock_dict.get("depth"),
        expire,
    )

def validate_lock(lock):
    assert util.is_str(lock["root"])
    assert lock["root"].startswith("/")
    assert lock["type"] == "write"
    assert lock["scope"] in ("shared", "exclusive")
    assert lock["depth"] in ("0", "infinity")
    assert util.is_bytes(lock["owner"]), lock  # XML bytestring
    # raises TypeError:
    timeout = float(lock["timeout"])
    assert timeout > 0 or timeout == -1, "timeout must be positive or -1"
    assert util.is_str(lock["principal"])
    if "token" in lock:
        assert util.is_str(lock["token"])

# ========================================================================
# LockManager
# ========================================================================
class LockManager:
    """
    Implements locking functionality using a custom storage layer.

    """

    LOCK_TIME_OUT_DEFAULT = 604800  # 1 week, in seconds

    def __init__(self, storage):
        """
        storage:
            LockManagerStorage object
        """
        assert hasattr(storage, "get_lock_list")
        self._lock = ReadWriteLock()
        self.storage = storage
        self.storage.open()

    def __del__(self):
        self.storage.close()

    def __repr__(self):
        return "{}({!r})".format(self.__class__.__name__, self.storage)

    def _dump(self, msg=""):
        urlDict = {}  # { <url>: [<tokenlist>] }
        ownerDict = {}  # { <LOCKOWNER>: [<tokenlist>] }
        userDict = {}  # { <LOCKUSER>: [<tokenlist>] }
        tokenDict = {}  # { <token>: <LOCKURLS> }

        _logger.info("{}: {}".format(self, msg))

        for lock in self.storage.get_lock_list(
            "/", include_root=True, include_children=True, token_only=False
        ):
            tok = lock["token"]
            tokenDict[tok] = lock_string(lock)
            userDict.setdefault(lock["principal"], []).append(tok)
            ownerDict.setdefault(lock["owner"], []).append(tok)
            urlDict.setdefault(lock["root"], []).append(tok)

        _logger.info("Locks:\n{}".format(pformat(tokenDict, indent=0, width=255)))
        if tokenDict:
            _logger.info(
                "Locks by URL:\n{}".format(pformat(urlDict, indent=4, width=255))
            )
            _logger.info(
                "Locks by principal:\n{}".format(pformat(userDict, indent=4, width=255))
            )
            _logger.info(
                "Locks by owner:\n{}".format(pformat(ownerDict, indent=4, width=255))
            )

    def _generate_lock(
        self, principal, lock_type, lock_scope, lock_depth, lock_owner, path, timeout
    ):
        """Acquire lock and return lock_dict.

        principal
            Name of the principal.
        lock_type
            Must be 'write'.
        lock_scope
            Must be 'shared' or 'exclusive'.
        lock_depth
            Must be '0' or 'infinity'.
        lock_owner
            String identifying the owner.
        path
            Resource URL.
        timeout
            Seconds to live

        This function does NOT check, if the new lock creates a conflict!
        """
        if timeout is None:
            timeout = LockManager.LOCK_TIME_OUT_DEFAULT
        elif timeout < 0:
            timeout = -1

        lock_dict = {
            "root": path,
            "type": lock_type,
            "scope": lock_scope,
            "depth": lock_depth,
            "owner": lock_owner,
            "timeout": timeout,
            "principal": principal,
        }
        #
        self.storage.create(path, lock_dict)
        return lock_dict

    def acquire(
        self,
        *,
        url,
        lock_type,
        lock_scope,
        lock_depth,
        lock_owner,
        timeout,
        principal,
        token_list,
    ):
        """Check for permissions and acquire a lock.

        On success return new lock dictionary.
        On error raise a DAVError with an embedded DAVErrorCondition.
        """
        url = normalize_lock_root(url)
        self._lock.acquire_write()
        try:
            # Raises DAVError on conflict:
            self._check_lock_permission(
                url, lock_type, lock_scope, lock_depth, token_list, principal
            )
            return self._generate_lock(
                principal, lock_type, lock_scope, lock_depth, lock_owner, url, timeout
            )
        finally:
            self._lock.release()

    def refresh(self, token, *, timeout=None):
        """Set new timeout for lock, if existing and valid."""
        if timeout is None:
            timeout = LockManager.LOCK_TIME_OUT_DEFAULT
        return self.storage.refresh(token, timeout=timeout)

    def get_lock(self, token, *, key=None):
        """Return lock_dict, or None, if not found or invalid.

        Side effect: if lock is expired, it will be purged and None is returned.

        key:
            name of lock attribute that will be returned instead of a dictionary.
        """
        assert key in (
            None,
            "type",
            "scope",
            "depth",
            "owner",
            "root",
            "timeout",
            "principal",
            "token",
        )
        lock = self.storage.get(token)
        if key is None or lock is None:
            return lock
        return lock[key]

    def release(self, token):
        """Delete lock."""
        self.storage.delete(token)

    def is_token_locked_by_user(self, token, principal):
        """Return True, if <token> exists, is valid, and bound to <principal>."""
        return self.get_lock(token, key="principal") == principal

    def get_url_lock_list(self, url, *, recursive=False):
        """Return list of lock_dict, if <url> is protected by at least one direct, valid lock.

        Side effect: expired locks for this url are purged.
        """
        url = normalize_lock_root(url)
        lockList = self.storage.get_lock_list(
            url, include_root=True, include_children=recursive, token_only=False
        )
        return lockList

    def get_indirect_url_lock_list(self, url, *, principal=None):
        """Return a list of valid lockDicts, that protect <path> directly or indirectly.

        If a principal is given, only locks owned by this principal are returned.
        Side effect: expired locks for this path and all parents are purged.
        """
        url = normalize_lock_root(url)
        lockList = []
        u = url
        while u:
            lock_list = self.storage.get_lock_list(
                u, include_root=True, include_children=False, token_only=False
            )
            for lock in lock_list:
                if u != url and lock["depth"] != "infinity":
                    continue  # We only consider parents with Depth: infinity
                # TODO: handle shared locks in some way?
                #                if (lock["scope"] == "shared" and lock_scope == "shared"
                #                   and principal != lock["principal"]):
                # continue  # Only compatible with shared locks by other users
                if principal is None or principal == lock["principal"]:
                    lockList.append(lock)
            u = util.get_uri_parent(u)
        return lockList

    def is_url_locked(self, url):
        """Return True, if url is directly locked."""
        lockList = self.get_url_lock_list(url)
        return len(lockList) > 0

    def is_url_locked_by_token(self, url, lock_token):
        """Check, if url (or any of it's parents) is locked by lock_token."""
        lockUrl = self.get_lock(lock_token, key="root")
        return lockUrl and util.is_equal_or_child_uri(lockUrl, url)

    def remove_all_locks_from_url(self, url, *, recursive=False):
        self._lock.acquire_write()
        try:
            lockList = self.get_url_lock_list(url, recursive=recursive)
            for lock in lockList:
                self.release(lock["token"])
        finally:
            self._lock.release()

    def _check_lock_permission(
        self, url, lock_type, lock_scope, lock_depth, token_list, principal
    ):
        """Check, if <principal> can lock <url>, otherwise raise an error.

        If locking <url> would create a conflict, DAVError(HTTP_LOCKED) is
        raised. An embedded DAVErrorCondition contains the conflicting resource.

        @see http://www.webdav.org/specs/rfc4918.html#lock-model

        - Parent locks WILL NOT be conflicting, if they are depth-0.
        - Exclusive depth-infinity parent locks WILL be conflicting, even if
          they are owned by <principal>.
        - Child locks WILL NOT be conflicting, if we request a depth-0 lock.
        - Exclusive child locks WILL be conflicting, even if they are owned by
          <principal>. (7.7)
        - It is not enough to check whether a lock is owned by <principal>, but
          also the token must be passed with the request. (Because <principal>
          may run two different applications on his client.)
        - <principal> cannot lock-exclusive, if he holds a parent shared-lock.
          (This would only make sense, if he was the only shared-lock holder.)
        - TODO: litmus tries to acquire a shared lock on one resource twice
          (locks: 27 'double_sharedlock') and fails, when we return HTTP_LOCKED.
          So we allow multi shared locks on a resource even for the same
          principal.

        @param url: URL that shall be locked
        @param lock_type: "write"
        @param lock_scope: "shared"|"exclusive"
        @param lock_depth: "0"|"infinity"
        @param token_list: list of lock tokens, that the user submitted in If: header
        @param principal: name of the principal requesting a lock

        @return: None (or raise)
        """
        assert lock_type == "write"
        assert lock_scope in ("shared", "exclusive")
        assert lock_depth in ("0", "infinity")

        _logger.debug(
            "checkLockPermission({}, {}, {}, {})".format(
                url, lock_scope, lock_depth, principal
            )
        )

        # Error precondition to collect conflicting URLs
        errcond = DAVErrorCondition(PRECONDITION_CODE_LockConflict)

        self._lock.acquire_read()
        try:
            # Check url and all parents for conflicting locks
            u = url
            while u:
                lock_list = self.get_url_lock_list(u)
                for lock in lock_list:
                    _logger.debug(
                        "    check parent {}, {}".format(u, lock_string(lock))
                    )
                    if u != url and lock["depth"] != "infinity":
                        # We only consider parents with Depth: infinity
                        continue
                    elif lock["scope"] == "shared" and lock_scope == "shared":
                        # Only compatible with shared locks (even by same
                        # principal)
                        continue
                    # Lock conflict
                    _logger.debug(
                        " -> DENIED due to locked parent {}".format(lock_string(lock))
                    )
                    errcond.add_href(lock["root"])
                u = util.get_uri_parent(u)

            if lock_depth == "infinity":
                # Check child URLs for conflicting locks
                child_ocks = self.storage.get_lock_list(
                    url, include_root=False, include_children=True, token_only=False
                )

                for lock in child_ocks:
                    assert util.is_child_uri(url, lock["root"])
                    #                    if util.is_child_uri(url, lock["root"]):
                    _logger.debug(
                        " -> DENIED due to locked child {}".format(lock_string(lock))
                    )
                    errcond.add_href(lock["root"])
        finally:
            self._lock.release()

        # If there were conflicts, raise HTTP_LOCKED for <url>, and pass
        # conflicting resource with 'no-conflicting-lock' precondition
        if len(errcond.hrefs) > 0:
            raise DAVError(HTTP_LOCKED, err_condition=errcond)
        return

    def check_write_permission(self, *, url, depth, token_list, principal):
        """Check, if <principal> can modify <url>, otherwise raise HTTP_LOCKED.

        If modifying <url> is prevented by a lock, DAVError(HTTP_LOCKED) is
        raised. An embedded DAVErrorCondition contains the conflicting locks.

        <url> may be modified by <principal>, if it is not currently locked
        directly or indirectly (i.e. by a locked parent).
        For depth-infinity operations, <url> also must not have locked children.

        It is not enough to check whether a lock is owned by <principal>, but
        also the token must be passed with the request. Because <principal> may
        run two different applications.

        See http://www.webdav.org/specs/rfc4918.html#lock-model
            http://www.webdav.org/specs/rfc4918.html#rfc.section.7.4

        TODO: verify assumptions:
        - Parent locks WILL NOT be conflicting, if they are depth-0.
        - Exclusive child locks WILL be conflicting, even if they are owned by <principal>.

        @param url: URL that shall be modified, created, moved, or deleted
        @param depth: "0"|"infinity"
        @param token_list: list of lock tokens, that the principal submitted in If: header
        @param principal: name of the principal requesting a lock

        @return: None or raise error
        """
        assert util.is_str(url)
        assert depth in ("0", "infinity")
        _logger.debug(
            "check_write_permission({}, {}, {}, {})".format(
                url, depth, token_list, principal
            )
        )

        # Error precondition to collect conflicting URLs
        errcond = DAVErrorCondition(PRECONDITION_CODE_LockConflict)

        self._lock.acquire_read()
        try:
            # Check url and all parents for conflicting locks
            u = url
            while u:
                lock_list = self.get_url_lock_list(u)
                _logger.debug("  checking {}".format(u))
                for lock in lock_list:
                    _logger.debug("     lock={}".format(lock_string(lock)))
                    if u != url and lock["depth"] != "infinity":
                        # We only consider parents with Depth: inifinity
                        continue
                    elif principal == lock["principal"] and lock["token"] in token_list:
                        # User owns this lock
                        continue
                    else:
                        # Token is owned by principal, but not passed with lock list
                        _logger.debug(
                            " -> DENIED due to locked parent {}".format(
                                lock_string(lock)
                            )
                        )
                        errcond.add_href(lock["root"])
                u = util.get_uri_parent(u)

            if depth == "infinity":
                # Check child URLs for conflicting locks
                child_ocks = self.storage.get_lock_list(
                    url, include_root=False, include_children=True, token_only=False
                )

                for lock in child_ocks:
                    assert util.is_child_uri(url, lock["root"])
                    #                    if util.is_child_uri(url, lock["root"]):
                    _logger.debug(
                        " -> DENIED due to locked child {}".format(lock_string(lock))
                    )
                    errcond.add_href(lock["root"])
        finally:
            self._lock.release()

        # If there were conflicts, raise HTTP_LOCKED for <url>, and pass
        # conflicting resource with 'no-conflicting-lock' precondition
        if len(errcond.hrefs) > 0:
            raise DAVError(HTTP_LOCKED, err_condition=errcond)
        return


text:
package org.deidentifier.arx.examples;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;

import org.deidentifier.arx.ARXAnonymizer;
import org.deidentifier.arx.ARXConfiguration;
import org.deidentifier.arx.ARXResult;
import org.deidentifier.arx.AttributeType;
import org.deidentifier.arx.AttributeType.Hierarchy;
import org.deidentifier.arx.AttributeType.Hierarchy.DefaultHierarchy;
import org.deidentifier.arx.Data;
import org.deidentifier.arx.Data.DefaultData;
import org.deidentifier.arx.DataSubset;
import org.deidentifier.arx.criteria.KMap;
import org.deidentifier.arx.metric.Metric;

/**
 * This class implements an example on how to use the k-map model
 *
 * @author Fabian Prasser
 */
public class Example41 extends Example {

    /**
     * Entry point.
     *
     * @param args
     *            the arguments
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {

        // Define public dataset
        DefaultData data = Data.create();
        data.add("identifier", "name", "zip", "age", "nationality", "sen");
        data.add("a", "Alice", "47906", "35", "USA", "0");
        data.add("b", "Bob", "47903", "59", "Canada", "1");
        data.add("c", "Christine", "47906", "42", "USA", "1");
        data.add("d", "Dirk", "47630", "18", "Brazil", "0");
        data.add("e", "Eunice", "47630", "22", "Brazil", "0");
        data.add("f", "Frank", "47633", "63", "Peru", "1");
        data.add("g", "Gail", "48973", "33", "Spain", "0");
        data.add("h", "Harry", "48972", "47", "Bulgaria", "1");
        data.add("i", "Iris", "48970", "52", "France", "1");

        // Define research subset
        DataSubset subset = DataSubset.create(data, new HashSet<Integer>(Arrays.asList(1, 2, 5, 7, 8)));

        // Define hierarchies
        DefaultHierarchy age = Hierarchy.create();
        age.add("18", "1*", "<=40", "*");
        age.add("22", "2*", "<=40", "*");
        age.add("33", "3*", "<=40", "*");
        age.add("35", "3*", "<=40", "*");
        age.add("42", "4*", ">40", "*");
        age.add("47", "4*", ">40", "*");
        age.add("52", "5*", ">40", "*");
        age.add("59", "5*", ">40", "*");
        age.add("63", "6*", ">40", "*");

        DefaultHierarchy nationality = Hierarchy.create();
        nationality.add("Canada", "N. America", "America", "*");
        nationality.add("USA", "N. America", "America", "*");
        nationality.add("Peru", "S. America", "America", "*");
        nationality.add("Brazil", "S. America", "America", "*");
        nationality.add("Bulgaria", "E. Europe", "Europe", "*");
        nationality.add("France", "W. Europe", "Europe", "*");
        nationality.add("Spain", "W. Europe", "Europe", "*");

        DefaultHierarchy zip = Hierarchy.create();
        zip.add("47630", "4763*", "476*", "47*", "4*", "*");
        zip.add("47633", "4763*", "476*", "47*", "4*", "*");
        zip.add("47903", "4790*", "479*", "47*", "4*", "*");
        zip.add("47906", "4790*", "479*", "47*", "4*", "*");
        zip.add("48970", "4897*", "489*", "48*", "4*", "*");
        zip.add("48972", "4897*", "489*", "48*", "4*", "*");
        zip.add("48973", "4897*", "489*", "48*", "4*", "*");

        // Set data attribute types
        data.getDefinition().setAttributeType("identifier", AttributeType.IDENTIFYING_ATTRIBUTE);
        data.getDefinition().setAttributeType("name", AttributeType.IDENTIFYING_ATTRIBUTE);
        data.getDefinition().setAttributeType("zip", zip);
        data.getDefinition().setAttributeType("age", age);
        data.getDefinition().setAttributeType("nationality", nationality);
        data.getDefinition().setAttributeType("sen", AttributeType.INSENSITIVE_ATTRIBUTE);

        // Create an instance of the anonymizer
        ARXAnonymizer anonymizer = new ARXAnonymizer();
        ARXConfiguration config = ARXConfiguration.create();
        config.addCriterion(new KMap(3, subset));
        config.setMaxOutliers(1d);
        config.setMetric(Metric.createLossMetric());

        // Now anonymize
        ARXResult result = anonymizer.anonymize(data, config);

        // Print input
        System.out.println(" - Input data:");
        print(data.getHandle().iterator());

        // Print input
        System.out.println(" - Input research subset:");
        print(data.getHandle().getView().iterator());

        // Print info
        printResult(result, data);

        // Print results
        System.out.println(" - Transformed data:");
        print(result.getOutput(false).iterator());

        // Print results
        System.out.println(" - Transformed research subset:");
        print(result.getOutput(false).getView().iterator());
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.thebluealliance.androidclient.datafeed;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.thebluealliance.androidclient.helpers.JSONHelper;
import com.thebluealliance.androidclient.models.Award;
import com.thebluealliance.androidclient.models.Event;
import com.thebluealliance.androidclient.models.Media;
import com.thebluealliance.androidclient.models.Team;
import com.thebluealliance.androidclient.types.EventType;
import com.thebluealliance.androidclient.types.MediaType;

import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;

import java.util.ArrayList;
import java.util.Date;

import static org.junit.Assert.assertEquals;

@Ignore
@RunWith(RobolectricTestRunner.class)
public class TBAApiTest {

    @org.junit.Test
    public void testParseEvent() {
        String eventJson = "{\"key\": \"2014ctgro\", \"end_date\": \"2014-03-09\", \"name\": \"Groton District Event\", \"short_name\": \"Groton\", \"facebook_eid\": null, \"official\": true, \"location\": \"Groton, CT, USA\", \"event_code\": \"ctgro\", \"year\": 2014, \"event_type_string\": \"District\", \"start_date\": \"2014-03-08\", \"event_type\": 1}";
        Event event = JSONHelper.getGson().fromJson(eventJson, Event.class);

        //now, assert that all the properties are there
        assertEquals(event.getKey(), "2014ctgro");
        assertEquals(event.getStartDate().getTime(), new Date(114, 2, 8).getTime());
        assertEquals(event.getEndDate().getTime(), new Date(114, 2, 9).getTime());
        assertEquals(event.getName(), "Groton District Event");
        assertEquals(event.getShortName(), "Groton");
        assertEquals(event.getAddress(), "Groton, CT, USA");
        assertEquals(event.getEventTypeEnum(), EventType.DISTRICT);
    }

    @org.junit.Test
    public void testParseTeam() {
        String teamJson = "{\n"
                + "  \"website\": \"http://www.uberbots.org\",\n"
                + "  \"name\": \"UTC Fire and Security & Avon High School\",\n"
                + "  \"locality\": \"Avon\",\n"
                + "  \"rookie_year\": 2003,\n"
                + "  \"region\": \"CT\",\n"
                + "  \"team_number\": 1124,\n"
                + "  \"location\": \"Avon, CT, USA\",\n"
                + "  \"key\": \"frc1124\",\n"
                + "  \"country_name\": \"USA\",\n"
                + "  \"nickname\": \"ÜberBots\"\n"
                + "}";
        Team team = JSONHelper.getGson().fromJson(teamJson, Team.class);

        assertEquals(team.getWebsite(), "http://www.uberbots.org");
        assertEquals(team.getName(), "UTC Fire and Security & Avon High School");
        assertEquals(team.getAddress(), "Avon, CT, USA");
        assertEquals((int) team.getTeamNumber(), 1124);
        assertEquals(team.getKey(), "frc1124");
        assertEquals(team.getNickname(), "ÜberBots");
    }

    @org.junit.Test
    public void testParseMedia() {
        String mediaJson = "["
                + "  {"
                + "    \"type\": \"cdphotothread\","
                + "    \"details\": {"
                + "      \"image_partial\": \"fe3/fe38d320428adf4f51ac969efb3db32c_l.jpg\""
                + "    },"
                + "    \"foreign_key\": \"39894\""
                + "  },"
                + "  {"
                + "    \"type\": \"youtube\","
                + "    \"details\": {},"
                + "    \"foreign_key\": \"RpSgUrsghv4\""
                + "  }"
                + "]";

        ArrayList<Media> medias = new ArrayList<>();
        JsonArray mediaArray = JSONHelper.getasJsonArray(mediaJson);
        for (JsonElement media : mediaArray) {
            medias.add(JSONHelper.getGson().fromJson(media, Media.class));
        }

        assertEquals(medias.size(), mediaArray.size());
        assertEquals(medias.size(), 2);

        Media cd = medias.get(0);
        Media yt = medias.get(1);
        assertEquals(cd.getForeignKey(), "39894");
        assertEquals(MediaType.fromString(cd.getType()), MediaType.CD_PHOTO_THREAD);
        assertEquals(cd.getDetailsJson(),
                     JSONHelper.getasJsonObject(
                             "{\"image_partial\": \"fe3/fe38d320428adf4f51ac969efb3db32c_l"
                             + ".jpg\"}"));

        assertEquals(MediaType.fromString(yt.getType()), MediaType.YOUTUBE);
        assertEquals(yt.getForeignKey(), "RpSgUrsghv4");
        assertEquals(yt.getDetailsJson(), new JsonObject());
    }

    @org.junit.Test
    public void testParseMatch() {
        /*
        String matchJson = "{\"comp_level\": \"f\", \"match_number\": 1, \"videos\": [{\"type\": \"youtube\", \"key\": \"ci6LicTg5rk\"}], \"time_string\": \"3:36 PM\", \"set_number\": 1, \"key\": \"2014ctgro_f1m1\", \"time\": \"1394393760\", \"alliances\": {\"blue\": {\"score\": 113, \"teams\": [\"frc1991\", \"frc230\", \"frc1699\"]}, \"red\": {\"score\": 120, \"teams\": [\"frc236\", \"frc237\", \"frc2064\"]}}, \"event_key\": \"2014ctgro\"}";
        Match match = JSONHelper.getGson().fromJson(matchJson, Match.class);

        assertEquals(match.getKey(), "2014ctgro_f1m1");
        assertEquals(match.getEventKey(), "2014ctgro");
        assertEquals(match.getMatchNumber().intValue(), 1);
        assertEquals(match.getSetNumber().intValue(), 1);
        assertEquals(MatchType.fromShortType(match.getCompLevel()), MatchType.FINAL);
        assertEquals(match.getAlliancesJson(),
                     JSONHelper.getasJsonObject(
                             "{\"blue\": {\"score\": 113, \"teams\": [\"frc1991\", \"frc230\", "
                             + "\"frc1699\"]}, \"red\": {\"score\": 120, \"teams\": [\"frc236\", "
                             + "\"frc237\", \"frc2064\"]}}"));
        assertEquals(match.getTime().longValue(), new Date(1394393760).getTime());
        assertEquals(match.getVideosJson(),
                     JSONHelper
                             .getasJsonArray("[{\"type\": \"youtube\", \"key\": \"ci6LicTg5rk\"}]"));
                             */
    }

    @org.junit.Test
    public void testParseAwardNoAwardee() {
        String json = "{\n"
                + "    \"event_key\": \"2010sc\",\n"
                + "    \"name\": \"Winner\",\n"
                + "    \"recipient_list\": [\n"
                + "      {\n"
                + "        \"team_number\": 343,\n"
                + "        \"awardee\": null\n"
                + "      },\n"
                + "      {\n"
                + "        \"team_number\": 1261,\n"
                + "        \"awardee\": null\n"
                + "      },\n"
                + "      {\n"
                + "        \"team_number\": 1398,\n"
                + "        \"awardee\": null\n"
                + "      }\n"
                + "    ],\n"
                + "    \"year\": 2010\n"
                + "  }";
        Award award = JSONHelper.getGson().fromJson(json, Award.class);

        assertEquals(award.getEventKey(), "2010sc");
        assertEquals(award.getName(), "Winner");
        assertEquals(award.getYear().intValue(), 2010);

        /*
        JsonArray recips = award.getWinners();
        String[] winners = {"343", "1261", "1398"};
        assertNotNull(recips);
        assertEquals(recips.size(), 3);
        for (int i = 0; i < 3; i++) {
            assertEquals(winners[i],
                         recips.get(i).getAsJsonObject().get("team_number").getAsString());
        }*/
    }

    @org.junit.Test
    public void testParseAwardNoTeam() {
        String json = "{\n"
                + "    \"event_key\": \"2010sc\",\n"
                + "    \"name\": \"FIRST Dean's List Finalist Award\",\n"
                + "    \"recipient_list\": [\n"
                + "      {\n"
                + "        \"team_number\": null,\n"
                + "        \"awardee\": \"Brandon Dean\"\n"
                + "      },\n"
                + "      {\n"
                + "        \"team_number\": null,\n"
                + "        \"awardee\": \"Megan Shew\"\n"
                + "      }\n"
                + "    ],\n"
                + "    \"year\": 2010\n"
                + "  }";
        Award award = JSONHelper.getGson().fromJson(json, Award.class);

        assertEquals(award.getEventKey(), "2010sc");
        assertEquals(award.getName(), "FIRST Dean's List Finalist Award");
        assertEquals(award.getYear().intValue(), 2010);
        /*
        JsonArray recips = award.getWinners();
        String[] winners = {"Brandon Dean", "Megan Shew"};
        assertNotNull(recips);
        assertEquals(recips.size(), 2);
        for (int i = 0; i < 2; i++) {
            assertEquals(winners[i], recips.get(i).getAsJsonObject().get("awardee").getAsString());
        }*/
    }

}


text:
namespace SequenceAssembler
{
    #region -- Using Directives --

    using System.Collections;

    #endregion -- Using Directives --

    /// <summary>
    /// ColorSchemeInfo holds information about a particular color scheme
    /// mentioned in the app.config. The information includes Name, Alphabet
    /// and the alphabet v\s color mapping.
    /// </summary>
    public class ColorSchemeInfo
    {
        #region -- Private Members --

        /// <summary>
        /// Holds the alphabet v\s color mapping for a particular color scheme.
        /// </summary>
        private Hashtable colorMapping;

        #endregion -- Private Members --

        #region -- Constructor --

        /// <summary>
        /// Initializes a new instance of the ColorSchemeInfo class.
        /// </summary>
        public ColorSchemeInfo()
        {
            this.colorMapping = new Hashtable();
        }

        #endregion -- Constructor --

        #region -- Properties --

        /// <summary>
        /// Gets or sets the name of a particular color scheme.
        /// </summary>
        public string Name
        {
            get;
            set;
        }

        /// <summary>
        /// Gets the alphabet v\s color mapping for a particular color scheme.
        /// </summary>
        public Hashtable ColorMapping
        {
            get
            {
                return this.colorMapping;
            }
        }

        #endregion -- Properties --
    }
}


text:
Does the [civic issue finder](http://www.codeforamerica.org/geeks/civicissues) actually work? Lets explore the data to find out.

## About
The civic issues finder is a widget that fetches open issues in projects included in the [Cfapi](http://www.codeforamerica.org/api/). More information about how the civic issue finder works is available in the project [Readme](https://github.com/codeforamerica/civic-issue-finder#civic-issue-finder). We want to ask questions around how these open issues become solved. We are looking at metrics like timestamps of activity and how frequently some issues get viewed or clicked. Hopefully this leads to a better understanding of how to have larger amounts of contribution on open source projects.

### How
1. Pull down all the acitivty from Google Analytics
2. Go explore those GitHub Issues
3. Perhaps visualize number of clicks, number of closed issues, number of commented on issues, relationships between people.

### Status
This project is currently in its exploration phase. You can see gotissues's progress and milestone activity [here](https://github.com/codeforamerica/gotissues/milestones?direction=asc&sort=due_date&state=open).

### Installation
#### Requirements
* `pip` and `virtualenv` - https://github.com/codeforamerica/howto/blob/master/Python-Virtualenv.md
* Google Analytics credentials for your `.env` file. Ping @ondrae to get the credentials, then fill in your `env.sample` file. Then `mv env.sample .env`

```
git clone https://github.com/codeforamerica/gotissues
cd gotissues
virtualenv .venv
source .venv/bin/activate
pip install -r requirements.txt
```

### To Run
Either use
```
source .env
python run.py
```
or to mimic Heroku use
```
foreman start
```

### To Test
In the top level, run

```
python tests/tests.py
```


text:
    Polymer('core-xhr', {

      /**
       * Sends a HTTP request to the server and returns the XHR object.
       *
       * @method request
       * @param {Object} inOptions
       *    @param {String} inOptions.url The url to which the request is sent.
       *    @param {String} inOptions.method The HTTP method to use, default is GET.
       *    @param {boolean} inOptions.sync By default, all requests are sent asynchronously. To send synchronous requests, set to true.
       *    @param {Object} inOptions.params Data to be sent to the server.
       *    @param {Object} inOptions.body The content for the request body for POST method.
       *    @param {Object} inOptions.headers HTTP request headers.
       *    @param {String} inOptions.responseType The response type. Default is 'text'.
       *    @param {boolean} inOptions.withCredentials Whether or not to send credentials on the request. Default is false.
       *    @param {Object} inOptions.callback Called when request is completed.
       * @returns {Object} XHR object.
       */
      request: function(options) {
        var xhr = new XMLHttpRequest();
        var url = options.url;
        var method = options.method || 'GET';
        var async = !options.sync;
        //
        var params = this.toQueryString(options.params);
        if (params && method == 'GET') {
          url += (url.indexOf('?') > 0 ? '&' : '?') + params;
        }
        var xhrParams = this.isBodyMethod(method) ? (options.body || params) : null;
        //
        xhr.open(method, url, async);
        if (options.responseType) {
          xhr.responseType = options.responseType;
        }
        if (options.withCredentials) {
          xhr.withCredentials = true;
        }
        this.makeReadyStateHandler(xhr, options.callback);
        this.setRequestHeaders(xhr, options.headers);
        xhr.send(xhrParams);
        if (!async) {
          xhr.onreadystatechange(xhr);
        }
        return xhr;
      },

      toQueryString: function(params) {
        var r = [];
        for (var n in params) {
          var v = params[n];
          n = encodeURIComponent(n);
          r.push(v == null ? n : (n + '=' + encodeURIComponent(v)));
        }
        return r.join('&');
      },

      isBodyMethod: function(method) {
        return this.bodyMethods[(method || '').toUpperCase()];
      },

      bodyMethods: {
        POST: 1,
        PUT: 1,
        PATCH: 1,
        DELETE: 1
      },

      makeReadyStateHandler: function(xhr, callback) {
        xhr.onreadystatechange = function() {
          if (xhr.readyState == 4) {
            callback && callback.call(null, xhr.response, xhr);
          }
        };
      },

      setRequestHeaders: function(xhr, headers) {
        if (headers) {
          for (var name in headers) {
            xhr.setRequestHeader(name, headers[name]);
          }
        }
      }

    });


text:
package com.streamsets.pipeline.stage.origin.pulsar;

import com.streamsets.pipeline.api.ConfigDefBean;
import com.streamsets.pipeline.api.ConfigGroups;
import com.streamsets.pipeline.api.GenerateResourceBundle;
import com.streamsets.pipeline.api.Source;
import com.streamsets.pipeline.api.StageDef;
import com.streamsets.pipeline.api.base.configurablestage.DSourceOffsetCommitter;
import com.streamsets.pipeline.api.service.ServiceConfiguration;
import com.streamsets.pipeline.api.service.ServiceDependency;
import com.streamsets.pipeline.api.service.dataformats.DataFormatParserService;
import com.streamsets.pipeline.lib.pulsar.config.PulsarGroups;
import com.streamsets.pipeline.stage.origin.lib.BasicConfig;
import com.streamsets.pipeline.stage.origin.lib.MessageConfig;

@StageDef(
    version = 1,
    label = "Pulsar Consumer",
    description = "Read data from Pulsar topics",
    icon = "pulsar.png",
    recordsByRef = true,
    upgraderDef = "upgrader/PulsarDSource.yaml",
    onlineHelpRefUrl = "index.html?contextID=task_kzh_cpc_r2b",
    services = @ServiceDependency(
        service = DataFormatParserService.class,
        configuration = {
            @ServiceConfiguration(name = "displayFormats", value = "BINARY,DATAGRAM,DELIMITED,JSON,LOG,PROTOBUF," +
                "SDC_JSON,TEXT,XML")
        }
    )
)
@ConfigGroups(PulsarGroups.class)
@GenerateResourceBundle
public class PulsarDSource extends DSourceOffsetCommitter {

  @ConfigDefBean(groups = {"PULSAR"})
  public BasicConfig basicConfig;

  @ConfigDefBean(groups = {"PULSAR"})
  public MessageConfig messageConfig;

  @ConfigDefBean
  public PulsarSourceConfig pulsarConfig;

  @Override
  protected Source createSource() {
    return new PulsarSource(basicConfig, pulsarConfig, new PulsarMessageConsumerFactoryImpl(),
        new PulsarMessageConverterImpl(messageConfig));
  }
}


text:
<?php

namespace Illuminate\Tests\Validation;

use PHPUnit\Framework\TestCase;
use Illuminate\Validation\Validator;
use Illuminate\Translation\Translator;
use Illuminate\Translation\ArrayLoader;
use Illuminate\Validation\Rules\Exists;
use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Validation\DatabasePresenceVerifier;

class ValidationExistsRuleTest extends TestCase
{
    /**
     * Setup the database schema.
     *
     * @return void
     */
    protected function setUp(): void
    {
        $db = new DB;

        $db->addConnection([
            'driver' => 'sqlite',
            'database' => ':memory:',
        ]);

        $db->bootEloquent();
        $db->setAsGlobal();

        $this->createSchema();
    }

    public function testItCorrectlyFormatsAStringVersionOfTheRule()
    {
        $rule = new Exists('table');
        $rule->where('foo', 'bar');
        $this->assertEquals('exists:table,NULL,foo,bar', (string) $rule);

        $rule = new Exists('table', 'column');
        $rule->where('foo', 'bar');
        $this->assertEquals('exists:table,column,foo,bar', (string) $rule);
    }

    public function testItChoosesValidRecordsUsingWhereInRule()
    {
        $rule = new Exists('users', 'id');
        $rule->whereIn('type', ['foo', 'bar']);

        EloquentTestUser::create(['id' => '1', 'type' => 'foo']);
        EloquentTestUser::create(['id' => '2', 'type' => 'bar']);
        EloquentTestUser::create(['id' => '3', 'type' => 'baz']);
        EloquentTestUser::create(['id' => '4', 'type' => 'other']);

        $trans = $this->getIlluminateArrayTranslator();
        $v = new Validator($trans, [], ['id' => $rule]);
        $v->setPresenceVerifier(new DatabasePresenceVerifier(Eloquent::getConnectionResolver()));

        $v->setData(['id' => 1]);
        $this->assertTrue($v->passes());
        $v->setData(['id' => 2]);
        $this->assertTrue($v->passes());
        $v->setData(['id' => 3]);
        $this->assertFalse($v->passes());
        $v->setData(['id' => 4]);
        $this->assertFalse($v->passes());
    }

    public function testItChoosesValidRecordsUsingWhereNotInRule()
    {
        $rule = new Exists('users', 'id');
        $rule->whereNotIn('type', ['foo', 'bar']);

        EloquentTestUser::create(['id' => '1', 'type' => 'foo']);
        EloquentTestUser::create(['id' => '2', 'type' => 'bar']);
        EloquentTestUser::create(['id' => '3', 'type' => 'baz']);
        EloquentTestUser::create(['id' => '4', 'type' => 'other']);

        $trans = $this->getIlluminateArrayTranslator();
        $v = new Validator($trans, [], ['id' => $rule]);
        $v->setPresenceVerifier(new DatabasePresenceVerifier(Eloquent::getConnectionResolver()));

        $v->setData(['id' => 1]);
        $this->assertFalse($v->passes());
        $v->setData(['id' => 2]);
        $this->assertFalse($v->passes());
        $v->setData(['id' => 3]);
        $this->assertTrue($v->passes());
        $v->setData(['id' => 4]);
        $this->assertTrue($v->passes());
    }

    public function testItChoosesValidRecordsUsingWhereNotInAndWhereNotInRulesTogether()
    {
        $rule = new Exists('users', 'id');
        $rule->whereIn('type', ['foo', 'bar', 'baz'])->whereNotIn('type', ['foo', 'bar']);

        EloquentTestUser::create(['id' => '1', 'type' => 'foo']);
        EloquentTestUser::create(['id' => '2', 'type' => 'bar']);
        EloquentTestUser::create(['id' => '3', 'type' => 'baz']);
        EloquentTestUser::create(['id' => '4', 'type' => 'other']);

        $trans = $this->getIlluminateArrayTranslator();
        $v = new Validator($trans, [], ['id' => $rule]);
        $v->setPresenceVerifier(new DatabasePresenceVerifier(Eloquent::getConnectionResolver()));

        $v->setData(['id' => 1]);
        $this->assertFalse($v->passes());
        $v->setData(['id' => 2]);
        $this->assertFalse($v->passes());
        $v->setData(['id' => 3]);
        $this->assertTrue($v->passes());
        $v->setData(['id' => 4]);
        $this->assertFalse($v->passes());
    }

    protected function createSchema()
    {
        $this->schema('default')->create('users', function ($table) {
            $table->unsignedInteger('id');
            $table->string('type');
        });
    }

    /**
     * Get a schema builder instance.
     *
     * @return \Illuminate\Database\Schema\Builder
     */
    protected function schema($connection = 'default')
    {
        return $this->connection($connection)->getSchemaBuilder();
    }

    /**
     * Get a database connection instance.
     *
     * @return \Illuminate\Database\Connection
     */
    protected function connection($connection = 'default')
    {
        return $this->getConnectionResolver()->connection($connection);
    }

    /**
     * Get connection resolver.
     *
     * @return \Illuminate\Database\ConnectionResolverInterface
     */
    protected function getConnectionResolver()
    {
        return Eloquent::getConnectionResolver();
    }

    /**
     * Tear down the database schema.
     *
     * @return void
     */
    protected function tearDown(): void
    {
        $this->schema('default')->drop('users');
    }

    public function getIlluminateArrayTranslator()
    {
        return new Translator(
            new ArrayLoader, 'en'
        );
    }
}

/**
 * Eloquent Models.
 */
class EloquentTestUser extends Eloquent
{
    protected $table = 'users';
    protected $guarded = [];
    public $timestamps = false;
}


text:
'use strict';

/**
 * @file World Server
 * @author Elmario Husha
 * @name CubeWars - World Server
 * @package MSc Computer Science - Project
 */

/**
 * External Modules
 */
var http  = require('http');
var redis = require('redis');
var express = require('express');
var _ = require('underscore');
var cookie = require('cookie');
var connect = require('connect');
var validator = require('validator');

/**
 * Server Module
 * @module Server
 */
define(
[
    'config',
    'common',
    'utils',
    'world',
    'auth',
    'vec2',
    'player',
    'playerManager',
    'movementManager',
    // Networking Modules
    'game/generic',
    'game/movement',
    'game/player'
],

function(
    config,
    common,
    Util,
    WorldMap,
    Auth,
    Vec2,
    Player,
    PlayerManager,
    MovementManager,
    // Networking Modules
    NetModuleGeneric,
    NetModuleMovement,
    NetModulePlayer
) {
    var db_logon = common.db.connect('logon');
    var db_world = common.db.connect('world');
    /**
     * Our main world server module
     * @constructor
     * @alias module:Server
     */
    var Server = function() {
        this._rstore  = require('socket.io/lib/stores/redis');
        this._server  = express();
        this._clients = {};

        this._sessionStore = new this._rstore ({
            redisPub: redis.createClient(),
            redisSub: redis.createClient(),
            redisClient: redis.createClient()
        });
    };

    /**
     * Our World Server
     * @type {Object}
     */
    Server.prototype = {
        /**
         * Basic Startup routine
         * @param  {Object} Server Paramms
         */
        init: function(params) {
            var _this = this;

            this.params = params || {};
            this.setupServer();
            this.startServer();
            this.initNetworking();
        },

        /**
         * Initialise modules
         */
        setupServer: function() {
            var params = this.params;

            this._server.configure(function() {
                this.set('port', params.port);
                this.use(express.cookieParser());
                console.log(config.misc.genericStartupMessage);
            });

            this._worldMap = new WorldMap(150000);
        },

        /**
         * Start HTTP Listener
         */
        startServer: function() {
            var _this = this;
            this._express = http.createServer(this._server).listen(this._server.get('port'), function() {
                console.log('World Server', '[LOG]', 'CubeWars world server instance started [' + _this._server.get('port') + ']');
            });

            if(!this._express) {
                console.log('Failed to load world server instance, please check port setup');
            }

            this._network = require('socket.io').listen(
                this._express, {'store': this._sessionStore}
            );

            this._network.configure(function() {
                this.set('transports', ['websocket']);
                this.set('log level', 0);
                this.set('authorization', Auth.process);
            });
        },

        /**
         * Start Socket Listener
         */
        initNetworking: function() {
            var _this  = this;
            this._network.sockets.on('connection', function(client) {
                _this._clients[client.id] = client;

                NetModuleGeneric(client, _this._network, _this._worldMap, _this._clients, db_world);
                NetModulePlayer(client, _this._network, _this._worldMap, _this._clients, db_world);
                NetModuleMovement(client, _this._network, _this._worldMap, _this._clients, db_world);

                client.on('disconnect', function() {
                    var leavingClient = client.id;
                    var leavingPlayer = _this._worldMap.getPlayerByClient(leavingClient);
                    if(typeof leavingPlayer == 'undefined') {
                        return;
                    }
                    _this._network.sockets.emit('SMSG-PLAYER-LEFT', leavingPlayer.playerId, leavingClient);
                    _this._worldMap.removePlayer(client.id)
                });

            });
        }
    };

    return new Server();
});


text:
package main

import (
	"fmt"

	"io"

	"github.com/golang/glog"
	"github.com/spf13/cobra"
	"k8s.io/kops/cmd/kops/util"
	api "k8s.io/kops/pkg/apis/kops"
	"k8s.io/kops/pkg/apis/kops/registry"
	"k8s.io/kops/pkg/kubeconfig"
	"k8s.io/kops/pkg/resources"
	"k8s.io/kops/upup/pkg/fi"
	"k8s.io/kops/upup/pkg/fi/cloudup"
	"k8s.io/kops/upup/pkg/fi/cloudup/awsup"
	"k8s.io/kops/util/pkg/tables"
	"k8s.io/kops/util/pkg/vfs"
	"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
	"k8s.io/kubernetes/pkg/util/i18n"
)

type DeleteClusterOptions struct {
	Yes         bool
	Region      string
	External    bool
	Unregister  bool
	ClusterName string
}

var (
	delete_cluster_long = templates.LongDesc(i18n.T(`
	Deletes a k8s cluster.
	`))

	delete_cluster_example = templates.Examples(i18n.T(`
		# Delete a cluster in AWS.
		kops delete cluster --name=k8s.cluster.site --yes
	`))
)

func NewCmdDeleteCluster(f *util.Factory, out io.Writer) *cobra.Command {
	options := &DeleteClusterOptions{}

	cmd := &cobra.Command{
		Use:     "cluster CLUSTERNAME [--yes]",
		Short:   "Delete cluster",
		Long:    delete_cluster_long,
		Example: delete_cluster_example,
		Run: func(cmd *cobra.Command, args []string) {
			err := rootCommand.ProcessArgs(args)
			if err != nil {
				exitWithError(err)
			}

			// Note _not_ ClusterName(); we only want the --name flag
			options.ClusterName = rootCommand.clusterName

			err = RunDeleteCluster(f, out, options)
			if err != nil {
				exitWithError(err)
			}
		},
	}

	cmd.Flags().BoolVarP(&options.Yes, "yes", "y", options.Yes, "Specify --yes to delete the cluster")
	cmd.Flags().BoolVar(&options.Unregister, "unregister", options.Unregister, "Don't delete cloud resources, just unregister the cluster")
	cmd.Flags().BoolVar(&options.External, "external", options.External, "Delete an external cluster")

	cmd.Flags().StringVar(&options.Region, "region", options.Region, "region")
	return cmd
}

type getter func(o interface{}) interface{}

func RunDeleteCluster(f *util.Factory, out io.Writer, options *DeleteClusterOptions) error {
	var configBase vfs.Path

	clusterName := options.ClusterName
	if clusterName == "" {
		return fmt.Errorf("--name is required (for safety)")
	}

	var cloud fi.Cloud
	var cluster *api.Cluster
	var err error

	if options.External {
		region := options.Region
		if region == "" {
			return fmt.Errorf("--region is required (when --external)")
		}

		tags := map[string]string{"KubernetesCluster": clusterName}
		cloud, err = awsup.NewAWSCloud(region, tags)
		if err != nil {
			return fmt.Errorf("error initializing AWS client: %v", err)
		}
	} else {
		cluster, err = GetCluster(f, clusterName)
		if err != nil {
			return err
		}

		configBase, err = registry.ConfigBase(cluster)
		if err != nil {
			return err
		}
	}

	wouldDeleteCloudResources := false

	if !options.Unregister {
		if cloud == nil {
			cloud, err = cloudup.BuildCloud(cluster)
			if err != nil {
				return err
			}
		}

		// Todo lets make this smart enough to detect the cloud and switch on the ClusterResources interface
		d := &resources.AwsCluster{}
		d.ClusterName = clusterName
		d.Cloud = cloud

		clusterResources, err := d.ListResources()
		if err != nil {
			return err
		}

		if len(clusterResources) == 0 {
			fmt.Fprintf(out, "No cloud resources to delete\n")
		} else {
			wouldDeleteCloudResources = true

			t := &tables.Table{}
			t.AddColumn("TYPE", func(r *resources.ResourceTracker) string {
				return r.Type
			})
			t.AddColumn("ID", func(r *resources.ResourceTracker) string {
				return r.ID
			})
			t.AddColumn("NAME", func(r *resources.ResourceTracker) string {
				return r.Name
			})
			var l []*resources.ResourceTracker
			for _, v := range clusterResources {
				l = append(l, v)
			}

			err := t.Render(l, out, "TYPE", "NAME", "ID")
			if err != nil {
				return err
			}

			if !options.Yes {
				return fmt.Errorf("Must specify --yes to delete")
			}

			fmt.Fprintf(out, "\n")

			err = d.DeleteResources(clusterResources)
			if err != nil {
				return err
			}
		}
	}

	if !options.External {
		if !options.Yes {
			if wouldDeleteCloudResources {
				fmt.Fprintf(out, "\nMust specify --yes to delete cloud resources & unregister cluster\n")
			} else {
				fmt.Fprintf(out, "\nMust specify --yes to unregister the cluster\n")
			}
			return nil
		}
		err := registry.DeleteAllClusterState(configBase)
		if err != nil {
			return fmt.Errorf("error removing cluster from state store: %v", err)
		}
	}

	b := kubeconfig.NewKubeconfigBuilder()
	b.Context = clusterName
	err = b.DeleteKubeConfig()
	if err != nil {
		glog.Warningf("error removing kube config: %v", err)
	}

	fmt.Fprintf(out, "\nCluster deleted\n")
	return nil
}


text:
import Model from 'flarum/Model';
import mixin from 'flarum/utils/mixin';

export default class FeedBack extends mixin(Model, {

  id: Model.attribute('user_id'),
  text: Model.attribute('text'),
  status: Model.attribute('status'),

}) {}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="Julien Blin">
//   Copyright (c) 2014 Julien Blin
// </copyright>
// <summary>
//   AssemblyInfo.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System.Reflection;

[assembly: AssemblyTitle("Demeter.Kernel.Tests")]
[assembly: AssemblyDescription("Unit tests for Demeter.Kernel assembly.")]


text:
package com.moesounds.exception;

import javax.servlet.http.HttpServletRequest;

/**
 * Custom {@link RuntimeException} where a non-admin user attempted to login into an admin page
 *
 * @author NYPD
 *
 */
public class UnauthorizedUserException extends RuntimeException {

    private static final long serialVersionUID = 1987666346814209997L;
    private String ipAddress;

    public UnauthorizedUserException(HttpServletRequest request) {
        super();

        String forwardedForHeader = request.getHeader("X-FORWARDED-FOR");
        this.ipAddress = forwardedForHeader != null ? forwardedForHeader : request.getRemoteAddr();
    }

    public String getIpAddress() {
        return ipAddress;
    }

}


text:
namespace content {

DevToolsIOContext::Stream::Stream(
    scoped_refptr<base::SequencedTaskRunner> task_runner)
    : RefCountedDeleteOnSequence<DevToolsIOContext::Stream>(
          std::move(task_runner)) {}

std::string DevToolsIOContext::Stream::Register(DevToolsIOContext* context) {
  static unsigned s_last_stream_handle = 0;
  const std::string handle = base::NumberToString(++s_last_stream_handle);
  Register(context, handle);
  return handle;
}

void DevToolsIOContext::Stream::Register(DevToolsIOContext* context,
                                         const std::string& handle) {
  context->RegisterStream(this, handle);
}

bool DevToolsIOContext::Stream::SupportsSeek() const {
  return true;
}

DevToolsIOContext::Stream::~Stream() = default;

DevToolsIOContext::DevToolsIOContext() = default;

DevToolsIOContext::~DevToolsIOContext() = default;

void DevToolsIOContext::RegisterStream(scoped_refptr<Stream> stream,
                                       const std::string& id) {
  bool inserted = streams_.emplace(id, std::move(stream)).second;
  DCHECK(inserted);
}

scoped_refptr<DevToolsIOContext::Stream> DevToolsIOContext::GetByHandle(
    const std::string& handle) {
  auto it = streams_.find(handle);
  return it == streams_.end() ? nullptr : it->second;
}

bool DevToolsIOContext::Close(const std::string& handle) {
  size_t erased_count = streams_.erase(handle);
  return !!erased_count;
}

void DevToolsIOContext::DiscardAllStreams() {
  streams_.clear();
}

// static
bool DevToolsIOContext::IsTextMimeType(const std::string& mime_type) {
  static const char* kTextMIMETypePrefixes[] = {
      "text/", "application/x-javascript", "application/json",
      "application/xml"};
  for (size_t i = 0; i < std::size(kTextMIMETypePrefixes); ++i) {
    if (base::StartsWith(mime_type, kTextMIMETypePrefixes[i],
                         base::CompareCase::INSENSITIVE_ASCII))
      return true;
  }
  return false;
}

}  // namespace content


text:
<!--

********************************************************************************

WARNING:

    DO NOT EDIT "kibana/README.md"

    IT IS AUTO-GENERATED

    (from the other files in "kibana/" combined with a set of templates)

********************************************************************************

-->

# **DEPRECATION NOTICE**

This image has been deprecated in favor of the [official `kibana` image](https://www.elastic.co/guide/en/kibana/current/_pulling_the_image.html) provided and maintained by [elastic.co](https://www.elastic.co/). The list of images available from Elastic can be found at [www.docker.elastic.co](https://www.docker.elastic.co/). The images found here will receive no further updates once the `6.0.0` release is available upstream. Please adjust your usage accordingly.

Elastic provides open-source support for Kibana via the [elastic/kibana GitHub repository](https://github.com/elastic/kibana) and the Docker image via the [elastic/kibana-docker GitHub repository](https://github.com/elastic/kibana-docker), as well as community support via its [forums](https://discuss.elastic.co/c/kibana).

# Supported tags and respective `Dockerfile` links

-	[`5.6.9`, `5.6`, `5`, `latest` (*5/Dockerfile*)](https://github.com/docker-library/kibana/blob/249795079412622520b290ce2a93eae360db3b68/5/Dockerfile)
-	[`4.6.6`, `4.6`, `4` (*4.6/Dockerfile*)](https://github.com/docker-library/kibana/blob/febc4b766dabfc5a30f04373337cd0a0ec997bb2/4.6/Dockerfile)

# Quick reference

-	**Where to get help**:
	[the Docker Community Forums](https://forums.docker.com/), [the Docker Community Slack](https://blog.docker.com/2016/11/introducing-docker-community-directory-docker-community-slack/), or [Stack Overflow](https://stackoverflow.com/search?tab=newest&q=docker)

-	**Where to file issues**:
	[https://github.com/docker-library/kibana/issues](https://github.com/docker-library/kibana/issues)

-	**Maintained by**:
	[the Docker Community](https://github.com/docker-library/kibana)

-	**Supported architectures**: ([more info](https://github.com/docker-library/official-images#architectures-other-than-amd64))
	[`amd64`](https://hub.docker.com/r/amd64/kibana/)

-	**Published image artifact details**:
	[repo-info repo's `repos/kibana/` directory](https://github.com/docker-library/repo-info/blob/master/repos/kibana) ([history](https://github.com/docker-library/repo-info/commits/master/repos/kibana))
	(image metadata, transfer size, etc)

-	**Image updates**:
	[official-images PRs with label `library/kibana`](https://github.com/docker-library/official-images/pulls?q=label%3Alibrary%2Fkibana)
	[official-images repo's `library/kibana` file](https://github.com/docker-library/official-images/blob/master/library/kibana) ([history](https://github.com/docker-library/official-images/commits/master/library/kibana))

-	**Source of this description**:
	[docs repo's `kibana/` directory](https://github.com/docker-library/docs/tree/master/kibana) ([history](https://github.com/docker-library/docs/commits/master/kibana))

-	**Supported Docker versions**:
	[the latest release](https://github.com/docker/docker-ce/releases/latest) (down to 1.6 on a best-effort basis)

# What is Kibana?

Kibana is an open source data visualization plugin for Elasticsearch. It provides visualization capabilities on top of the content indexed on an Elasticsearch cluster. Users can create bar, line and scatter plots, or pie charts and maps on top of large volumes of data.

Kibana is a registered trademark of Elasticsearch BV.

> [wikipedia.org/wiki/Kibana](https://en.wikipedia.org/wiki/Kibana)

![logo](https://raw.githubusercontent.com/docker-library/docs/8bb704930619acddf6f5705e7d1cf54defdd3388/kibana/logo.png)

# How to use this image

You can run the default `kibana` command simply:

```console
$ docker run --link some-elasticsearch:elasticsearch -d kibana
```

You can also pass in additional flags to `kibana`:

```console
$ docker run --link some-elasticsearch:elasticsearch -d kibana --plugins /somewhere/else
```

This image includes `EXPOSE 5601` ([default `port`](https://www.elastic.co/guide/en/kibana/5.2/settings.html)). If you'd like to be able to access the instance from the host without the container's IP, standard port mappings can be used:

```console
$ docker run --name some-kibana --link some-elasticsearch:elasticsearch -p 5601:5601 -d kibana
```

You can also provide the address of elasticsearch via `ELASTICSEARCH_URL` environnement variable:

```console
$ docker run --name some-kibana -e ELASTICSEARCH_URL=http://some-elasticsearch:9200 -p 5601:5601 -d kibana
```

Then, access it via `http://localhost:5601` or `http://host-ip:5601` in a browser.

## ... via [`docker stack deploy`](https://docs.docker.com/engine/reference/commandline/stack_deploy/) or [`docker-compose`](https://github.com/docker/compose)

Example `stack.yml` for `kibana`:

```yaml
version: '3.1'

services:

  kibana:
    image: kibana
    ports:
      - 5601:5601

  elasticsearch:
    image: elasticsearch
```

[![Try in PWD](https://github.com/play-with-docker/stacks/raw/cff22438cb4195ace27f9b15784bbb497047afa7/assets/images/button.png)](http://play-with-docker.com?stack=https://raw.githubusercontent.com/docker-library/docs/9efeec18b6b2ed232cf0fbd3914b6211e16e242c/kibana/stack.yml)

Run `docker stack deploy -c stack.yml kibana` (or `docker-compose -f stack.yml up`), wait for it to initialize completely, and visit `http://swarm-ip:5601`, `http://localhost:5601`, or `http://host-ip:5601` (as appropriate).

# License

View [license information](https://github.com/elastic/kibana/blob/4557a6fc0ba08c5e7ac813a180179e5e2631c90a/LICENSE.md) for the software contained in this image.

As with all Docker images, these likely also contain other software which may be under other licenses (such as Bash, etc from the base distribution, along with any direct or indirect dependencies of the primary software being contained).

Some additional license information which was able to be auto-detected might be found in [the `repo-info` repository's `kibana/` directory](https://github.com/docker-library/repo-info/tree/master/repos/kibana).

As for any pre-built image usage, it is the image user's responsibility to ensure that any use of this image complies with any relevant licenses for all software contained within.


text:
// Copyright 2018 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.profiler;

import static com.google.common.truth.Truth.assertThat;

import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link TimeSeries}. */
@RunWith(JUnit4.class)
public final class TimeSeriesTest {
  @Test
  public void testAddRange() {
    TimeSeries timeSeries = new TimeSeries(42, 100);
    timeSeries.addRange(42, 142);
    timeSeries.addRange(442, 542);
    double[] values = timeSeries.toDoubleArray(5);
    assertThat(values).usingTolerance(1.0e-10).containsExactly(1, 0, 0, 0, 1).inOrder();
  }

  @Test
  public void testAddRangeWithValue() {
    TimeSeries timeSeries = new TimeSeries(42, 100);
    timeSeries.addRange(42, 242, 3);
    timeSeries.addRange(442, 542, 0.5);
    double[] values = timeSeries.toDoubleArray(5);
    assertThat(values).usingTolerance(1.0e-10).containsExactly(3, 3, 0, 0, .5).inOrder();
  }

  @Test
  public void testAddRangeOverlappingWithValue() {
    TimeSeries timeSeries = new TimeSeries(42, 100);
    timeSeries.addRange(42, 242, 3);
    timeSeries.addRange(142, 442, 0.5);
    double[] values = timeSeries.toDoubleArray(5);
    assertThat(values).usingTolerance(1.0e-10).containsExactly(3, 3.5, 0.5, 0.5, 0).inOrder();
  }

  @Test
  public void testAddRangeFractions() {
    TimeSeries timeSeries = new TimeSeries(42, 100);
    timeSeries.addRange(92, 267);
    double[] values = timeSeries.toDoubleArray(5);
    assertThat(values).usingTolerance(1.0e-10).containsExactly(0.5, 1, 0.25, 0, 0).inOrder();
  }

  @Test
  public void testAddRangeWithValueFractions() {
    TimeSeries timeSeries = new TimeSeries(42, 100);
    timeSeries.addRange(92, 267, 3);
    double[] values = timeSeries.toDoubleArray(5);
    assertThat(values).usingTolerance(1.0e-10).containsExactly(1.5, 3, 0.75, 0, 0).inOrder();
  }

  @Test
  public void testResize() {
    TimeSeries timeSeries = new TimeSeries(0, 100);
    timeSeries.addRange(0, 100 * 100 + 1, 42);
    double[] values = timeSeries.toDoubleArray(101);
    double[] expected = new double[101];
    Arrays.fill(expected, 0, expected.length - 1, 42);
    expected[expected.length - 1] = 0.42;
    assertThat(values).usingTolerance(1.0e-10).containsExactly(expected).inOrder();
  }
}


text: from .trigonometry import *


text:
module.exports = () => {
  return {
    restrict: 'E',
    template: require('./template.html'),
    controller: ['$scope', 'dataStore', ($scope, dataStore) => {
      $scope.workouts = dataStore.getWorkouts();
    }]
  };
};


text:
let assert = require('chai').assert;
let async = require('async');

import { Descriptor } from 'pip-services3-commons-node';
import { ConfigParams } from 'pip-services3-commons-node';
import { References } from 'pip-services3-commons-node';
import { ConsoleLogger } from 'pip-services3-components-node';

import { MessageTemplatesMemoryPersistence } from 'pip-services-msgtemplates-node';
import { MessageTemplatesController } from 'pip-services-msgtemplates-node';
import { IMessageTemplatesClientV1 } from '../../src/version1/IMessageTemplatesClientV1';
import { MessageTemplatesDirectClientV1 } from '../../src/version1/MessageTemplatesDirectClientV1';
import { MessageTemplatesClientFixtureV1 } from './MessageTemplatesClientFixtureV1';

suite('MessageTemplatesDirectClientV1', ()=> {
    let client: MessageTemplatesDirectClientV1;
    let fixture: MessageTemplatesClientFixtureV1;

    suiteSetup((done) => {
        let logger = new ConsoleLogger();
        let persistence = new MessageTemplatesMemoryPersistence();
        let controller = new MessageTemplatesController();

        let references: References = References.fromTuples(
            new Descriptor('pip-services', 'logger', 'console', 'default', '1.0'), logger,
            new Descriptor('pip-services-msgtemplates', 'persistence', 'memory', 'default', '1.0'), persistence,
            new Descriptor('pip-services-msgtemplates', 'controller', 'default', 'default', '1.0'), controller,
        );
        controller.setReferences(references);

        client = new MessageTemplatesDirectClientV1();
        client.setReferences(references);

        fixture = new MessageTemplatesClientFixtureV1(client);

        client.open(null, done);
    });

    suiteTeardown((done) => {
        client.close(null, done);
    });

    test('CRUD Operations', (done) => {
        fixture.testCrudOperations(done);
    });

});


text:
from abc import ABCMeta, abstractmethod

class OffensiveModule(object):
    __metaclass__ = ABCMeta

    def __init__(self):
        self.targets = []
        self.results = []

    @abstractmethod
    def execute(self):
        pass

    @abstractmethod
    def loadConfig(self, config):
        pass

    def getTargets(self):
        return self.targets

    def addResult(self, result):
        self.results.append(result)

    def addResults(self, results):
        self.results.extend(results)

    def getResults(self):
        return self.results

    def feed(self, targets):
        self.targets.extend(targets)

    def clearTargets(self):
        self.targets = []


text:
package com.pphi.iron.dragon.component.card.demand;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.pphi.iron.dragon.component.City;
import com.pphi.iron.dragon.component.Load;

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
public class Contract {

    private final City city;
    private final Load load;
    private final int payment;

    @JsonCreator
    public Contract(
            @JsonProperty("city") String city,
            @JsonProperty("load") Load load,
            @JsonProperty("payment") int payment) {
        this.city = City.valueOf(city);
        this.load = load;
        this.payment = payment;
    }

    public Contract(City city, Load load, int payment) {
        this.city = city;
        this.load = load;
        this.payment = payment;
    }

    @JsonProperty("city")
    public City getCity() {
        return city;
    }

    @JsonProperty("load")
    public Load getLoad() {
        return load;
    }

    @JsonProperty("payment")
    public int getPayment() {
        return payment;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("city", city)
                .add("load", load)
                .add("payment", payment)
                .toString();
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(city, load, payment);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        final Contract other = (Contract) obj;
        return Objects.equal(this.city, other.city)
                && Objects.equal(this.load, other.load)
                && Objects.equal(this.payment, other.payment);
    }
}


text:
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/listView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentBottom="true"
        android:clipToPadding="false"
        android:fadingEdge="none"
        android:fadingEdgeLength="0dp"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:dividerHeight="0dp"
        android:divider="@null"
        android:scrollbars="none"
        android:paddingBottom="16dp"
        android:verticalScrollbarPosition="left"/>

</RelativeLayout>