text:
package net.dv8tion.jda.core.handle;

import gnu.trove.iterator.TLongIterator;
import gnu.trove.set.TLongSet;
import gnu.trove.set.hash.TLongHashSet;
import net.dv8tion.jda.client.entities.Relationship;
import net.dv8tion.jda.client.entities.impl.FriendImpl;
import net.dv8tion.jda.client.entities.impl.UserSettingsImpl;
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.OnlineStatus;
import net.dv8tion.jda.core.WebSocketCode;
import net.dv8tion.jda.core.entities.ChannelType;
import net.dv8tion.jda.core.entities.EntityBuilder;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.impl.JDAImpl;
import net.dv8tion.jda.core.managers.impl.PresenceImpl;
import net.dv8tion.jda.core.requests.WebSocketClient;
import org.json.JSONArray;
import org.json.JSONObject;

public class ReadyHandler extends SocketHandler
{
    private final TLongSet incompleteGuilds = new TLongHashSet();
    private final TLongSet acknowledgedGuilds = new TLongHashSet();
    private final TLongSet unavailableGuilds = new TLongHashSet();
    private final TLongSet guildsRequiringChunking = new TLongHashSet();
    private final TLongSet guildsRequiringSyncing = new TLongHashSet();

    public ReadyHandler(JDAImpl api)
    {
        super(api);
    }

    @Override
    protected Long handleInternally(JSONObject content)
    {
        EntityBuilder builder = api.getEntityBuilder();

        //Core
        JSONArray guilds = content.getJSONArray("guilds");
        JSONObject selfJson = content.getJSONObject("user");

        builder.createSelfUser(selfJson);

        if (api.getAccountType() == AccountType.CLIENT && !content.isNull("user_settings"))
        {
            // handle user settings
            JSONObject userSettingsJson = content.getJSONObject("user_settings");
            UserSettingsImpl userSettingsObj = (UserSettingsImpl) api.asClient().getSettings();
            userSettingsObj
                    // TODO: set all information and handle updates
                    .setStatus(userSettingsJson.isNull("status") ? OnlineStatus.ONLINE : OnlineStatus.fromKey(userSettingsJson.getString("status")));
            // update presence information unless the status is ONLINE
            if (userSettingsObj.getStatus() != OnlineStatus.ONLINE)
                ((PresenceImpl) api.getPresence()).setCacheStatus(userSettingsObj.getStatus());
        }

        //Keep a list of all guilds in incompleteGuilds that need to be setup (GuildMemberChunk / GuildSync)
        //Send all guilds to the EntityBuilder's first pass to setup caching for when GUILD_CREATE comes
        // or, for Client accounts, to start the setup process (since we already have guild info)
        //Callback points to guildSetupComplete so that when MemberChunking and GuildSync processes are done, we can
        // "check off" the completed guild from the set of guilds in incompleteGuilds.

        for (int i = 0; i < guilds.length(); i++)
        {
            JSONObject guild = guilds.getJSONObject(i);
            incompleteGuilds.add(guild.getLong("id"));
        }

        //We use two different for-loops here so that we cache all of the ids before sending them off to the EntityBuilder
        //  due to the checks in checkIfReadyToSendRequests and guildSetupComplete triggering too soon otherwise.
        // Specifically: incompleteGuilds.size() == acknowledgedGuilds.size() and
        //  incompleteGuilds.size() == unavailableGuilds.size() respectively.

        for (int i = 0; i < guilds.length(); i++)
        {
            JSONObject guild = guilds.getJSONObject(i);

            //If a Guild isn't unavailable, then it is possible that we were given all information
            // needed to fully load the guild. In this case, we provide the method `guildSetupComplete`
            // as the secondPassCallback so it can immediately be called to signify that the provided guild
            // is loaded and ready to go.
            //If a Guild is unavailable it won't have the information needed, so we pass null as the secondPassCallback
            // for now and wait for the GUILD_CREATE event to give us the required information.
            if (guild.has("unavailable") && guild.getBoolean("unavailable"))
                builder.createGuildFirstPass(guild, null);
            else
                builder.createGuildFirstPass(guild, this::guildSetupComplete);
        }

        if (guilds.length() == 0)
            guildLoadComplete(content);

        return null;
    }

    public void guildLoadComplete(JSONObject content)
    {
        api.getClient().setChunkingAndSyncing(false);
        EntityBuilder builder = api.getEntityBuilder();
        JSONArray privateChannels = content.getJSONArray("private_channels");

        if (api.getAccountType() == AccountType.CLIENT)
        {
            JSONArray relationships = content.getJSONArray("relationships");
            JSONArray presences = content.getJSONArray("presences");
            JSONObject notes = content.getJSONObject("notes");
            JSONArray readstates = content.has("read_state") ? content.getJSONArray("read_state") : null;
            JSONArray guildSettings = content.has("user_guild_settings") ? content.getJSONArray("user_guild_settings") : null;

            for (int i = 0; i < relationships.length(); i++)
            {
                JSONObject relationship = relationships.getJSONObject(i);
                Relationship r = builder.createRelationship(relationship);
                if (r == null)
                    JDAImpl.LOG.fatal("Provided relationship in READY with an unknown type! JSON: " + relationship.toString());
            }

            for (int i = 0; i < presences.length(); i++)
            {
                JSONObject presence = presences.getJSONObject(i);
                String userId = presence.getJSONObject("user").getString("id");
                FriendImpl friend = (FriendImpl) api.asClient().getFriendById(userId);
                if (friend == null)
                    WebSocketClient.LOG.warn("Received a presence in the Presences array in READY that did not correspond to a cached Friend! JSON: " + presence);
                else
                    builder.createPresence(friend, presence);
            }
        }

        for (int i = 0; i < privateChannels.length(); i++)
        {
            JSONObject chan = privateChannels.getJSONObject(i);
            ChannelType type = ChannelType.fromId(chan.getInt("type"));

            switch (type)
            {
                case PRIVATE:
                    builder.createPrivateChannel(chan);
                    break;
                case GROUP:
                    builder.createGroup(chan);
                    break;
                default:
                    WebSocketClient.LOG.warn("Received a Channel in the priv_channels array in READY of an unknown type! JSON: " + type);
            }

        }

        api.getClient().ready();
    }

    public void acknowledgeGuild(Guild guild, boolean available, boolean requiresChunking, boolean requiresSync)
    {
        acknowledgedGuilds.add(guild.getIdLong());
        if (available)
        {
            //We remove from unavailable guilds because it is possible that we were told it was unavailable, but
            // during a long READY load it could have become available and was sent to us.
            unavailableGuilds.remove(guild.getIdLong());
            if (requiresChunking)
                guildsRequiringChunking.add(guild.getIdLong());
            if (requiresSync)
                guildsRequiringSyncing.add(guild.getIdLong());
        }
        else
            unavailableGuilds.add(guild.getIdLong());

        checkIfReadyToSendRequests();
    }

    public void guildSetupComplete(Guild guild)
    {
        if (!incompleteGuilds.remove(guild.getIdLong()))
            WebSocketClient.LOG.fatal("Completed the setup for Guild: " + guild + " without matching id in ReadyHandler cache");
        if (incompleteGuilds.size() == unavailableGuilds.size())
            guildLoadComplete(allContent.getJSONObject("d"));
        else
            checkIfReadyToSendRequests();
    }

    public void clearCache()
    {
        incompleteGuilds.clear();
        acknowledgedGuilds.clear();
        unavailableGuilds.clear();
        guildsRequiringChunking.clear();
        guildsRequiringSyncing.clear();
    }

    private void checkIfReadyToSendRequests()
    {
        if (acknowledgedGuilds.size() == incompleteGuilds.size())
        {
            api.getClient().setChunkingAndSyncing(true);
            if (api.getAccountType() == AccountType.CLIENT)
                sendGuildSyncRequests();
            sendMemberChunkRequests();
        }
    }

    private void sendGuildSyncRequests()
    {
        if (guildsRequiringSyncing.isEmpty())
            return;

        JSONArray guildIds = new JSONArray();

        for (TLongIterator it = guildsRequiringSyncing.iterator(); it.hasNext(); )
        {
            guildIds.put(it.next());

            //We can only request 50 guilds in a single request, so after we've reached 50, send them
            // and reset the
            if (guildIds.length() == 50)
            {
                api.getClient().chunkOrSyncRequest(new JSONObject()
                        .put("op", WebSocketCode.GUILD_SYNC)
                        .put("d", guildIds));
                guildIds = new JSONArray();
            }
        }

        //Send the remaining guilds that need to be sent
        if (guildIds.length() > 0)
        {
            api.getClient().chunkOrSyncRequest(new JSONObject()
                    .put("op", WebSocketCode.GUILD_SYNC)
                    .put("d", guildIds));
        }
        guildsRequiringSyncing.clear();
    }

    private void sendMemberChunkRequests()
    {
        if (guildsRequiringChunking.isEmpty())
            return;

        JSONArray guildIds = new JSONArray();
        for (TLongIterator it = guildsRequiringChunking.iterator(); it.hasNext(); )
        {
            guildIds.put(it.next());

            //We can only request 50 guilds in a single request, so after we've reached 50, send them
            // and reset the
            if (guildIds.length() == 50)
            {
                api.getClient().chunkOrSyncRequest(new JSONObject()
                    .put("op", 8)
                    .put("d", new JSONObject()
                        .put("guild_id", guildIds)
                        .put("query", "")
                        .put("limit", 0)
                    ));
                guildIds = new JSONArray();
            }
        }

        //Send the remaining guilds that need to be sent
        if (guildIds.length() > 0)
        {
            api.getClient().chunkOrSyncRequest(new JSONObject()
                .put("op", 8)
                .put("d", new JSONObject()
                        .put("guild_id", guildIds)
                        .put("query", "")
                        .put("limit", 0)
                ));
        }
        guildsRequiringChunking.clear();
    }
}


text:
var ApplicationController = Ember.Controller.extend({
    isSignedIn: Ember.computed.bool('user.isSignedIn'),

    actions: {
        toggleMenu: function () {
            this.toggleProperty('showMenu');
        }
    }
});

export default ApplicationController;

redpajama_set_name: RedPajamaGithub


text:
"""Test Link functionality."""
#
# (C) Pywikipedia bot team, 2014
#
# Distributed under the terms of the MIT license.
#
from __future__ import unicode_literals

__version__ = '$Id: aa25b1639caf3feda0252e8537da36ea918e94e7 $'

import pywikibot
from pywikibot import config2 as config
from pywikibot.page import Link
from pywikibot.exceptions import Error, InvalidTitle
from tests.aspects import (
    unittest,
    AlteredDefaultSiteTestCase as LinkTestCase,
    DefaultDrySiteTestCase,
    WikimediaDefaultSiteTestCase,
    TestCase,
)

# ---- Tests checking if the parser does (not) accept (in)valid titles

class TestLink(DefaultDrySiteTestCase):

    """
    Test parsing links with DrySite.

    The DrySite is using the builtin namespaces which behaviour is controlled
    in this repository so namespace aware tests do work, even when the actual
    default site is using completely different namespaces.
    """

    def test_valid(self):
        """Test that valid titles are correctly normalized."""
        self.assertEqual(Link('Sandbox', self.get_site()).title, 'Sandbox')
        self.assertEqual(Link('A "B"', self.get_site()).title, 'A "B"')
        self.assertEqual(Link('A \'B\'', self.get_site()).title, 'A \'B\'')
        self.assertEqual(Link('.com', self.get_site()).title, '.com')
        self.assertEqual(Link('~', self.get_site()).title, '~')
        self.assertEqual(Link('"', self.get_site()).title, '"')
        self.assertEqual(Link('\'', self.get_site()).title, '\'')
        self.assertEqual(Link('Talk:Sandbox', self.get_site()).title, 'Sandbox')
        self.assertEqual(Link('Talk:Foo:Sandbox', self.get_site()).title, 'Foo:Sandbox')
        self.assertEqual(Link('File:Example.svg', self.get_site()).title, 'Example.svg')
        self.assertEqual(Link('File_talk:Example.svg', self.get_site()).title, 'Example.svg')
        self.assertEqual(Link('Foo/.../Sandbox', self.get_site()).title, 'Foo/.../Sandbox')
        self.assertEqual(Link('Sandbox/...', self.get_site()).title, 'Sandbox/...')
        self.assertEqual(Link('A~~', self.get_site()).title, 'A~~')
        self.assertEqual(Link(':A', self.get_site()).title, 'A')
        # Length is 256 total, but only title part matters
        self.assertEqual(Link('Category:' + 'X' * 248, self.get_site()).title, 'X' * 248)
        self.assertEqual(Link('X' * 252, self.get_site()).title, 'X' * 252)
        self.assertEqual(Link('A%20B', self.get_site()).title, 'A B')
        self.assertEqual(Link('A é B', self.get_site()).title, u'A é B')
        self.assertEqual(Link('A é B', self.get_site()).title, u'A é B')
        self.assertEqual(Link('A é B', self.get_site()).title, u'A é B')

        l = Link('A | B', self.get_site())
        self.assertEqual(l.title, 'A')
        self.assertEqual(l.anchor, ' B')

        l = Link('A%23B', self.get_site())
        self.assertEqual(l.title, 'A')
        self.assertEqual(l.section, 'B')

    def test_invalid(self):
        """Test that invalid titles raise InvalidTitle exception."""
        self.assertRaises(InvalidTitle, Link('', self.get_site()).parse)
        self.assertRaises(InvalidTitle, Link(':', self.get_site()).parse)
        self.assertRaises(InvalidTitle, Link('__  __', self.get_site()).parse)
        self.assertRaises(InvalidTitle, Link('  __  ', self.get_site()).parse)
        # Bad characters forbidden regardless of wgLegalTitleChars
        self.assertRaises(InvalidTitle, Link('A [ B', self.get_site()).parse)
        self.assertRaises(InvalidTitle, Link('A ] B', self.get_site()).parse)
        self.assertRaises(InvalidTitle, Link('A { B', self.get_site()).parse)
        self.assertRaises(InvalidTitle, Link('A } B', self.get_site()).parse)
        self.assertRaises(InvalidTitle, Link('A < B', self.get_site()).parse)
        self.assertRaises(InvalidTitle, Link('A > B', self.get_site()).parse)
        # URL encoding
        # %XX is understood by wikimedia but not %XXXX
        self.assertRaises(InvalidTitle, Link('A%2523B', self.get_site()).parse)
        # A link is invalid if their (non-)talk page would be in another
        # namespace than the link's "other" namespace
        self.assertRaises(InvalidTitle, Link('Talk:File:Example.svg', self.get_site()).parse)
        # Directory navigation
        self.assertRaises(InvalidTitle, Link('.', self.get_site()).parse)
        self.assertRaises(InvalidTitle, Link('..', self.get_site()).parse)
        self.assertRaises(InvalidTitle, Link('./Sandbox', self.get_site()).parse)
        self.assertRaises(InvalidTitle, Link('../Sandbox', self.get_site()).parse)
        self.assertRaises(InvalidTitle, Link('Foo/./Sandbox', self.get_site()).parse)
        self.assertRaises(InvalidTitle, Link('Foo/../Sandbox', self.get_site()).parse)
        self.assertRaises(InvalidTitle, Link('Sandbox/.', self.get_site()).parse)
        self.assertRaises(InvalidTitle, Link('Sandbox/..', self.get_site()).parse)
        # Tilde
        self.assertRaises(InvalidTitle, Link('A ~~~ Name', self.get_site()).parse)
        self.assertRaises(InvalidTitle, Link('A ~~~~ Signature', self.get_site()).parse)
        self.assertRaises(InvalidTitle, Link('A ~~~~~ Timestamp', self.get_site()).parse)
        # Overlength
        self.assertRaises(InvalidTitle, Link('x' * 256, self.get_site()).parse)
        self.assertRaises(InvalidTitle, Link('Invalid:' + 'X' * 248, self.get_site()).parse)
        # Namespace prefix without actual title
        self.assertRaises(InvalidTitle, Link('Talk:', self.get_site()).parse)
        self.assertRaises(InvalidTitle, Link('Category: ', self.get_site()).parse)
        self.assertRaises(InvalidTitle, Link('Category: #bar', self.get_site()).parse)

# ---- The first set of tests are explicit links, starting with a ':'.

class TestPartiallyQualifiedExplicitLinkSameSiteParser(LinkTestCase):

    """Link tests."""

    family = 'wikipedia'
    code = 'en'
    cached = True

    def test_partially_qualified_NS0_code(self):
        """Test ':wikipedia:Main Page' on enwp is namespace 4."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link(':wikipedia:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 4)

    def test_partially_qualified_NS1_code(self):
        """Test ':wikipedia:Talk:Main Page' on enwp is namespace 4."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link(':wikipedia:Talk:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Talk:Main Page')
        self.assertEqual(link.namespace, 4)

    def test_partially_qualified_NS0_family(self):
        """Test ':en:Main Page' on enwp is namespace 0."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link(':en:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 0)

    def test_partially_qualified_NS1_family(self):
        """Test ':en:Talk:Main Page' on enwp is namespace 1."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link(':en:Talk:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 1)

class TestPartiallyQualifiedExplicitLinkDifferentCodeParser(LinkTestCase):

    """Link tests."""

    family = 'wikipedia'
    code = 'en'
    cached = True

    def test_partially_qualified_NS0_family(self):
        """Test ':en:Main Page' on dewp is namespace 0."""
        config.mylang = 'de'
        config.family = 'wikipedia'
        link = Link(':en:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 0)

    def test_partially_qualified_NS1_family(self):
        """Test ':en:Talk:Main Page' on dewp is namespace 1."""
        config.mylang = 'de'
        config.family = 'wikipedia'
        link = Link(':en:Talk:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 1)

class TestPartiallyQualifiedExplicitLinkDifferentFamilyParser(LinkTestCase):

    """Link tests."""

    family = 'wikipedia'
    code = 'en'
    cached = True

    def test_partially_qualified_NS0_code(self):
        """Test ':wikipedia:Main Page' on enws is namespace 0."""
        config.mylang = 'en'
        config.family = 'wikisource'
        link = Link(':wikipedia:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 0)

    def test_partially_qualified_NS1_code(self):
        """Test ':wikipedia:Talk:Main Page' on enws is ns 1."""
        config.mylang = 'en'
        config.family = 'wikisource'
        link = Link(':wikipedia:Talk:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 1)

class TestFullyQualifiedSameNamespaceFamilyParser(LinkTestCase):

    """Link tests."""

    family = 'wikipedia'
    code = 'en'
    cached = True

    def test_namespace_vs_family(self):
        """Test namespace is selected before family."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link(':wikipedia:en:Main Page')
        link.parse()
        self.assertEqual(link.title, 'En:Main Page')
        self.assertEqual(link.namespace, 4)

        link = Link(':wikipedia:en:Talk:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'En:Talk:Main Page')
        self.assertEqual(link.namespace, 4)

class TestFullyQualifiedExplicitLinkSameFamilyParser(LinkTestCase):

    """Link tests."""

    family = 'wikipedia'
    code = 'en'
    cached = True

    def test_fully_qualified_NS0_code(self):
        """Test ':en:wikipedia:Main Page' on enwp is namespace 4."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link(':en:wikipedia:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 4)

    def test_fully_qualified_NS1_code(self):
        """Test ':en:wikipedia:Talk:Main Page' on enwp is namespace 4."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link(':en:wikipedia:Talk:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Talk:Main Page')
        self.assertEqual(link.namespace, 4)

class TestFullyQualifiedExplicitLinkDifferentFamilyParser(LinkTestCase):

    """Link tests."""

    sites = {
        'enws': {
            'family': 'wikisource',
            'code': 'en'
        },
        'enwp': {
            'family': 'wikipedia',
            'code': 'en'
        }
    }
    cached = True

    def test_fully_qualified_NS0_code(self):
        """Test ':en:wikipedia:Main Page' on enws is namespace 0."""
        config.mylang = 'en'
        config.family = 'wikisource'
        link = Link(':en:wikipedia:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site('enwp'))
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 0)

    def test_fully_qualified_NS1_code(self):
        """Test ':en:wikipedia:Main Page' on enwp is namespace 1."""
        config.mylang = 'en'
        config.family = 'wikisource'
        link = Link(':en:wikipedia:Talk:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site('enwp'))
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 1)

    def test_fully_qualified_NS0_family(self):
        """Test ':wikipedia:en:Main Page' on enws is namespace 0."""
        config.mylang = 'en'
        config.family = 'wikisource'
        link = Link(':wikipedia:en:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site('enwp'))
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 0)

    def test_fully_qualified_NS1_family(self):
        """Test ':wikipedia:en:Talk:Main Page' on enws is namespace 1."""
        config.mylang = 'en'
        config.family = 'wikisource'
        link = Link(':wikipedia:en:Talk:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site('enwp'))
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 1)

class TestFullyQualifiedExplicitLinkNoLangConfigFamilyParser(LinkTestCase):

    """Link tests."""

    sites = {
        'wikidata': {
            'family': 'wikidata',
            'code': 'wikidata'
        },
        'enwp': {
            'family': 'wikipedia',
            'code': 'en'
        }
    }
    cached = True

    def test_fully_qualified_NS0_code(self):
        """Test ':en:wikipedia:Main Page' on wikidata is namespace 4."""
        config.mylang = 'wikidata'
        config.family = 'wikidata'
        link = Link(':en:wikipedia:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site('enwp'))
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 4)

    def test_fully_qualified_NS1_code(self):
        """Test ':en:wikipedia:Talk:Main Page' on wikidata is namespace 4."""
        config.mylang = 'wikidata'
        config.family = 'wikidata'
        link = Link(':en:wikipedia:Talk:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site('enwp'))
        self.assertEqual(link.title, 'Talk:Main Page')
        self.assertEqual(link.namespace, 4)

    def test_fully_qualified_NS0_family(self):
        """Test ':wikipedia:en:Main Page' on wikidata is namespace 0."""
        config.mylang = 'wikidata'
        config.family = 'wikidata'
        link = Link(':wikipedia:en:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site('enwp'))
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 0)

    def test_fully_qualified_NS1_family(self):
        """Test ':wikipedia:en:Talk:Main Page' on wikidata is namespace 1."""
        config.mylang = 'wikidata'
        config.family = 'wikidata'
        link = Link(':wikipedia:en:Talk:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site('enwp'))
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 1)

class TestFullyQualifiedNoLangFamilyExplicitLinkParser(LinkTestCase):

    """Link tests."""

    sites = {
        'wikidata': {
            'family': 'wikidata',
            'code': 'wikidata'
        },
        'enwp': {
            'family': 'wikipedia',
            'code': 'en'
        },
        'test.wp': {
            'family': 'wikipedia',
            'code': 'test'
        },
    }
    cached = True

    def test_fully_qualified_NS0_code(self):
        """Test ':testwiki:wikidata:Q6' on enwp is namespace 0."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link(':testwiki:wikidata:Q6')
        link.parse()
        self.assertEqual(link.site, self.get_site('wikidata'))
        self.assertEqual(link.title, 'Q6')
        self.assertEqual(link.namespace, 0)

    def test_fully_qualified_NS1_code(self):
        """Test ':testwiki:wikidata:Talk:Q6' on enwp is namespace 1."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link(':testwiki:wikidata:Talk:Q6')
        link.parse()
        self.assertEqual(link.site, self.get_site('wikidata'))
        self.assertEqual(link.title, 'Q6')
        self.assertEqual(link.namespace, 1)

    def test_fully_qualified_NS0_family(self):
        """Test ':wikidata:testwiki:Q6' on enwp is namespace 0."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link(':wikidata:testwiki:Q6')
        link.parse()
        self.assertEqual(link.site, self.get_site('test.wp'))
        self.assertEqual(link.title, 'Q6')
        self.assertEqual(link.namespace, 0)

    def test_fully_qualified_NS1_family(self):
        """Test ':wikidata:testwiki:Talk:Q6' on enwp is namespace 1."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link(':wikidata:testwiki:Talk:Q6')
        link.parse()
        self.assertEqual(link.site, self.get_site('test.wp'))
        self.assertEqual(link.title, 'Q6')
        self.assertEqual(link.namespace, 1)

class TestFullyQualifiedOneSiteFamilyExplicitLinkParser(LinkTestCase):

    """Link tests."""

    family = 'species'
    code = 'species'
    cached = True

    def test_fully_qualified_NS0_code(self):
        """Test ':species:species:Main Page' on species is namespace 0."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link(':species:species:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 0)

    def test_fully_qualified_NS1_code(self):
        """Test ':species:species:Talk:Main Page' on species is namespace 1."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link(':species:species:Talk:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 1)

# ---- Tests of a Link without colons, which shouldnt be interwikis, follow.

class TestPartiallyQualifiedImplicitLinkSameSiteParser(LinkTestCase):

    """Link tests."""

    family = 'wikipedia'
    code = 'en'
    cached = True

    def test_partially_qualified_NS0_code(self):
        """Test 'wikipedia:Main Page' on enwp is namespace 4."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link('wikipedia:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 4)

    def test_partially_qualified_NS1_code(self):
        """Test 'wikipedia:Talk:Main Page' on enwp is namespace 4."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link('wikipedia:Talk:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Talk:Main Page')
        self.assertEqual(link.namespace, 4)

    def test_partially_qualified_NS0_family(self):
        """Test 'en:Main Page' on enwp is namespace 0."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link('en:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 0)

    def test_partially_qualified_NS1_family(self):
        """Test 'en:Talk:Main Page' on enwp is namespace 1."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link('en:Talk:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 1)

class TestPartiallyQualifiedImplicitLinkDifferentCodeParser(LinkTestCase):

    """Link tests."""

    family = 'wikipedia'
    code = 'en'
    cached = True

    def test_partially_qualified_NS0_family(self):
        """Test 'en:Main Page' on dewp  is namespace 0."""
        config.mylang = 'de'
        config.family = 'wikipedia'
        link = Link('en:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 0)

    def test_partially_qualified_NS1_family(self):
        """Test 'en:Talk:Main Page' on dewp is namespace 1."""
        config.mylang = 'de'
        config.family = 'wikipedia'
        link = Link('en:Talk:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 1)

class TestPartiallyQualifiedImplicitLinkDifferentFamilyParser(LinkTestCase):

    """Link tests."""

    family = 'wikipedia'
    code = 'en'
    cached = True

    def test_partially_qualified_NS0_code(self):
        """Test 'wikipedia:Main Page' on enws is namespace 0."""
        config.mylang = 'en'
        config.family = 'wikisource'
        link = Link('wikipedia:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 0)

    def test_partially_qualified_NS1_code(self):
        """Test 'wikipedia:Talk:Main Page' on enws is ns 1."""
        config.mylang = 'en'
        config.family = 'wikisource'
        link = Link('wikipedia:Talk:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 1)

class TestFullyQualifiedImplicitLinkSameFamilyParser(LinkTestCase):

    """Link tests."""

    family = 'wikipedia'
    code = 'en'
    cached = True

    def test_fully_qualified_NS0_code(self):
        """Test 'en:wikipedia:Main Page' on enwp is namespace 4."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link('en:wikipedia:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 4)

    def test_fully_qualified_NS1_code(self):
        """Test 'en:wikipedia:Talk:Main Page' on enwp is namespace 4."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link('en:wikipedia:Talk:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Talk:Main Page')
        self.assertEqual(link.namespace, 4)

class TestFullyQualifiedImplicitLinkDifferentFamilyParser(LinkTestCase):

    """Link tests."""

    sites = {
        'enws': {
            'family': 'wikisource',
            'code': 'en'
        },
        'enwp': {
            'family': 'wikipedia',
            'code': 'en'
        }
    }
    cached = True

    def test_fully_qualified_NS0_code(self):
        """Test 'en:wikipedia:Main Page' on enws is namespace 0."""
        config.mylang = 'en'
        config.family = 'wikisource'
        link = Link('en:wikipedia:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site('enwp'))
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 0)

    def test_fully_qualified_NS1_code(self):
        """Test 'en:wikipedia:Main Page' on enws is namespace 1."""
        config.mylang = 'en'
        config.family = 'wikisource'
        link = Link('en:wikipedia:Talk:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site('enwp'))
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 1)

    def test_fully_qualified_NS0_family(self):
        """Test 'wikipedia:en:Main Page' on enws is namespace 0."""
        config.mylang = 'en'
        config.family = 'wikisource'
        link = Link('wikipedia:en:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site('enwp'))
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 0)

    def test_fully_qualified_NS1_family(self):
        """Test 'wikipedia:en:Talk:Main Page' on enws is namespace 1."""
        config.mylang = 'en'
        config.family = 'wikisource'
        link = Link('wikipedia:en:Talk:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site('enwp'))
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 1)

class TestFullyQualifiedImplicitLinkNoLangConfigFamilyParser(LinkTestCase):

    """Link tests."""

    sites = {
        'wikidata': {
            'family': 'wikidata',
            'code': 'wikidata'
        },
        'enwp': {
            'family': 'wikipedia',
            'code': 'en'
        }
    }
    cached = True

    def test_fully_qualified_NS0_code(self):
        """Test 'en:wikipedia:Main Page' on wikidata is namespace 4."""
        config.mylang = 'wikidata'
        config.family = 'wikidata'
        link = Link('en:wikipedia:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site('enwp'))
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 4)

    def test_fully_qualified_NS1_code(self):
        """Test 'en:wikipedia:Talk:Main Page' on wikidata is not namespace 1."""
        config.mylang = 'wikidata'
        config.family = 'wikidata'
        link = Link('en:wikipedia:Talk:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site('enwp'))
        self.assertEqual(link.title, 'Talk:Main Page')
        self.assertEqual(link.namespace, 4)

    def test_fully_qualified_NS0_family(self):
        """Test 'wikipedia:en:Main Page' on wikidata is namespace 0."""
        config.mylang = 'wikidata'
        config.family = 'wikidata'
        link = Link('wikipedia:en:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site('enwp'))
        self.assertEqual(link.namespace, 0)
        self.assertEqual(link.title, 'Main Page')

    def test_fully_qualified_NS1_family(self):
        """Test 'wikipedia:en:Talk:Main Page' on wikidata is namespace 1."""
        config.mylang = 'wikidata'
        config.family = 'wikidata'
        link = Link('wikipedia:en:Talk:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site('enwp'))
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 1)

class TestFullyQualifiedNoLangFamilyImplicitLinkParser(LinkTestCase):

    """Link tests."""

    family = 'wikidata'
    code = 'test'
    cached = True

    def test_fully_qualified_NS0_code(self):
        """Test 'testwiki:wikidata:Q6' on enwp is namespace 0."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link('testwiki:wikidata:Q6')
        link.parse()
        self.assertEqual(link.site, pywikibot.Site('wikidata', 'wikidata'))
        self.assertEqual(link.title, 'Q6')
        self.assertEqual(link.namespace, 0)

    def test_fully_qualified_NS1_code(self):
        """Test 'testwiki:wikidata:Talk:Q6' on enwp is namespace 1."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link('testwiki:wikidata:Talk:Q6')
        link.parse()
        self.assertEqual(link.site, pywikibot.Site('wikidata', 'wikidata'))
        self.assertEqual(link.title, 'Q6')
        self.assertEqual(link.namespace, 1)

    def test_fully_qualified_NS0_family(self):
        """Test 'wikidata:testwiki:Q6' on enwp is namespace 0."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link('wikidata:testwiki:Q6')
        link.parse()
        self.assertEqual(link.site, pywikibot.Site('test', 'wikipedia'))
        self.assertEqual(link.title, 'Q6')
        self.assertEqual(link.namespace, 0)

    def test_fully_qualified_NS1_family(self):
        """Test 'wikidata:testwiki:Talk:Q6' on enwp is namespace 1."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link('wikidata:testwiki:Talk:Q6')
        link.parse()
        self.assertEqual(link.site, pywikibot.Site('test', 'wikipedia'))
        self.assertEqual(link.title, 'Q6')
        self.assertEqual(link.namespace, 1)

class TestFullyQualifiedOneSiteFamilyImplicitLinkParser(LinkTestCase):

    """Link tests."""

    family = 'species'
    code = 'species'
    cached = True

    def test_fully_qualified_NS0_family_code(self):
        """Test 'species:species:Main Page' on enwp is namespace 0."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link('species:species:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 0)

    def test_fully_qualified_NS1_family_code(self):
        """Test 'species:species:Talk:Main Page' on enwp is namespace 1."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link('species:species:Talk:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 1)

    def test_fully_qualified_NS0_code(self):
        """Test 'species:Main Page' on enwp is namespace 0."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link('species:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 0)

    def test_fully_qualified_NS1_code(self):
        """Test 'species:Talk:Main Page' on enwp is namespace 1."""
        config.mylang = 'en'
        config.family = 'wikipedia'
        link = Link('species:Talk:Main Page')
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'Main Page')
        self.assertEqual(link.namespace, 1)

class TestEmptyTitle(TestCase):

    """Test links which contain no title."""

    family = 'wikipedia'
    code = 'en'

    def test_interwiki_mainpage(self):
        """Test that Link allow links without a title to the main page."""
        link = Link('en:', self.get_site())
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, '')
        self.assertEqual(link.namespace, 0)

    def test_interwiki_namespace_without_title(self):
        """Test that Link doesn't allow links without a title."""
        link = Link('en:Help:', self.get_site())
        self.assertRaisesRegex(
            InvalidTitle, "'en:Help:' has no title.", link.parse)

    def test_no_text(self):
        """Test that Link doesn't allow empty."""
        link = Link('', self.get_site())
        self.assertRaisesRegex(
            InvalidTitle, "The link does not contain a page title", link.parse)

    def test_namespace_lookalike(self):
        """Test that Link does only detect valid namespaces."""
        link = Link('CAT:', self.get_site())
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'CAT:')
        self.assertEqual(link.namespace, 0)

        link = Link('en:CAT:', self.get_site())
        link.parse()
        self.assertEqual(link.site, self.get_site())
        self.assertEqual(link.title, 'CAT:')
        self.assertEqual(link.namespace, 0)

class TestInvalidInterwikiLinks(WikimediaDefaultSiteTestCase):

    """Test links to non-wikis."""

    family = 'wikipedia'
    code = 'en'

    def test_non_wiki_prefix(self):
        """Test that Link fails if the interwiki prefix is not a wiki."""
        link = Link('bugzilla:1337', source=self.site)
        self.assertRaisesRegex(
            Error,
            'bugzilla:1337 is not a local page on wikipedia:en, and the '
            'interwiki prefix bugzilla is not supported by Pywikibot!',
            link.parse)

    def test_other_wiki_prefix(self):
        """Test that Link fails if the interwiki prefix is a unknown family."""
        link = Link('bulba:this-will-never-work', source=self.site)
        self.assertRaisesRegex(
            Error,
            'bulba:this-will-never-work is not a local page on wikipedia:en, '
            'and the interwiki prefix bulba is not supported by Pywikibot!',
            link.parse)

if __name__ == '__main__':
    try:
        unittest.main()
    except SystemExit:
        pass


text:
package mf.org.apache.xerces.impl.dv.dtd;

import mf.org.apache.xerces.impl.dv.InvalidDatatypeValueException;
import mf.org.apache.xerces.impl.dv.ValidationContext;
import mf.org.apache.xerces.util.XML11Char;

/**
 *
IDREFDatatypeValidator - represents the IDREFS
 * attribute type from XML 1.1 recommendation. The
 * Value Space of IDREF is the set of all strings
 * that match the NCName production and have been
 * used in an XML Document as the value of an element
 * or attribute of Type ID. The Lexical space of
 * IDREF is the set of strings that match the NCName
 * production.

 *
The Value space of IDREF is scoped to a specific
 * instance document

 *
 * @xerces.internal
 *
 * @author Jeffrey Rodriguez, IBM
 * @author Sandy Gao, IBM
 * @author Neil Graham, IBM
 *
 * @version $Id: XML11IDREFDatatypeValidator.java 699892 2008-09-28 21:08:27Z mrglavas $
 */
public class XML11IDREFDatatypeValidator extends IDREFDatatypeValidator {

    // construct an IDREF datatype validator
    public XML11IDREFDatatypeValidator() {
        super();
    }

    /**
     * Checks that "content" string is valid IDREF value.
     * If invalid a Datatype validation exception is thrown.
     *
     * @param content       the string value that needs to be validated
     * @param context       the validation context
     * @throws InvalidDatatypeException if the content is
     *         invalid according to the rules for the validators
     * @see InvalidDatatypeValueException
     */
    public void validate(String content, ValidationContext context) throws InvalidDatatypeValueException {

        //Check if is valid key-[81] EncName ::= [A-Za-z] ([A-Za-z0-9._] | '-')*
        if(context.useNamespaces()) {
            if (!XML11Char.isXML11ValidNCName(content)) {
                throw new InvalidDatatypeValueException("IDREFInvalidWithNamespaces", new Object[]{content});
            }
        }
        else {
            if (!XML11Char.isXML11ValidName(content)) {
                throw new InvalidDatatypeValueException("IDREFInvalid", new Object[]{content});
            }
        }

        context.addIdRef(content);

    }

}


text:
require File.expand_path('../spec_helper', __FILE__)
require 'media_api'

### FIXME: P in Part is capitalized here, but not for others. Standardize.
describe VideoApi::Multipart::StreamPart do

  let(:klass) { VideoApi::Multipart::StreamPart }

  let(:stream)            { mock(Symbol) }
  let(:size)              { mock(Symbol) }
  let(:progress_listener) { lambda { |x| "PL received #{x}" } }

  describe "Constants"

  describe "#initialize" do
    let(:meth) { :new }
    context "when given stream, size, &progress_listener" do
      it "should assign stream into @stream" do
        obj = klass.send(meth, stream, size, &progress_listener)
        obj.instance_variable_get(:@stream).should == stream
      end
      it "should assign size into @size" do
        obj = klass.send(meth, stream, size, &progress_listener)
        obj.instance_variable_get(:@size).should == size
      end
      it "should assign &progress_listener into @progress_listener" do
        obj = klass.send(meth, stream, size, &progress_listener)
        obj.instance_variable_get(:@progress_listener).should == progress_listener
      end
    end
  end

  describe "an instance" do
    let(:obj)  { klass.new(stream, size, &progress_listener) }

    describe "#read" do
      let(:meth) { :read }
      context "when given offset, how_much" do
        let(:offset)   { mock(Symbol) }
        let(:how_much) { mock(Symbol) }
        let(:data)     { mock(Symbol, :length => :data_length) }
        before(:each) do
          stream.stub!(:read).and_return(data)
          stream.stub!(:eof?).and_return(false)
        end
        it "should @stream.read(how_much) -> data" do
          stream.should_receive(:read).with(how_much).and_return(data)
          obj.send(meth, offset, how_much)
        end
        it "should return data" do
          obj.send(meth, offset, how_much).should == data
        end
        context "and @progress_listener is truthy" do
          it "should @progress_listener.call(data.length)" do
            data.should_receive(:length).and_return(:data_length)
            progress_listener.should_receive(:call).with(:data_length)
            obj.send(meth, offset, how_much)
          end
        end
        context "and @stream.eof? is truthy" do
          before(:each) do stream.stub!(:eof?).and_return(:something_truthy) end
          it "should close @stream" do
            stream.should_receive(:close)
            obj.send(meth, offset, how_much)
          end
        end
      end
    end

    describe "#size" do
      let(:meth) { :size }
      it "should return @size" do
        obj.instance_variable_set(:@size, :expected)
        obj.send(meth).should == :expected
      end
    end

  end

end


text:
require 'pry'
require 'matrix'

class Matrix
  def []=(i, j, x)
    @rows[i][j] = x
  end

  def same(matrix)
  	self.coordinate_sort == matrix.coordinate_sort
  end

  def coordinate_sort
  	result = []

  	column_count.times do |index|
			col = column(index)
			x, y = col[0], col[1]
			result << [x, y]
		end

  	result.sort
  end
end

class Paper
	SHAPE_CHAR = "\u25FC"
	SHAPE_ORIGIN_CHAR = "\u25A3"
	ORIGIN_CHAR = "\u25A2"
	DEFAULT_DIMENSION = 11

	def initialize(matrix, title=nil, height=DEFAULT_DIMENSION, width=DEFAULT_DIMENSION)
		@matrix = matrix
		@title = title
		@height = height
		@width = width
	end

	def plot
		draw_matrix
		print
	end

	private

	def draw_matrix
		@paper = Matrix.build(@height, @width) { '.' }
		x_origin = (@width / 2)
		y_origin = (@height / 2)

		# assumes the input matix is 2xN
		@matrix.column_count.times do |index|
			col = @matrix.column(index)
			x, y = col[0], col[1]
			@paper[y_origin+y, x_origin+x] = SHAPE_CHAR
		end

		# set the origin marker
		origin_covered = @paper[x_origin, y_origin] == SHAPE_CHAR
		@paper[x_origin, y_origin] = origin_covered ? SHAPE_ORIGIN_CHAR : ORIGIN_CHAR
	end

	def print
		puts
		puts "# #{@title}" if @title
		puts @matrix
		puts @paper.to_a.map { |row| row.join(' ') }
	end
end

class BlockDefinition < Struct.new(:name, :matrix)
	def dimensions
		r, c = matrix.row_count, matrix.column_count
		return r, c
	end

	def size
		matrix.column_count
	end
end

Transform = BlockDefinition
UserShape = BlockDefinition

def plot_transformed_block(transform, block)
	result = transform.matrix * block.matrix
	Paper.new(result, "#{transform.name} #{block.name}").plot
end

TRANSFORMS = {
	:rot_90_c => Transform.new("rotate 90 clockwise", Matrix[[0, 1], [-1, 0]]),
	:rot_90_ac => Transform.new("rotate 90 anticlockwise", Matrix[[0, -1], [1, 0]]),
	:rot_180 => Transform.new("rotate 180", Matrix[[-1, 0], [0, -1]]),
	:reflect_x => Transform.new("reflect on x axis", Matrix[[1, 0], [0, -1]]),
	:reflect_y => Transform.new("reflect on y axis", Matrix[[-1, 0], [0, 1]]),
	:identity => Transform.new("identity", Matrix[[1,0],[0, 1]]),
	:reflect_y_x => Transform.new("reflect_y_x", Matrix[[0, 1], [1, 0]]),
	:reflect_y_negative_x => Transform.new("reflect_y_negative_x", Matrix[[0, -1], [-1, 0]])
}

BLOCKS = {
	:four_z => BlockDefinition.new("four_z", Matrix[[0, 0, 1, 1], [0, 1, 1, 2]]),
	:five_z => BlockDefinition.new("five_z", Matrix[[0, 1, 1, 1, 2], [0, 0, 1, 2, 2]]),
	:unbalanced_z => BlockDefinition.new("unbalanced_z", Matrix[[0, 0, 1, 1, 1], [0, 1, 1, 2, 3]]),
	:space_ship => BlockDefinition.new("space_ship", Matrix[[0, 1, 1, 2, 2], [0, 0, 1, 1, 2]]),
	:cross => BlockDefinition.new("cross", Matrix[[0, 1, 1, 2, 1], [1, 0, 1, 1, 2]]),
	:large_square => BlockDefinition.new("large square", Matrix[[0, 0, 1, 1],[0, 1, 1, 0]]),
	:small_square => BlockDefinition.new("small square", Matrix[[0],[0]]),
	:two_line => BlockDefinition.new("two line", Matrix[[0, 0],[0, 1]]),
	:three_line => BlockDefinition.new("three line", Matrix[[0, 0, 0],[0, 1, 2]]),
	:four_line => BlockDefinition.new("four line", Matrix[[0, 0, 0, 0],[0, 1, 2, 3]]),
	:five_line => BlockDefinition.new("five line", Matrix[[0, 0, 0, 0, 0],[0, 1, 2, 3, 4]]),
	:large_corner => BlockDefinition.new("large corner", Matrix[[0, 0, 0, 1, 2],[0, 1, 2, 2, 2]]),
	:small_corner => BlockDefinition.new("small corner", Matrix[[0, 0, 1],[0, 1, 1]]),
	:large_l => BlockDefinition.new("large l", Matrix[[0, 1, 0, 0, 0],[0, 0, 1, 2, 3]]),
	:small_l => BlockDefinition.new("small l", Matrix[[0, 1, 0, 0],[0, 0, 1, 2]]),
	:ewe => BlockDefinition.new("ewe", Matrix[[0, 1, 2, 0, 2],[0, 0, 0, 1, 1]]),
	:short_t => BlockDefinition.new("short t", Matrix[[1, 0, 1, 2],[0, 1, 1, 1]]),
	:long_t => BlockDefinition.new("long t", Matrix[[1, 1, 0, 1, 2],[0, 1, 2, 2, 2]]),
	:stylish => BlockDefinition.new("stylish", Matrix[[1, 1, 2, 0, 1],[0, 1, 1, 2, 2]]),
	:conjoined_squares => BlockDefinition.new("conjoined squares", Matrix[[0, 1, 0, 1, 0],[0, 0, 1, 1, 2]]),
	:line_with_growth => BlockDefinition.new("line with growth", Matrix[[0, 0, 0, 1, 0],[0, 1, 2, 2, 3]])
}

def map_matrix_to_origin(matrix)
	x_row = matrix.row(0).to_a
	y_row = matrix.row(1).to_a
	min_x = x_row.min
	min_y = y_row.min

	new_matrix = matrix.dup

	matrix.column_count.times do |index|
		col = matrix.column(index)
		x, y = col[0], col[1]

		new_matrix[0, index] = x - min_x
		new_matrix[1, index] = y - min_y
	end

	new_matrix
end

def same_dimensions?(shape_definition, unknown_shape)
	shape_definition.dimensions == unknown_shape.dimensions
end

def are_same_shape?(shape_definition, unknown_shape)
	return false unless same_dimensions?(shape_definition, unknown_shape)

	t = [
		TRANSFORMS[:identity],
		TRANSFORMS[:reflect_x],
		TRANSFORMS[:reflect_y],
		TRANSFORMS[:rot_180],
		TRANSFORMS[:rot_90_ac],
		TRANSFORMS[:rot_90_c],
		TRANSFORMS[:reflect_y_x],
		TRANSFORMS[:reflect_y_negative_x],
	]

	t.length.times do |index|
		unknown_shape_at_origin = map_matrix_to_origin(unknown_shape.matrix)
		transformed_shape = map_matrix_to_origin(t[index].matrix*shape_definition.matrix)
		return true if unknown_shape_at_origin.same(transformed_shape)
	end

	return false
end

def find_shape_name(unknown_shape)
	# no point checking shapes of a different size
	BLOCKS.find_all { |name, block| block.size == unknown_shape.size }.each do |name, block|
		if are_same_shape?(block, unknown_shape)
			return name.to_s
		end
	end

	return "not a known block shape"
end

# plot_transformed_block(TRANSFORMS[:identity], BLOCKS[:small_corner])
# plot_transformed_block(TRANSFORMS[:reflect_x], BLOCKS[:small_corner])

# result = TRANSFORMS[:reflect_x].matrix * BLOCKS[:small_corner].matrix
# result = map_matrix_to_origin(result)
# Paper.new(result, "moved to origin").plot

# line = BLOCKS[:five_line]
# moved_line = UserShape.new("five line moved", Matrix[[7, 8, 9, 10, 11], [4, 4, 4, 4, 4]])

# shapes_match = are_same_shape?(line, moved_line)
# puts "Recognises transformed shape: #{shapes_match}"

# unknown_shape = UserShape.new("unknown", Matrix[[9, 8, 9, 10, 8], [8, 9, 9, 9, 10]])
# shape_name = find_shape_name(unknown_shape)
# puts "Shape name of #{unknown_shape.name} is #{shape_name}"

# u_origin = map_matrix_to_origin(unknown_shape.matrix)
# transformed_block = map_matrix_to_origin(TRANSFORMS[:reflect_y_negative_x].matrix * BLOCKS[:stylish].matrix)

# Paper.new(BLOCKS[:stylish].matrix, "stylish").plot

# title = "Unknown shape at origin"
# Paper.new(u_origin, title).plot
# puts u_origin

# title = "Transformed stylish"
# Paper.new(transformed_block, title).plot
# puts transformed_block

# class BlockDefinitionContainer
# 	def self.[](name)
# 		BLOCKS[name]
# 	end
# end

# small_square = BlockDefinitionContainer[:small_square]
# puts "Matrix of small square: #{small_square.matrix}"

BLOCKS.values.each { |block| Paper.new(block.matrix, block.name).plot }


text:
Peezy
=====
A very random Noire game that we have come to love.

**Licensed under MIT.**


text:
package com.panaceamobile.panacea.sdk.webservices;

import com.panaceamobile.panacea.sdk.PMConstants;
import com.panaceamobile.panacea.sdk.PMPreferencesHelper;
import com.panaceamobile.panacea.sdk.PanaceaSDK;
import com.panaceamobile.panacea.sdk.PanaceaSDK.Tag;
import com.panaceamobile.panacea.sdk.messaging.PMLocalBroadcastReceiver;
import com.panaceamobile.panacea.sdk.model.PMBaseResponse;
import com.panaceamobile.panacea.sdk.web.HttpPost.Observer;

public class UpdatePreferencesObserver implements Observer {

	String channel_key;
	String given_name;
	public UpdatePreferencesObserver(String channel_key, String given_name)
	{
		this.channel_key = channel_key;
		this.given_name = given_name;
	}

	public void postCompleted(String data) {
		PMBaseResponse response;
		try {
			System.out.println("Update Channel Key returns result:"+ data);
			response = new PMBaseResponse(data);

			//Generic response - these variables will be changed for the specific responses
			String result = PanaceaSDK.Result.PANACEA_ERROR_CODE;
			int status = response.getStatus();
			String message = response.getDescription();

			//save push notification key
			if (response.getStatus() == PMConstants.Status.OK)
			{
				//if push notification key was included
				if (channel_key != null)
				{
					PMPreferencesHelper.setPushNotificationKey(channel_key);

					//registration good go to inbox
					result = PanaceaSDK.Result.PUSH_KEY_UPDATED;
				}
				if(given_name!=null)
				{
					PMPreferencesHelper.setGivenName(given_name);
					result = PanaceaSDK.Result.GIVEN_NAME_UPDATED;
				}

				//Send successful broadcast
				PMLocalBroadcastReceiver.sendPostDataSuccess(Tag.REGISTER, result,
					status, message,PMWebServiceController.IntentAction.WebService.DEVICE_UPDATE_PREFERENCES);

				System.out.println("Update Preferences success - Result:"+ result + " Message:");
			}

			//Send successful broadcast
			PMLocalBroadcastReceiver.sendPostDataFailure(Tag.REGISTER, result,
				status, message,PMWebServiceController.IntentAction.WebService.DEVICE_UPDATE_PREFERENCES);

			System.out.println("Update Preferences failure - Result:"+ result + " Message:" + message);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void postError(Exception e) {
		// TODO Auto-generated method stub

	}

}


text:
import React from 'react';
import { FormattedHTMLMessage } from 'react-intl';
import styled from 'styled-components';
import { accent2Color, brandSecondary } from '../theme';

const SaleTitle = styled.h1`
  text-align: center;
  color: ${brandSecondary};
`;

const SaleSlogan = styled.h2`
  text-align: center;
  position: relative;
  color: ${accent2Color};
`;

export default () => (
  <div>
    <SaleTitle>
      Grosser Ausverkauf!
    </SaleTitle>
    <SaleSlogan>
      <FormattedHTMLMessage id="HOME.SALE" />
    </SaleSlogan>
  </div>
);


text:
package org.apache.ignite.console.configuration;

import java.util.Set;

/**
 * Service class with list of generated by configurator, known deprecated, and excluded from configurator fields.
 */
@SuppressWarnings("AssignmentOrReturnOfFieldWithMutableType")
public class MetadataInfo {
    /** List of generated fields. */
    private final Set<String> generatedFields;

    /** List of deprecated fields. */
    private final Set<String> deprecatedFields;

    /** List of excluded fields. */
    private final Set<String> excludedFields;

    /**
     * Constructor.
     *
     * @param generatedFields List of generated fields.
     * @param deprecatedFields List of deprecated fields.
     * @param excludedFields List of excluded fields.
     */
    public MetadataInfo(Set<String> generatedFields, Set<String> deprecatedFields, Set<String> excludedFields) {
        this.generatedFields = generatedFields;
        this.deprecatedFields = deprecatedFields;
        this.excludedFields = excludedFields;
    }

    /**
     * @return List of generated fields.
     */
    public Set<String> getGeneratedFields() {
        return generatedFields;
    }

    /**
     * @return List of deprecated fields.
     */
    public Set<String> getDeprecatedFields() {
        return deprecatedFields;
    }

    /**
     * @return List of excluded fields.
     */
    public Set<String> getExcludedFields() {
        return excludedFields;
    }
}


text:
usage() {
  echo "Usage: "
  echo "    ${0} <ethernet name> <port> <destination server ip> <port> [multiport placeholder]"
  echo "        if multiport placeholder has value, the port should be <num>,<num>,..."
}

if [ $# -lt 4 -o $# -gt 5 ]; then
  usage
  exit 1
elif [ $# -eq 4 ]; then
  iptables -t nat -D PREROUTING -p tcp -i ${1} --dport ${2} -j DNAT --to-destination ${3}:${4}
else
  iptables -t nat -D PREROUTING -p tcp -i ${1} --match multiport --dports ${2} -j DNAT --to-destination ${3}:${4}
fi
#iptables-save
#netfilter-persistent save


text:
Changes
=======

dev (master)
++++++++++++

* Fixed ``pip install urllib3[secure]`` on modern pip. (Issue #706)

* pyopenssl: Fixed SSL3_WRITE_PENDING error. (Issue #717)

* pyopenssl: Support for TLSv1.1 and TLSv1.2. (Issue #696)

* Close connections more defensively on exception. (Issue #734)

* Adjusted ``read_chunked`` to handle gzipped, chunk-encoded bodies without
  repeatedly flushing the decoder, to function better on Jython. (Issue #743)

* Accept ``ca_cert_dir`` for SSL-related PoolManager configuration. (Issue #758)

* ... [Short description of non-trivial change.] (Issue #)

1.12 (2015-09-03)
+++++++++++++++++

* Rely on ``six`` for importing ``httplib`` to work around
  conflicts with other Python 3 shims. (Issue #688)

* Add support for directories of certificate authorities, as supported by
  OpenSSL. (Issue #701)

* New exception: ``NewConnectionError``, raised when we fail to establish
  a new connection, usually ``ECONNREFUSED`` socket error.

1.11 (2015-07-21)
+++++++++++++++++

* When ``ca_certs`` is given, ``cert_reqs`` defaults to
  ``'CERT_REQUIRED'``. (Issue #650)

* ``pip install urllib3[secure]`` will install Certifi and
  PyOpenSSL as dependencies. (Issue #678)

* Made ``HTTPHeaderDict`` usable as a ``headers`` input value
  (Issues #632, #679)

* Added `urllib3.contrib.appengine <https://urllib3.readthedocs.org/en/latest/contrib.html#google-app-engine>`_
  which has an ``AppEngineManager`` for using ``URLFetch`` in a
  Google AppEngine environment. (Issue #664)

* Dev: Added test suite for AppEngine. (Issue #631)

* Fix performance regression when using PyOpenSSL. (Issue #626)

* Passing incorrect scheme (e.g. ``foo://``) will raise
  ``ValueError`` instead of ``AssertionError`` (backwards
  compatible for now, but please migrate). (Issue #640)

* Fix pools not getting replenished when an error occurs during a
  request using ``release_conn=False``. (Issue #644)

* Fix pool-default headers not applying for url-encoded requests
  like GET. (Issue #657)

* log.warning in Python 3 when headers are skipped due to parsing
  errors. (Issue #642)

* Close and discard connections if an error occurs during read.
  (Issue #660)

* Fix host parsing for IPv6 proxies. (Issue #668)

* Separate warning type SubjectAltNameWarning, now issued once
  per host. (Issue #671)

* Fix ``httplib.IncompleteRead`` not getting converted to
  ``ProtocolError`` when using ``HTTPResponse.stream()``
  (Issue #674)

1.10.4 (2015-05-03)
+++++++++++++++++++

* Migrate tests to Tornado 4. (Issue #594)

* Append default warning configuration rather than overwrite.
  (Issue #603)

* Fix streaming decoding regression. (Issue #595)

* Fix chunked requests losing state across keep-alive connections.
  (Issue #599)

* Fix hanging when chunked HEAD response has no body. (Issue #605)

1.10.3 (2015-04-21)
+++++++++++++++++++

* Emit ``InsecurePlatformWarning`` when SSLContext object is missing.
  (Issue #558)

* Fix regression of duplicate header keys being discarded.
  (Issue #563)

* ``Response.stream()`` returns a generator for chunked responses.
  (Issue #560)

* Set upper-bound timeout when waiting for a socket in PyOpenSSL.
  (Issue #585)

* Work on platforms without `ssl` module for plain HTTP requests.
  (Issue #587)

* Stop relying on the stdlib's default cipher list. (Issue #588)

1.10.2 (2015-02-25)
+++++++++++++++++++

* Fix file descriptor leakage on retries. (Issue #548)

* Removed RC4 from default cipher list. (Issue #551)

* Header performance improvements. (Issue #544)

* Fix PoolManager not obeying redirect retry settings. (Issue #553)

1.10.1 (2015-02-10)
+++++++++++++++++++

* Pools can be used as context managers. (Issue #545)

* Don't re-use connections which experienced an SSLError. (Issue #529)

* Don't fail when gzip decoding an empty stream. (Issue #535)

* Add sha256 support for fingerprint verification. (Issue #540)

* Fixed handling of header values containing commas. (Issue #533)

1.10 (2014-12-14)
+++++++++++++++++

* Disabled SSLv3. (Issue #473)

* Add ``Url.url`` property to return the composed url string. (Issue #394)

* Fixed PyOpenSSL + gevent ``WantWriteError``. (Issue #412)

* ``MaxRetryError.reason`` will always be an exception, not string.
  (Issue #481)

* Fixed SSL-related timeouts not being detected as timeouts. (Issue #492)

* Py3: Use ``ssl.create_default_context()`` when available. (Issue #473)

* Emit ``InsecureRequestWarning`` for *every* insecure HTTPS request.
  (Issue #496)

* Emit ``SecurityWarning`` when certificate has no ``subjectAltName``.
  (Issue #499)

* Close and discard sockets which experienced SSL-related errors.
  (Issue #501)

* Handle ``body`` param in ``.request(...)``. (Issue #513)

* Respect timeout with HTTPS proxy. (Issue #505)

* PyOpenSSL: Handle ZeroReturnError exception. (Issue #520)

1.9.1 (2014-09-13)
++++++++++++++++++

* Apply socket arguments before binding. (Issue #427)

* More careful checks if fp-like object is closed. (Issue #435)

* Fixed packaging issues of some development-related files not
  getting included. (Issue #440)

* Allow performing *only* fingerprint verification. (Issue #444)

* Emit ``SecurityWarning`` if system clock is waaay off. (Issue #445)

* Fixed PyOpenSSL compatibility with PyPy. (Issue #450)

* Fixed ``BrokenPipeError`` and ``ConnectionError`` handling in Py3.
  (Issue #443)

1.9 (2014-07-04)
++++++++++++++++

* Shuffled around development-related files. If you're maintaining a distro
  package of urllib3, you may need to tweak things. (Issue #415)

* Unverified HTTPS requests will trigger a warning on the first request. See
  our new `security documentation
  <https://urllib3.readthedocs.org/en/latest/security.html>`_ for details.
  (Issue #426)

* New retry logic and ``urllib3.util.retry.Retry`` configuration object.
  (Issue #326)

* All raised exceptions should now wrapped in a
  ``urllib3.exceptions.HTTPException``-extending exception. (Issue #326)

* All errors during a retry-enabled request should be wrapped in
  ``urllib3.exceptions.MaxRetryError``, including timeout-related exceptions
  which were previously exempt. Underlying error is accessible from the
  ``.reason`` propery. (Issue #326)

* ``urllib3.exceptions.ConnectionError`` renamed to
  ``urllib3.exceptions.ProtocolError``. (Issue #326)

* Errors during response read (such as IncompleteRead) are now wrapped in
  ``urllib3.exceptions.ProtocolError``. (Issue #418)

* Requesting an empty host will raise ``urllib3.exceptions.LocationValueError``.
  (Issue #417)

* Catch read timeouts over SSL connections as
  ``urllib3.exceptions.ReadTimeoutError``. (Issue #419)

* Apply socket arguments before connecting. (Issue #427)

1.8.3 (2014-06-23)
++++++++++++++++++

* Fix TLS verification when using a proxy in Python 3.4.1. (Issue #385)

* Add ``disable_cache`` option to ``urllib3.util.make_headers``. (Issue #393)

* Wrap ``socket.timeout`` exception with
  ``urllib3.exceptions.ReadTimeoutError``. (Issue #399)

* Fixed proxy-related bug where connections were being reused incorrectly.
  (Issues #366, #369)

* Added ``socket_options`` keyword parameter which allows to define
  ``setsockopt`` configuration of new sockets. (Issue #397)

* Removed ``HTTPConnection.tcp_nodelay`` in favor of
  ``HTTPConnection.default_socket_options``. (Issue #397)

* Fixed ``TypeError`` bug in Python 2.6.4. (Issue #411)

1.8.2 (2014-04-17)
++++++++++++++++++

* Fix ``urllib3.util`` not being included in the package.

1.8.1 (2014-04-17)
++++++++++++++++++

* Fix AppEngine bug of HTTPS requests going out as HTTP. (Issue #356)

* Don't install ``dummyserver`` into ``site-packages`` as it's only needed
  for the test suite. (Issue #362)

* Added support for specifying ``source_address``. (Issue #352)

1.8 (2014-03-04)
++++++++++++++++

* Improved url parsing in ``urllib3.util.parse_url`` (properly parse '@' in
  username, and blank ports like 'hostname:').

* New ``urllib3.connection`` module which contains all the HTTPConnection
  objects.

* Several ``urllib3.util.Timeout``-related fixes. Also changed constructor
  signature to a more sensible order. [Backwards incompatible]
  (Issues #252, #262, #263)

* Use ``backports.ssl_match_hostname`` if it's installed. (Issue #274)

* Added ``.tell()`` method to ``urllib3.response.HTTPResponse`` which
  returns the number of bytes read so far. (Issue #277)

* Support for platforms without threading. (Issue #289)

* Expand default-port comparison in ``HTTPConnectionPool.is_same_host``
  to allow a pool with no specified port to be considered equal to to an
  HTTP/HTTPS url with port 80/443 explicitly provided. (Issue #305)

* Improved default SSL/TLS settings to avoid vulnerabilities.
  (Issue #309)

* Fixed ``urllib3.poolmanager.ProxyManager`` not retrying on connect errors.
  (Issue #310)

* Disable Nagle's Algorithm on the socket for non-proxies. A subset of requests
  will send the entire HTTP request ~200 milliseconds faster; however, some of
  the resulting TCP packets will be smaller. (Issue #254)

* Increased maximum number of SubjectAltNames in ``urllib3.contrib.pyopenssl``
  from the default 64 to 1024 in a single certificate. (Issue #318)

* Headers are now passed and stored as a custom
  ``urllib3.collections_.HTTPHeaderDict`` object rather than a plain ``dict``.
  (Issue #329, #333)

* Headers no longer lose their case on Python 3. (Issue #236)

* ``urllib3.contrib.pyopenssl`` now uses the operating system's default CA
  certificates on inject. (Issue #332)

* Requests with ``retries=False`` will immediately raise any exceptions without
  wrapping them in ``MaxRetryError``. (Issue #348)

* Fixed open socket leak with SSL-related failures. (Issue #344, #348)

1.7.1 (2013-09-25)
++++++++++++++++++

* Added granular timeout support with new ``urllib3.util.Timeout`` class.
  (Issue #231)

* Fixed Python 3.4 support. (Issue #238)

1.7 (2013-08-14)
++++++++++++++++

* More exceptions are now pickle-able, with tests. (Issue #174)

* Fixed redirecting with relative URLs in Location header. (Issue #178)

* Support for relative urls in ``Location: ...`` header. (Issue #179)

* ``urllib3.response.HTTPResponse`` now inherits from ``io.IOBase`` for bonus
  file-like functionality. (Issue #187)

* Passing ``assert_hostname=False`` when creating a HTTPSConnectionPool will
  skip hostname verification for SSL connections. (Issue #194)

* New method ``urllib3.response.HTTPResponse.stream(...)`` which acts as a
  generator wrapped around ``.read(...)``. (Issue #198)

* IPv6 url parsing enforces brackets around the hostname. (Issue #199)

* Fixed thread race condition in
  ``urllib3.poolmanager.PoolManager.connection_from_host(...)`` (Issue #204)

* ``ProxyManager`` requests now include non-default port in ``Host: ...``
  header. (Issue #217)

* Added HTTPS proxy support in ``ProxyManager``. (Issue #170 #139)

* New ``RequestField`` object can be passed to the ``fields=...`` param which
  can specify headers. (Issue #220)

* Raise ``urllib3.exceptions.ProxyError`` when connecting to proxy fails.
  (Issue #221)

* Use international headers when posting file names. (Issue #119)

* Improved IPv6 support. (Issue #203)

1.6 (2013-04-25)
++++++++++++++++

* Contrib: Optional SNI support for Py2 using PyOpenSSL. (Issue #156)

* ``ProxyManager`` automatically adds ``Host: ...`` header if not given.

* Improved SSL-related code. ``cert_req`` now optionally takes a string like
  "REQUIRED" or "NONE". Same with ``ssl_version`` takes strings like "SSLv23"
  The string values reflect the suffix of the respective constant variable.
  (Issue #130)

* Vendored ``socksipy`` now based on Anorov's fork which handles unexpectedly
  closed proxy connections and larger read buffers. (Issue #135)

* Ensure the connection is closed if no data is received, fixes connection leak
  on some platforms. (Issue #133)

* Added SNI support for SSL/TLS connections on Py32+. (Issue #89)

* Tests fixed to be compatible with Py26 again. (Issue #125)

* Added ability to choose SSL version by passing an ``ssl.PROTOCOL_*`` constant
  to the ``ssl_version`` parameter of ``HTTPSConnectionPool``. (Issue #109)

* Allow an explicit content type to be specified when encoding file fields.
  (Issue #126)

* Exceptions are now pickleable, with tests. (Issue #101)

* Fixed default headers not getting passed in some cases. (Issue #99)

* Treat "content-encoding" header value as case-insensitive, per RFC 2616
  Section 3.5. (Issue #110)

* "Connection Refused" SocketErrors will get retried rather than raised.
  (Issue #92)

* Updated vendored ``six``, no longer overrides the global ``six`` module
  namespace. (Issue #113)

* ``urllib3.exceptions.MaxRetryError`` contains a ``reason`` property holding
  the exception that prompted the final retry. If ``reason is None`` then it
  was due to a redirect. (Issue #92, #114)

* Fixed ``PoolManager.urlopen()`` from not redirecting more than once.
  (Issue #149)

* Don't assume ``Content-Type: text/plain`` for multi-part encoding parameters
  that are not files. (Issue #111)

* Pass `strict` param down to ``httplib.HTTPConnection``. (Issue #122)

* Added mechanism to verify SSL certificates by fingerprint (md5, sha1) or
  against an arbitrary hostname (when connecting by IP or for misconfigured
  servers). (Issue #140)

* Streaming decompression support. (Issue #159)

1.5 (2012-08-02)
++++++++++++++++

* Added ``urllib3.add_stderr_logger()`` for quickly enabling STDERR debug
  logging in urllib3.

* Native full URL parsing (including auth, path, query, fragment) available in
  ``urllib3.util.parse_url(url)``.

* Built-in redirect will switch method to 'GET' if status code is 303.
  (Issue #11)

* ``urllib3.PoolManager`` strips the scheme and host before sending the request
  uri. (Issue #8)

* New ``urllib3.exceptions.DecodeError`` exception for when automatic decoding,
  based on the Content-Type header, fails.

* Fixed bug with pool depletion and leaking connections (Issue #76). Added
  explicit connection closing on pool eviction. Added
  ``urllib3.PoolManager.clear()``.

* 99% -> 100% unit test coverage.

1.4 (2012-06-16)
++++++++++++++++

* Minor AppEngine-related fixes.

* Switched from ``mimetools.choose_boundary`` to ``uuid.uuid4()``.

* Improved url parsing. (Issue #73)

* IPv6 url support. (Issue #72)

1.3 (2012-03-25)
++++++++++++++++

* Removed pre-1.0 deprecated API.

* Refactored helpers into a ``urllib3.util`` submodule.

* Fixed multipart encoding to support list-of-tuples for keys with multiple
  values. (Issue #48)

* Fixed multiple Set-Cookie headers in response not getting merged properly in
  Python 3. (Issue #53)

* AppEngine support with Py27. (Issue #61)

* Minor ``encode_multipart_formdata`` fixes related to Python 3 strings vs
  bytes.

1.2.2 (2012-02-06)
++++++++++++++++++

* Fixed packaging bug of not shipping ``test-requirements.txt``. (Issue #47)

1.2.1 (2012-02-05)
++++++++++++++++++

* Fixed another bug related to when ``ssl`` module is not available. (Issue #41)

* Location parsing errors now raise ``urllib3.exceptions.LocationParseError``
  which inherits from ``ValueError``.

1.2 (2012-01-29)
++++++++++++++++

* Added Python 3 support (tested on 3.2.2)

* Dropped Python 2.5 support (tested on 2.6.7, 2.7.2)

* Use ``select.poll`` instead of ``select.select`` for platforms that support
  it.

* Use ``Queue.LifoQueue`` instead of ``Queue.Queue`` for more aggressive
  connection reusing. Configurable by overriding ``ConnectionPool.QueueCls``.

* Fixed ``ImportError`` during install when ``ssl`` module is not available.
  (Issue #41)

* Fixed ``PoolManager`` redirects between schemes (such as HTTP -> HTTPS) not
  completing properly. (Issue #28, uncovered by Issue #10 in v1.1)

* Ported ``dummyserver`` to use ``tornado`` instead of ``webob`` +
  ``eventlet``. Removed extraneous unsupported dummyserver testing backends.
  Added socket-level tests.

* More tests. Achievement Unlocked: 99% Coverage.

1.1 (2012-01-07)
++++++++++++++++

* Refactored ``dummyserver`` to its own root namespace module (used for
  testing).

* Added hostname verification for ``VerifiedHTTPSConnection`` by vendoring in
  Py32's ``ssl_match_hostname``. (Issue #25)

* Fixed cross-host HTTP redirects when using ``PoolManager``. (Issue #10)

* Fixed ``decode_content`` being ignored when set through ``urlopen``. (Issue
  #27)

* Fixed timeout-related bugs. (Issues #17, #23)

1.0.2 (2011-11-04)
++++++++++++++++++

* Fixed typo in ``VerifiedHTTPSConnection`` which would only present as a bug if
  you're using the object manually. (Thanks pyos)

* Made RecentlyUsedContainer (and consequently PoolManager) more thread-safe by
  wrapping the access log in a mutex. (Thanks @christer)

* Made RecentlyUsedContainer more dict-like (corrected ``__delitem__`` and
  ``__getitem__`` behaviour), with tests. Shouldn't affect core urllib3 code.

1.0.1 (2011-10-10)
++++++++++++++++++

* Fixed a bug where the same connection would get returned into the pool twice,
  causing extraneous "HttpConnectionPool is full" log warnings.

1.0 (2011-10-08)
++++++++++++++++

* Added ``PoolManager`` with LRU expiration of connections (tested and
  documented).
* Added ``ProxyManager`` (needs tests, docs, and confirmation that it works
  with HTTPS proxies).
* Added optional partial-read support for responses when
  ``preload_content=False``. You can now make requests and just read the headers
  without loading the content.
* Made response decoding optional (default on, same as before).
* Added optional explicit boundary string for ``encode_multipart_formdata``.
* Convenience request methods are now inherited from ``RequestMethods``. Old
  helpers like ``get_url`` and ``post_url`` should be abandoned in favour of
  the new ``request(method, url, ...)``.
* Refactored code to be even more decoupled, reusable, and extendable.
* License header added to ``.py`` files.
* Embiggened the documentation: Lots of Sphinx-friendly docstrings in the code
  and docs in ``docs/`` and on urllib3.readthedocs.org.
* Embettered all the things!
* Started writing this file.

0.4.1 (2011-07-17)
++++++++++++++++++

* Minor bug fixes, code cleanup.

0.4 (2011-03-01)
++++++++++++++++

* Better unicode support.
* Added ``VerifiedHTTPSConnection``.
* Added ``NTLMConnectionPool`` in contrib.
* Minor improvements.

0.3.1 (2010-07-13)
++++++++++++++++++

* Added ``assert_host_name`` optional parameter. Now compatible with proxies.

0.3 (2009-12-10)
++++++++++++++++

* Added HTTPS support.
* Minor bug fixes.
* Refactored, broken backwards compatibility with 0.2.
* API to be treated as stable from this version forward.

0.2 (2008-11-17)
++++++++++++++++

* Added unit tests.
* Bug fixes.

0.1 (2008-11-16)
++++++++++++++++

* First release.


text:
package vacuum_server

import (
	"time"

	"flag"

	"os"

	"sync"

	"github.com/xiaonanln/goTimer"
	"github.com/xiaonanln/vacuum"
	"github.com/xiaonanln/vacuum/common"
	"github.com/xiaonanln/vacuum/config"
	"github.com/xiaonanln/vacuum/vacuum_server/dispatcher_client"
	"github.com/xiaonanln/vacuum/vlog"
)

const (
	DISPATCHER_ADDR   = ":"
	DEFAULT_LOG_LEVEL = "info"
)

var (
	serverID   = 1 // default server ID to be 1
	logLevel   = DEFAULT_LOG_LEVEL
	configFile = ""
	serverOps  _ServerOps
)

func init() {
	// initializing the vacuum server
	flag.IntVar(&serverID, "sid", 1, "server ID")
	flag.StringVar(&logLevel, "log", DEFAULT_LOG_LEVEL, "log level")
	flag.StringVar(&configFile, "c", config.DEFAULT_CONFIG_FILENAME, "config file")
	flag.Parse()

	setupLog(logLevel)

	if serverID <= 0 {
		vlog.Panicf("Server ID must be positive, not %d", serverID)
	}

	vlog.Debug(">>> Server ID: %d, Config file: %s", serverID, configFile)

	config.LoadConfig(configFile)
	vacuumConfig := config.GetConfig().GetVacuumConfig(serverID)
	vlog.Debug("VACUUM %d LOAD CONFIG:", serverID)
	os.Stderr.WriteString(config.FormatConfig(vacuumConfig))

	timer.StartTicks(10 * time.Millisecond)

	storage := openStorage(vacuumConfig.Storage)
	vacuum.Setup(serverID, storage, &serverOps)
}

type DispatcherRespHandler struct{}

func (rh DispatcherRespHandler) HandleDispatcherResp_RegisterVacuumServer(serverIDs []int) {
	vlog.Info("RegisterVacuumServer: %v", serverIDs)
	serverOps.setVacuumServerIDs(serverIDs)
}

func (rh DispatcherRespHandler) HandleDispatcherResp_CreateString(name string, stringID string, args []interface{}) {
	vacuum.OnCreateString(name, stringID, args)
}

func (rh DispatcherRespHandler) HandleDispatcherResp_DeclareService(stringID string, serviceName string) {
	vacuum.OnDeclareService(stringID, serviceName)
}

func (rh DispatcherRespHandler) HandleDispatcherResp_SendStringMessage(stringID string, msg common.StringMessage, tag uint) {
	vacuum.OnSendStringMessage(stringID, msg, tag)
}

func (rh DispatcherRespHandler) HandleDispatcherResp_CloseString(stringID string) {
	vacuum.OnCloseString(stringID)
}

func (rh DispatcherRespHandler) HandleDispatcherResp_DelString(stringID string) {
	vacuum.OnDelString(stringID)
}

func (rh DispatcherRespHandler) HandleDispatcherResp_LoadString(name string, stringID string, args []interface{}) {
	vacuum.OnLoadString(name, stringID, args)
}

func (rh DispatcherRespHandler) HandleDispatcherResp_MigrateString(stringID string) {
	vacuum.MigrateString(stringID)
}

func (rh DispatcherRespHandler) HandleDispatcherResp_OnMigrateString(name string, stringID string, initArgs []interface{}, data map[string]interface{}, extraMigrateInfo map[string]interface{}) {
	vacuum.OnMigrateString(name, stringID, initArgs, data, extraMigrateInfo)
}

type _ServerOps struct {
	lock      sync.RWMutex
	serverIDs []int
}

func (so *_ServerOps) GetServerList() (ret []int) {
	so.lock.RLock()
	//vlog.Debug("GetServerList: %v", so.serverIDs)
	ret = so.serverIDs
	so.lock.RUnlock()
	return
}

func (so *_ServerOps) setVacuumServerIDs(serverIDs []int) {
	so.lock.Lock()
	so.serverIDs = serverIDs
	so.lock.Unlock()
}

func RunServer() {
	dispatcher_client.Initialize(serverID, DispatcherRespHandler{})

	vacuum.CreateStringLocally("Main")

	for {
		time.Sleep(time.Second)
	}
}

func ServerID() int {
	return serverID
}


text:
package cz.vutbr.web.domassign;

import com.intellij.psi.PsiElement;
import com.intellij.psi.html.HtmlTag;
import cz.vutbr.web.css.Declaration;
import cz.vutbr.web.css.Selector.PseudoDeclaration;

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

/**
 * This is a map that assigns a sorted list of declarations to each element
 * and an optional pseudo-element.
 *
 * @author burgetr
 */
public class DeclarationMap extends MultiMap<PsiElement, PseudoDeclaration, List<Declaration>> {

    /**
     * Adds a declaration for a specified list. If the list does not exist yet, it is created.
     *
     * @param tag    the element that the declaration belongs to
     * @param pseudo an optional pseudo-element or null
     * @param decl   the new declaration
     */
    public void addDeclaration(HtmlTag tag, PseudoDeclaration pseudo, Declaration decl) {
        List<Declaration> list = getOrCreate(tag, pseudo);
        list.add(decl);
    }

    /**
     * Sorts the given list according to the rule specificity.
     *
     * @param tag    the element to which the list is assigned
     * @param pseudo an optional pseudo-element or null
     */
    public void sortDeclarations(HtmlTag tag, PseudoDeclaration pseudo) {
        List<Declaration> list = get(tag, pseudo);
        if (list != null)
            Collections.sort(list);
    }

    @Override
    protected List<Declaration> createDataInstance() {
        return new ArrayList<Declaration>();
    }

}


text:
@interface WBComposeToolbar()
@property (nonatomic, weak) UIButton *emotionButton;
@end

@implementation WBComposeToolbar

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"compose_toolbar_background"]];

        [self setupBtn:@"compose_camerabutton_background" highImage:@"compose_camerabutton_background_highlighted" type:WBComposeToolbarButtonTypeCamera];

        [self setupBtn:@"compose_toolbar_picture" highImage:@"compose_toolbar_picture_highlighted" type:WBComposeToolbarButtonTypePicture];

        [self setupBtn:@"compose_mentionbutton_background" highImage:@"compose_mentionbutton_background_highlighted" type:WBComposeToolbarButtonTypeMention];

        [self setupBtn:@"compose_trendbutton_background" highImage:@"compose_trendbutton_background_highlighted" type:WBComposeToolbarButtonTypeTrend];

        self.emotionButton = [self setupBtn:@"compose_emoticonbutton_background" highImage:@"compose_emoticonbutton_background_highlighted" type:WBComposeToolbarButtonTypeEmotion];
    }
    return self;
}

- (UIButton *)setupBtn:(NSString *)image highImage:(NSString *)highImage type:(WBComposeToolbarButtonType)type
{
    UIButton *btn = [[UIButton alloc] init];
    [btn setImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:highImage] forState:UIControlStateHighlighted];
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    btn.tag = type;
    [self addSubview:btn];
    return btn;
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    NSUInteger count = self.subviews.count;
    CGFloat btnW = self.width / count;
    CGFloat btnH = self.height;
    for (NSUInteger i = 0; i < count; i++) {
        UIButton *btn = self.subviews[i];
        btn.y = 0;
        btn.width = btnW;
        btn.height = btnH;
        btn.x = i * btnW;
    }
}

- (void)setShowKeyboardButton:(BOOL)showKeyboardButton
{
    _showKeyboardButton = showKeyboardButton;

    NSString *image = @"compose_emoticonbutton_background";
    NSString *highImage = @"compose_emoticonbutton_background_highlighted";

    if (showKeyboardButton) {
        image = @"compose_keyboardbutton_background";
        highImage = @"compose_keyboardbutton_background_highlighted";
    }

    [self.emotionButton setImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
    [self.emotionButton setImage:[UIImage imageNamed:highImage] forState:UIControlStateHighlighted];
}

- (void)btnClick:(UIButton *)btn;
{
    if ([self.delegate respondsToSelector:@selector(composeToolbar:didClickButton:)]) {
        [self.delegate composeToolbar:self didClickButton:(WBComposeToolbarButtonType)btn.tag];
    }
}

@end


text:
package genome.util;

import java.io.PrintWriter;
import java.io.StringWriter;

public class Utils {
	public static String error2StackTrace(Throwable e){
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		e.printStackTrace(pw);
		pw.flush();
		pw.close();
		return sw.toString();
	}
}


text:
[![Gem Version](https://badge.fury.io/rb/sorcery.svg)](https://rubygems.org/gems/sorcery)
[![Gem Downloads](https://img.shields.io/gem/dt/sorcery.svg)](https://rubygems.org/gems/sorcery)
[![Build Status](https://github.com/Sorcery/sorcery/actions/workflows/ruby.yml/badge.svg?branch=master)](https://github.com/Sorcery/sorcery/actions/workflows/ruby.yml)

Magical Authentication for Rails. Supports ActiveRecord, DataMapper, Mongoid and MongoMapper.

Inspired by Restful Authentication, Authlogic and Devise. Crypto code taken almost unchanged from Authlogic. OAuth code inspired by OmniAuth and Ryan Bates's Railscast about it.

### Philosophy

Sorcery is a stripped-down, bare-bones authentication library, with which you can write your own authentication flow. It was built with a few goals in mind:

- Less is more - less than 20 public methods to remember for the entire feature-set make the lib easy to 'get'.
- No built-in or generated code - use the library's methods inside *your own* MVC structures, and don't fight to fix someone else's.
- Magic yes, Voodoo no - the lib should be easy to hack for most developers.
- Configuration over Confusion - Centralized (1 file), Simple & short configuration as possible, not drowning in syntactic sugar.
- Keep MVC cleanly separated - DB is for models, sessions are for controllers. Models stay unaware of sessions.

## Table of Contents

1. [Useful Links](#useful-links)
2. [API Summary](#api-summary)
3. [Installation](#installation)
4. [Configuration](#configuration)
5. [Full Features List by Module](#full-features-list-by-module)
6. [Planned Features](#planned-features)
7. [Contributing](#contributing)
8. [Contact](#contact)
9. [License](#license)

## Useful Links

- [Documentation](http://rubydoc.info/gems/sorcery)
- [Railscast](http://railscasts.com/episodes/283-authentication-with-sorcery)
- [Simple tutorial](https://github.com/Sorcery/sorcery/wiki/Simple-Password-Authentication)
- [Example Rails app](https://github.com/Sorcery/sorcery-example-app)

Check out the tutorials in the [wiki](https://github.com/Sorcery/sorcery/wiki) for more:

- [DataMapper Support](https://github.com/Sorcery/sorcery/wiki/DataMapper-Support)
- [DelayedJob Integration](https://github.com/Sorcery/sorcery/wiki/DelayedJob-Integration)
- [Simple Password Authentication](https://github.com/Sorcery/sorcery/wiki/Simple-Password-Authentication)
- [Single Table Inheritance Support](https://github.com/Sorcery/sorcery/wiki/Single-Table-Inheritance-Support)
- [Upgrading](https://github.com/Sorcery/sorcery/wiki/Upgrading)

## API Summary

Below is a summary of the library methods. Most method names are self
explaining and the rest are commented:

### Core

```ruby
require_login # This is a before action
login(email, password, remember_me = false)
auto_login(user) # Login without credentials
logout
logged_in? # Available in views
current_user # Available in views
redirect_back_or_to # Use when a user tries to access a page while logged out, is asked to login, and we want to return him back to the page he originally wanted
@user.external? # Users who signed up using Facebook, Twitter, etc.
@user.active_for_authentication? # Add this method to define behaviour that will prevent selected users from signing in
@user.valid_password?('secret') # Compares 'secret' with the actual user's password, returns true if they match
User.authenticates_with_sorcery!
```

### HTTP Basic Auth

```ruby
require_login_from_http_basic # This is a before action
```

### External

```ruby
login_at(provider) # Sends the user to an external service (Facebook, Twitter, etc.) to authenticate
login_from(provider) # Tries to login from the external provider's callback
create_from(provider) # Create the user in the local app database
build_from(provider) # Build user instance using user_info_mappings
```

### Remember Me

```ruby
auto_login(user, should_remember = false) # Login without credentials, optional remember_me
remember_me!
forget_me!
force_forget_me! # Forgets all sessions by clearing the token, even if remember_me_token_persist_globally is set to true
```

### Reset Password

```ruby
User.load_from_reset_password_token(token)
@user.generate_reset_password_token! # Use if you want to send the email by yourself
@user.deliver_reset_password_instructions! # Generates the token and sends the email
@user.change_password(new_password)
@user.change_password!(new_password) # Same as change_password but raises exception on save
```

### Session Timeout

```ruby
invalidate_active_sessions! #Invalidate all sessions with a login_time or last_action_time before the current time. Must Opt-in
```

### User Activation

```ruby
User.load_from_activation_token(token)
@user.setup_activation
@user.activate!
```

Please see the tutorials in the github wiki for detailed usage information.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'sorcery'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install sorcery

## Configuration

Run the following command to generate the core migration file, the initializer file and the
`User` model class.

    $ rails generate sorcery:install

Run the following command generate the migrations files for remember_me and reset_password submodules and will create the initializer file (and add submodules to it), and create the `User` model class.

    $ rails generate sorcery:install remember_me reset_password

Run the following command to generate the core migration file, the initializer and change the model class (in the initializer and migration files) to the class `Person` (and its pluralized version, 'people')

    $ rails generate sorcery:install --model Person

Run the following command to generate only the migration files for the specified submodules and will add them to the initializer file.

    $ rails generate sorcery:install http_basic_auth external remember_me --only-submodules

Inside the initializer, the comments will tell you what each setting does.

## Full Features List by Module

**Core** (see [lib/sorcery/model.rb](https://github.com/Sorcery/sorcery/blob/master/lib/sorcery/model.rb) and [lib/sorcery/controller.rb](https://github.com/Sorcery/sorcery/blob/master/lib/sorcery/controller.rb)):

- Login / logout, optional return user to requested url on login, configurable redirect for non-logged-in users.
- Password encryption, algorithms: bcrypt (default), MD5, SHA-1, SHA-256, SHA-512, AES or custom. Configurable stretches and salt.
- Configurable attribute names for username, password and email.
- Allow multiple fields to serve as username.

**User Activation** (see [lib/sorcery/model/submodules/user_activation.rb](https://github.com/Sorcery/sorcery/blob/master/lib/sorcery/model/submodules/user_activation.rb)):

- User activation by email with optional success email
- Configurable attribute names
- Configurable mailer, method name, and attribute name
- Configurable temporary token expiration
- Optionally prevent non-active users to login

**Reset Password** (see [lib/sorcery/model/submodules/reset_password.rb](https://github.com/Sorcery/sorcery/blob/master/lib/sorcery/model/submodules/reset_password.rb)):

- Reset password with email verification
- Configurable mailer, method name, and attribute name
- Configurable temporary token expiration
- Configurable time between emails (hammering protection)

**Remember Me** (see [lib/sorcery/model/submodules/remember_me.rb](https://github.com/Sorcery/sorcery/blob/master/lib/sorcery/model/submodules/remember_me.rb)):

- Remember me with configurable expiration
- Configurable attribute names
- Configurable to persist globally (supporting multiple browsers at the same time), or starting anew after each login

**Session Timeout** (see [lib/sorcery/controller/submodules/session_timeout.rb](https://github.com/Sorcery/sorcery/blob/master/lib/sorcery/controller/submodules/session_timeout.rb)):

- Configurable session timeout
- Optionally session timeout will be calculated from last user action
- Optionally enable a method to clear all active sessions, expects an `invalidate_sessions_before` datetime attribute.

**Brute Force Protection** (see [lib/sorcery/model/submodules/brute_force_protection.rb](https://github.com/Sorcery/sorcery/blob/master/lib/sorcery/model/submodules/brute_force_protection.rb)):

- Brute force login hammering protection
- configurable logins before lock and lock duration

**Basic HTTP Authentication** (see [lib/sorcery/controller/submodules/http_basic_auth.rb](https://github.com/Sorcery/sorcery/blob/master/lib/sorcery/controller/submodules/http_basic_auth.rb)):

- A before action for requesting authentication with HTTP Basic
- Automatic login from HTTP Basic
- Automatic login is disabled if session key changed

**Activity Logging** (see [lib/sorcery/model/submodules/activity_logging.rb](https://github.com/Sorcery/sorcery/blob/master/lib/sorcery/model/submodules/activity_logging.rb)):

- Automatic logging of last login, last logout, last activity time and IP address for last login
- Configurable timeout by which to decide whether to include a user in the list of logged in users

**External** (see [lib/sorcery/controller/submodules/external.rb](https://github.com/Sorcery/sorcery/blob/master/lib/sorcery/controller/submodules/external.rb)):

- OAuth1 and OAuth2 support (currently: Twitter, Facebook, Github, Google, Heroku, LinkedIn, VK, LiveID, Xing, Salesforce)
- Configurable database column names
- Authentications table

## Planned Features

- Passing a block to encrypt, allowing the developer to define his own mix of salting and encrypting
- Forgot username, maybe as part of the reset_password module
- Scoping logins (to a subdomain or another arbitrary field)
- Allowing storing the salt and encrypted password in the same DB field for extra security
- Other reset password strategies (security questions?)
- Other brute force protection strategies (captcha)

Have an idea? Let us know, and it might get into the gem!

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/Sorcery/sorcery.

- [Git Workflow](https://github.com/Sorcery/sorcery/wiki/Git-Workflow)
- [Running the specs](https://github.com/Sorcery/sorcery/wiki/Running-the-specs)

## Contact

Feel free to ask questions using these contact details:

**Current Maintainers:**

- Josh Buker ([@athix](https://github.com/athix)) | [Email](mailto:crypto+sorcery@joshbuker.com?subject=Sorcery)

**Past Maintainers:**

- Noam Ben-Ari ([@NoamB](https://github.com/NoamB)) | [Email](mailto:nbenari@gmail.com) | [Twitter](https://twitter.com/nbenari)
- Kir Shatrov ([@kirs](https://github.com/kirs)) | [Email](mailto:shatrov@me.com) | [Twitter](https://twitter.com/Kiiiir)
- Grzegorz Witek ([@arnvald](https://github.com/arnvald)) | [Email](mailto:arnvald.to@gmail.com) | [Twitter](https://twitter.com/arnvald)
- Chase Gilliam ([@Ch4s3](https://github.com/Ch4s3)) | [Email](mailto:chase.gilliam@gmail.com)

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
module Beta
  module Connections
    class SeriesWorkConnection < GraphQL::Types::Relay::BaseConnection
      edge_type Beta::Edges::SeriesWorkEdge
    end
  end
end


text:
"use strict";

describe("byte", function() {
  it("matches a buffer byte", function() {
    var b = Buffer.from([0xf]);
    var p = Parsimmon.Binary.byte(0xf);
    assert.ok(p.parse(b).value);
  });

  it("formats single digit bytes like 0x0f", function() {
    var b = Buffer.from([0xa]);
    var p = Parsimmon.Binary.byte(0xf);
    assert.deepEqual(p.parse(b).expected, ["0x0f"]);
  });

  it("formats double digit bytes like 0xff", function() {
    var b = Buffer.from([0x12]);
    var p = Parsimmon.Binary.byte(0xff);
    assert.deepEqual(p.parse(b).expected, ["0xff"]);
  });

  it("disallows larger values than a byte.", function() {
    assert.throws(function() {
      Parsimmon.Binary.byte(0xfff);
    }, /4095=0xfff/);
  });

  context("Buffer is not present.", function() {
    var buff;
    before(function() {
      buff = global.Buffer;
      global.Buffer = undefined;
    });

    after(function() {
      global.Buffer = buff;
    });

    it("Disallows construction.", function() {
      assert.throws(function() {
        Parsimmon.Binary.byte(0xf);
      }, /buffer global/i);
    });
  });
});