text:
"""Test Link functionality."""
#
# (C) Pywikibot team, 2014-2022
#
# Distributed under the terms of the MIT license.
#
import re
from contextlib import suppress

import pywikibot
from pywikibot import Site, config
from pywikibot.exceptions import InvalidTitleError, SiteDefinitionError
from pywikibot.page import Link, Page, SiteLink
from pywikibot.site import Namespace
from tests.aspects import (
    AlteredDefaultSiteTestCase,
    DefaultDrySiteTestCase,
    TestCase,
    WikimediaDefaultSiteTestCase,
    unittest,
)

class TestCreateSeparated(DefaultDrySiteTestCase):

    """Test ``Link.create_separated``."""

    def _test_link(self, link, page, section, label):
        """Test the separate contents of the link."""
        self.assertIs(link.site, self.site)
        self.assertEqual(link.title, page)
        if section is None:
            self.assertIsNone(link.section)
        else:
            self.assertEqual(link.section, section)
        if label is None:
            self.assertIsNone(link.anchor)
        else:
            self.assertEqual(link.anchor, label)

    def test(self):
        """Test combinations of parameters."""
        self._test_link(Link.create_separated('Foo', self.site),
                        'Foo', None, None)
        self._test_link(Link.create_separated('Foo', self.site, section='Bar'),
                        'Foo', 'Bar', None)
        self._test_link(Link.create_separated('Foo', self.site, label='Baz'),
                        'Foo', None, 'Baz')
        self._test_link(Link.create_separated('Foo', self.site, section='Bar',
                                              label='Baz'),
                        'Foo', 'Bar', 'Baz')

# ---- 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 replaced(self, iterable):
        """Replace family specific title delimiter."""
        for items in iterable:
            if isinstance(items, str):
                items = [items]
            items = [re.sub(' ',
                            self.site.family.title_delimiter_and_aliases[0],
                            item)
                     for item in items]
            if len(items) == 1:
                items = items[0]
            yield items

    def test_valid(self):
        """Test that valid titles are correctly normalized."""
        title_tests = ['Sandbox', 'A "B"', "A 'B'", '.com', '~', '"', "'",
                       'Foo/.../Sandbox', 'Sandbox/...', 'A~~', 'X' * 252]

        extended_title_tests = [
            ('Talk:Sandbox', 'Sandbox'),
            ('Talk:Foo:Sandbox', 'Foo:Sandbox'),
            ('File:Example.svg', 'Example.svg'),
            ('File_talk:Example.svg', 'Example.svg'),
            (':A', 'A'),
            # Length is 256 total, but only title part matters
            ('Category:' + 'X' * 248, 'X' * 248),
            ('A%20B', 'A B'),
            ('A é B', 'A é B'),
            ('A é B', 'A é B'),
            ('A é B', 'A é B'),
            ('A   B', 'A B'),
            ('A   B', 'A B'),
        ]

        site = self.get_site()

        for title in self.replaced(title_tests):
            with self.subTest(title=title):
                self.assertEqual(Link(title, site).title, title)

        for link, title in self.replaced(extended_title_tests):
            with self.subTest(link=link, title=title):
                self.assertEqual(Link(link, site).title, title)

        anchor_link = Link('A | B', site)
        self.assertEqual(anchor_link.title, 'A')
        self.assertEqual(anchor_link.anchor, ' B')

        section_link = Link('A%23B', site)
        self.assertEqual(section_link.title, 'A')
        self.assertEqual(section_link.section, 'B')

    def test_invalid(self):
        """Test that invalid titles raise InvalidTitleError."""
        # Bad characters forbidden regardless of wgLegalTitleChars
        def generate_contains_illegal_chars_exc_regex(text):
            exc_regex = (
                r'^(u|)\'{}\' contains illegal char\(s\) (u|)\'{}\'$'
                .format(re.escape(text), re.escape(text[2])))
            return exc_regex

        # Directory navigation
        def generate_contains_dot_combinations_exc_regex(text):
            exc_regex = (r'^\(contains \. / combinations\): (u|)\'{}\'$'
                         .format(re.escape(text)))
            return exc_regex

        # Tilde
        def generate_contains_tilde_exc_regex(text):
            exc_regex = r'^\(contains ~~~\): (u|)\'{}\'$' \
                        .format(re.escape(text))
            return exc_regex

        # Overlength
        def generate_overlength_exc_regex(text):
            exc_regex = r'^\(over 255 bytes\): (u|)\'{}\'$' \
                        .format(re.escape(text))
            return exc_regex

        # Namespace prefix without actual title
        def generate_has_no_title_exc_regex(text):
            exc_regex = r'^(u|)\'{}\' has no title\.$'.format(
                re.escape(text.strip()))
            return exc_regex

        title_tests = [
            # Empty title
            (['', ':'],
             r'^The link \[\[.*\]\] does not contain a page title$'),

            (['A [ B', 'A ] B', 'A { B', 'A } B', 'A < B', 'A > B'],
             generate_contains_illegal_chars_exc_regex),

            # URL encoding
            # %XX is understood by wikimedia but not %XXXX
            (['A%2523B'],
             r'^(u|)\'A%23B\' contains illegal char\(s\) (u|)\'%23\'$'),

            # A link is invalid if their (non-)talk page would be in another
            # namespace than the link's "other" namespace
            (['Talk:File:Example.svg'],
             r'The \(non-\)talk page of (u|)\'Talk:File:Example.svg\''
             r' is a valid title in another namespace.'),

            (['.', '..', './Sandbox', '../Sandbox', 'Foo/./Sandbox',
              'Foo/../Sandbox', 'Sandbox/.', 'Sandbox/..'],
             generate_contains_dot_combinations_exc_regex),

            (['A ~~~ Name', 'A ~~~~ Signature', 'A ~~~~~ Timestamp'],
             generate_contains_tilde_exc_regex),

            ([('x' * 256), ('Invalid:' + 'X' * 248)],
             generate_overlength_exc_regex),

            (['Talk:'],
             generate_has_no_title_exc_regex),
        ]

        # Known issues with wikihow.
        if self.site.family.name != 'wikihow':
            title_tests.extend([
                (['Category: ', 'Category: #bar'],
                 generate_has_no_title_exc_regex),
                (['__  __', '  __  '],
                 r'^The link \[\[\]\] does not contain a page title$'),
            ])

        for texts_to_test, exception_regex in title_tests:
            for text in self.replaced(texts_to_test):
                with self.subTest(title=text):
                    if callable(exception_regex):
                        regex = exception_regex(text)
                    else:
                        regex = exception_regex
                    with self.assertRaisesRegex(InvalidTitleError, regex):
                        Link(text, self.get_site()).parse()

    def test_relative(self):
        """Test that relative links are handled properly."""
        # Subpage
        page = Page(self.get_site(), 'Foo')
        rel_link = Link('/bar', page)
        self.assertEqual(rel_link.title, 'Foo/bar')
        self.assertEqual(rel_link.site, self.get_site())
        # Subpage of Page with section
        page = Page(self.get_site(), 'Foo#Baz')
        rel_link = Link('/bar', page)
        self.assertEqual(rel_link.title, 'Foo/bar')
        self.assertEqual(rel_link.site, self.get_site())
        # Non-subpage link text beginning with slash
        abs_link = Link('/bar', self.get_site())
        self.assertEqual(abs_link.title, '/bar')

class Issue10254TestCase(DefaultDrySiteTestCase):

    """Test T102461 (Python issue 10254)."""

    def test_no_change(self):
        """Test T102461 (Python issue 10254) is not encountered."""
        title = 'Li̍t-sṳ́'
        link = Link(title, self.site)
        self.assertEqual(link.title, 'Li̍t-sṳ́')

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

class LinkTestCase(AlteredDefaultSiteTestCase):

    """Cached API test for link tests."""

    cache = True

class LinkTestWikiEn(LinkTestCase):

    """Link tests on wikipedia:en."""

    family = 'wikipedia'
    code = 'en'

    def setUp(self):
        """Setup tests."""
        super().setUp()
        config.mylang = 'en'
        config.family = 'wikipedia'

class TestPartiallyQualifiedExplicitLinkSameSiteParser(LinkTestWikiEn):

    """Link tests."""

    def test_partially_qualified_NS0_code(self):
        """Test ':wikipedia:Main Page' on enwp is namespace 4."""
        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."""
        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."""
        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."""
        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(LinkTestWikiEn):

    """Link tests."""

    def test_partially_qualified_NS0_family(self):
        """Test ':en:Main Page' on dewp is namespace 0."""
        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."""
        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'

    def setUp(self):
        """Setup tests."""
        super().setUp()
        config.mylang = 'en'
        config.family = 'wikisource'

    def test_partially_qualified_NS0_code(self):
        """Test ':wikipedia:Main Page' on enws is namespace 0."""
        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."""
        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'

    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(LinkTestWikiEn):

    """Link tests."""

    def test_fully_qualified_NS0_code(self):
        """Test ':en:wikipedia:Main Page' on enwp is namespace 4."""
        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."""
        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 TestFullyQualifiedLinkDifferentFamilyParser(LinkTestCase):

    """Test link to a different family with and without preleading colon."""

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

    PATTERN = '{colon}{first}:{second}:{title}'

    def setUp(self):
        """Setup tests."""
        super().setUp()
        config.mylang = 'en'
        config.family = 'wikisource'

    def test_fully_qualified_NS0(self):
        """Test that fully qualified link is in namespace 0."""
        family, code = 'wikipedia:en'.split(':')
        for colon in ('', ':'):  # with or without preleading colon
            # switch code:family sequence en:wikipedia or wikipedia:en
            for first, second in [(family, code), (code, family)]:
                with self.subTest(colon=colon,
                                  site='{}:{}'.format(first, second)):
                    link_title = self.PATTERN.format(colon=colon,
                                                     first=first,
                                                     second=second,
                                                     title='Main Page')
                    link = Link(link_title)
                    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(self):
        """Test that fully qualified link is in namespace 1."""
        family, code = 'wikipedia:en'.split(':')
        for colon in ('', ':'):  # with or without preleading colon
            # switch code:family sequence en:wikipedia or wikipedia:en
            for first, second in [(family, code), (code, family)]:
                with self.subTest(colon=colon,
                                  site='{}:{}'.format(first, second)):
                    link_title = self.PATTERN.format(colon=colon,
                                                     first=first,
                                                     second=second,
                                                     title='Talk:Main Page')
                    link = Link(link_title)
                    link.parse()
                    self.assertEqual(link.site, self.get_site('enwp'))
                    self.assertEqual(link.title, 'Main Page')
                    self.assertEqual(link.namespace, 1)

class TestFullyQualifiedExplicitLinkNoLangConfigFamilyParser(LinkTestCase):

    """Test link from family without lang code to a different family."""

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

    def setUp(self):
        """Setup tests."""
        super().setUp()
        config.mylang = 'wikidata'
        config.family = 'wikidata'

    def test_fully_qualified_NS0_code(self):
        """Test ':en:wikipedia:Main Page' on wikidata is namespace 4."""
        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."""
        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."""
        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."""
        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):

    """Test wikibase links."""

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

    def setUp(self):
        """Setup tests."""
        super().setUp()
        config.mylang = 'en'
        config.family = 'wikipedia'

    def test_fully_qualified_NS0_code(self):
        """Test ':testwiki:wikidata:Q6' on enwp is namespace 0."""
        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."""
        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.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."""
        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):

    """Test links to one site target family."""

    family = 'species'
    code = 'species'

    def setUp(self):
        """Setup tests."""
        super().setUp()
        config.mylang = 'en'
        config.family = 'wikipedia'

    def test_fully_qualified_NS0_code(self):
        """Test ':species:species:Main Page' on species is namespace 0."""
        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."""
        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 shouldn't be interwikis, follow.

class TestPartiallyQualifiedImplicitLinkSameSiteParser(LinkTestWikiEn):

    """Test partially qualified links to same site."""

    def test_partially_qualified_NS0_code(self):
        """Test 'wikipedia:Main Page' on enwp is namespace 4."""
        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."""
        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."""
        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."""
        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(LinkTestWikiEn):

    """Test partially qualified links to different code."""

    def test_partially_qualified_NS0_family(self):
        """Test 'en:Main Page' on dewp is namespace 0."""
        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."""
        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):

    """Test partially qualified links to different family."""

    family = 'wikipedia'
    code = 'en'

    def setUp(self):
        """Setup tests."""
        super().setUp()
        config.mylang = 'en'
        config.family = 'wikisource'

    def test_partially_qualified_NS0_code(self):
        """Test 'wikipedia:Main Page' on enws is namespace 0."""
        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."""
        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(LinkTestWikiEn):

    """Link tests."""

    def test_fully_qualified_NS0_code(self):
        """Test 'en:wikipedia:Main Page' on enwp is namespace 4."""
        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."""
        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 TestFullyQualifiedImplicitLinkNoLangConfigFamilyParser(LinkTestCase):

    """Test implicit link from family without lang code to other family."""

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

    def setUp(self):
        """Setup tests."""
        super().setUp()
        config.mylang = 'wikidata'
        config.family = 'wikidata'

    def test_fully_qualified_NS0_code(self):
        """Test 'en:wikipedia:Main Page' on wikidata is namespace 4."""
        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 isn't namespace 1."""
        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."""
        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."""
        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):

    """Test wikibase links without preleading colon."""

    family = 'wikidata'
    code = 'test'

    def setUp(self):
        """Setup tests."""
        super().setUp()
        config.mylang = 'en'
        config.family = 'wikipedia'

    def test_fully_qualified_NS0(self):
        """Test prefixed links with 'Q6' on enwp is namespace 0."""
        test = [('testwiki:wikidata', 'wikidata:wikidata'),
                ('wikidata:testwiki', 'wikipedia:test')]
        for linkprefix, sitetitle in test:
            with self.subTest(pattern=linkprefix):
                link = Link(linkprefix + ':Q6')
                link.parse()
                self.assertEqual(link.site, pywikibot.Site(sitetitle))
                self.assertEqual(link.title, 'Q6')
                self.assertEqual(link.namespace, 0)

    def test_fully_qualified_NS1(self):
        """Test prefixed links with 'Talk:Q6' on enwp is namespace 1."""
        test = [('testwiki:wikidata', 'wikidata:wikidata'),
                ('wikidata:testwiki', 'wikipedia:test')]
        for linkprefix, sitetitle in test:
            with self.subTest(pattern=linkprefix):
                link = Link(linkprefix + ':Talk:Q6')
                link.parse()
                self.assertEqual(link.site, pywikibot.Site(sitetitle))
                self.assertEqual(link.title, 'Q6')
                self.assertEqual(link.namespace, 1)

class TestFullyQualifiedOneSiteFamilyImplicitLinkParser(LinkTestCase):

    """Test links to one site target family without preleading colon."""

    family = 'species'
    code = 'species'

    def setUp(self):
        """Setup tests."""
        super().setUp()
        config.mylang = 'en'
        config.family = 'wikipedia'

    def test_fully_qualified_NS0_family_code(self):
        """Test 'species:species:Main Page' on enwp is namespace 0."""
        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."""
        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."""
        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."""
        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())
        with self.assertRaisesRegex(
                InvalidTitleError,
                "'en:Help:' has no title."):
            link.parse()

    def test_no_text(self):
        """Test that Link doesn't allow empty."""
        link = Link('', self.get_site())
        with self.assertRaisesRegex(
                InvalidTitleError,
                r'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 TestForeignInterwikiLinks(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)
        # bugzilla does not return a json content but redirects to phab.
        # api.Request._json_loads cannot detect this problem and raises
        # a SiteDefinitionError. The site is created anyway but the title
        # cannot be parsed
        with self.assertRaises(SiteDefinitionError):
            link.site
        self.assertEqual(link.site.sitename, 'wikimedia:wikimedia')
        self.assertTrue(link._is_interwiki)

    def test_other_wiki_prefix(self):
        """Test that Link fails if the interwiki prefix is a unknown family."""
        link = Link('bulba:title on auto-generated Site', source=self.site)
        self.assertEqual(link.title, 'Title on auto-generated Site')
        self.assertEqual(link.site.sitename, 'bulba:bulba')
        self.assertTrue(link._is_interwiki)

    def test_invalid_wiki_prefix(self):
        """Test that Link with prefix not listed in InterwikiMap."""
        title = 'Unknownprefix:This title'
        link = Link(title, source=self.site)
        self.assertEqual(link.title, title)
        self.assertEqual(link.site, self.site)
        self.assertFalse(link._is_interwiki)

class TestSiteLink(WikimediaDefaultSiteTestCase):

    """Test parsing namespaces when creating SiteLinks."""

    def _test_link(self, link, title, namespace, site_code, site_fam):
        """Test the separate contents of the link."""
        self.assertEqual(link.title, title)
        self.assertEqual(link.namespace, namespace)
        self.assertEqual(link.site, Site(site_code, site_fam))
        self.assertEqual(link.badges, [])

    def test_site_link(self):
        """Test parsing of title."""
        self._test_link(SiteLink('Foobar', 'enwiki'),
                        'Foobar', Namespace.MAIN, 'en', 'wikipedia')
        self._test_link(SiteLink('Mall:!!', 'svwiki'),
                        '!!', Namespace.TEMPLATE, 'sv', 'wikipedia')
        self._test_link(SiteLink('Vorlage:!!', 'dewikibooks'),
                        '!!', Namespace.TEMPLATE, 'de', 'wikibooks')
        self._test_link(SiteLink('Ai Weiwei: Never Sorry', 'enwiki'),
                        'Ai Weiwei: Never Sorry', Namespace.MAIN,
                        'en', 'wikipedia')

if __name__ == '__main__':  # pragma: no cover
    with suppress(SystemExit):
        unittest.main()


text:
require_relative 'helper'
require 'open3'
require 'security'

module FastlaneCore
  class KeychainImporter
    def self.import_file(path, keychain_path, keychain_password: nil, certificate_password: "", skip_set_partition_list: false, output: FastlaneCore::Globals.verbose?)
      UI.user_error!("Could not find file '#{path}'") unless File.exist?(path)

      command = "security import #{path.shellescape} -k '#{keychain_path.shellescape}'"
      command << " -P #{certificate_password.shellescape}"
      command << " -T /usr/bin/codesign" # to not be asked for permission when running a tool like `gym` (before Sierra)
      command << " -T /usr/bin/security"
      command << " -T /usr/bin/productbuild" # to not be asked for permission when using an installer cert for macOS
      command << " 1> /dev/null" unless output

      UI.command(command) if output
      Open3.popen3(command) do |stdin, stdout, stderr, thrd|
        UI.command_output(stdout.read.to_s) if output

        # Set partition list only if success since it can be a time consuming process if a lot of keys are installed
        if thrd.value.success? && !skip_set_partition_list
          keychain_password ||= resolve_keychain_password(keychain_path)
          set_partition_list(path, keychain_path, keychain_password: keychain_password, output: output)
        else
          # Output verbose if file is already installed since not an error otherwise we will show the whole error
          err = stderr.read.to_s.strip
          if err.include?("SecKeychainItemImport") && err.include?("The specified item already exists in the keychain")
            UI.verbose("'#{File.basename(path)}' is already installed on this machine")
          else
            UI.error(err)
          end
        end
      end
    end

    def self.set_partition_list(path, keychain_path, keychain_password: nil, output: FastlaneCore::Globals.verbose?)
      # When security supports partition lists, also add the partition IDs
      # See https://openradar.appspot.com/28524119
      if Helper.backticks('security -h | grep set-key-partition-list', print: false).length > 0
        command = "security set-key-partition-list"
        command << " -S apple-tool:,apple:,codesign:"
        command << " -s" # This is a needed in Catalina to prevent "security: SecKeychainItemCopyAccess: A missing value was detected."
        command << " -k #{keychain_password.to_s.shellescape}"
        command << " #{keychain_path.shellescape}"
        command << " 1> /dev/null" # always disable stdout. This can be very verbose, and leak potentially sensitive info

        # Showing loading indicator as this can take some time if a lot of keys installed
        Helper.show_loading_indicator("Setting key partition list... (this can take a minute if there are a lot of keys installed)")

        UI.command(command) if output
        Open3.popen3(command) do |stdin, stdout, stderr, thrd|
          unless thrd.value.success?
            err = stderr.read.to_s.strip

            # Inform user when no/wrong password was used as its needed to prevent UI permission popup from Xcode when signing
            if err.include?("SecKeychainItemSetAccessWithPassword")
              keychain_name = File.basename(keychain_path, ".*")
              Security::InternetPassword.delete(server: server_name(keychain_name))

              UI.important("")
              UI.important("Could not configure imported keychain item (certificate) to prevent UI permission popup when code signing\n" \
                       "Check if you supplied the correct `keychain_password` for keychain: `#{keychain_path}`\n" \
                       "#{err}")
              UI.important("")
              UI.important("Please look at the following docs to see how to set a keychain password:")
              UI.important(" - https://docs.fastlane.tools/actions/sync_code_signing")
              UI.important(" - https://docs.fastlane.tools/actions/get_certificates")
            else
              UI.error(err)
            end
          end
        end

        # Hiding after Open3 finishes
        Helper.hide_loading_indicator

      end
    end

    # https://github.com/fastlane/fastlane/issues/14196
    # Keychain password is needed to set the partition list to
    # prevent Xcode from prompting dialog for keychain password when signing
    # 1. Uses keychain password from login keychain if found
    # 2. Prompts user for keychain password and stores it in login keychain for user later
    def self.resolve_keychain_password(keychain_path)
      keychain_name = File.basename(keychain_path, ".*")
      server = server_name(keychain_name)

      # Attempt to find password in keychain for keychain
      item = Security::InternetPassword.find(server: server)
      if item
        keychain_password = item.password
        UI.important("Using keychain password from keychain item #{server} in #{keychain_path}")
      end

      if keychain_password.nil?
        if UI.interactive?
          UI.important("Enter the password for #{keychain_path}")
          UI.important("This passphrase will be stored in your local keychain with the name #{server} and used in future runs")
          UI.important("This prompt can be avoided by specifying the 'keychain_password' option or 'MATCH_KEYCHAIN_PASSWORD' environment variable")
          keychain_password = FastlaneCore::Helper.ask_password(message: "Password for #{keychain_name} keychain: ", confirm: true)
          Security::InternetPassword.add(server, "", keychain_password)
        else
          UI.important("Keychain password for #{keychain_path} was not specified and not found in your keychain. Specify the 'keychain_password' option to prevent the UI permission popup when code signing")
          keychain_password = ""
        end
      end

      return keychain_password
    end

    # server name used for accessing the macOS keychain
    def self.server_name(keychain_name)
      ["fastlane", "keychain", keychain_name].join("_")
    end

    private_class_method :server_name
  end
end

redpajama_set_name: RedPajamaGithub


text:
namespace AdaptiveTriggerLibrary.ConditionModifiers.LogicalModifiers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// A modifier where all values must meet the condition.
    /// </summary>
    public class AndModifier : ModifierBase,
                               ILogicalModifier
    {
        ///////////////////////////////////////////////////////////////////
        #region Private Methods

        private static bool IsConditionMet(bool condition, IEnumerable<bool> values)
        {
            return values?.All(m => m == condition) ?? false;
        }

        #endregion

        ///////////////////////////////////////////////////////////////////
        #region ILogicalModifier

        /// <summary>
        /// Checks if the <paramref name="value"/> meets the specified <paramref name="condition"/>.
        /// </summary>
        /// <param name="condition">The condition.</param>
        /// <param name="value">The actual value.</param>
        /// <exception cref="ArgumentException">The underlying type of <paramref name="condition"/> doesn't match expected condition type,
        /// or the underlying type of<paramref name="value"/> doesn't match the expected value type.</exception>
        /// <exception cref="InvalidCastException">Either <paramref name="condition"/> or <paramref name="value"/> cannot be casted to the specified underlying type.</exception>
        /// <returns>True, if the <paramref name="value"/> meets the specified <paramref name="condition"/>, otherwise false.</returns>
        public override bool IsConditionMet(object condition, object value)
        {
            // Null handling
            if (value == null)
            {
                if (TreatNullAsConditionIsMet)
                    return true;
                if (TreatNullAsConditionIsNotMet)
                    return false;
            }

            Tuple<bool, bool> singleValueParameters;
            Tuple<bool, IEnumerable<bool>> multiValueParameters;

            // Support multiple values
            var parsed = TryGetParsedParameters(condition, value, out multiValueParameters);
            if (parsed)
                return IsConditionMet(multiValueParameters.Item1, multiValueParameters.Item2);

            // Support single values
            parsed = TryGetParsedParameters(condition, value, out singleValueParameters);
            if (parsed)
                return IsConditionMet(singleValueParameters.Item1, new[] {singleValueParameters.Item2});

            // Cast failed
            throw new InvalidCastException(InvalidCastMessage);
        }

        #endregion
    }
}


text:
<mvc:View
	controllerName="sap.m.sample.StandardListItem.List"
	xmlns:mvc="sap.ui.core.mvc"
	xmlns="sap.m">
	<List
		id="ShortProductList"
		headerText="Products"
		items="{
			path: '/ProductCollection',
			sorter: {
				path: 'Name'
			}
		}">
		<items>
			<StandardListItem
				title="{Name}" />
		</items>
	</List>
</mvc:View>


text:
package org.stajistics.aop;

/**
 *
 * @author The Stajistics Project
 *
 */
public interface ProxyFactory<T> {

    T createProxy(T instance);

    public static final class NoOp<T> implements ProxyFactory<T> {

        @SuppressWarnings("rawtypes")
        private static final NoOp instance = new NoOp();

        private NoOp() {}

        @SuppressWarnings("unchecked")
        public static <T> NoOp<T> instance() {
            return instance;
        }

        public T createProxy(final T instance) {
            return instance;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>

<routes xmlns="http://symfony.com/schema/routing"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

    <route id="fos_message_inbox" pattern="/">
        <default key="_controller">FOSMessageBundle:Message:inbox</default>
    </route>

    <route id="fos_message_sent" pattern="/sent">
        <default key="_controller">FOSMessageBundle:Message:sent</default>
    </route>

    <route id="fos_message_deleted" pattern="/deleted">
        <default key="_controller">FOSMessageBundle:Message:deleted</default>
    </route>

    <route id="fos_message_search" pattern="/search">
        <default key="_controller">FOSMessageBundle:Message:search</default>
    </route>

    <route id="fos_message_thread_new" pattern="/new">
        <default key="_controller">FOSMessageBundle:Message:newThread</default>
    </route>

    <route id="zgh_message_inbox_content" pattern="/inbox_content">
        <default key="_controller">FOSMessageBundle:Message:inboxContent</default>
    </route>

    <route id="zgh_message_thread_delete" pattern="/{threadId}/delete">
        <default key="_controller">ZghMsgBundle:Message:delete</default>
        <requirement key="_method">POST|DELETE</requirement>
    </route>

    <route id="fos_message_thread_undelete" pattern="/{threadId}/undelete">
        <default key="_controller">FOSMessageBundle:Message:undelete</default>
        <requirement key="_method">POST</requirement>
    </route>

    <route id="fos_message_list_view" pattern="/{threadId}/messages">
        <default key="_controller">FOSMessageBundle:Message:messageList</default>
    </route>

    <route id="fos_message_thread_view" pattern="/{threadId}">
        <default key="_controller">FOSMessageBundle:Message:thread</default>
    </route>

</routes>


text:
ActiveTest.Tests.Record.date = function()
{
    with(ActiveTest)
    {
        var a = ModelWithStringDates.create({
            name: 'a'
        });
        assert(a.get('created').match(/^\d{4}/) && a.get('updated').match(/^\d{4}/),'created and updated set via string field');
        var old_date = a.get('updated');
        a.set('updated','');
        a.save();
        var new_date = a.get('updated');
        assert(ModelWithStringDates.find(a.id).get('updated') == new_date,'created and updated persist via string field');

        var a = ModelWithDates.create({
            name: 'a'
        });
        assert(ActiveSupport.dateFormat(ActiveSupport.dateFromDateTime(a.get('created')),'yyyy-mm-dd HH:MM:ss').match(/^\d{4}/) && ActiveSupport.dateFormat(ActiveSupport.dateFromDateTime(a.get('updated')),'yyyy-mm-dd HH:MM:ss').match(/^\d{4}/),'created and updated set via date field');
        var old_date = a.get('updated');
        a.set('updated','');
        a.save();
        var new_date = a.get('updated');
        var saved_date = ModelWithDates.find(a.id).get('updated');
        assert(saved_date.toString() == new_date.toString(),'created and updated persist via date field');

        //make sure dates are preserved
        var reload_test = ModelWithDates.find(a.id);
        var old_created = reload_test.get('created');
        reload_test.save();
        reload_test.reload();
        reload_test.save();
        reload_test.reload();
        assert(reload_test.get('created').toString() == old_created.toString(),'created time is preserved on update');
    }
};


text:
using Avalonia.Controls.Platform;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.Threading;

#nullable enable

namespace Avalonia.Web.Blazor
{
    public class BlazorWindowingPlatform : IWindowingPlatform, IPlatformSettings, IPlatformThreadingInterface
    {
        private bool _signaled;
        private static KeyboardDevice? s_keyboard;

        public IWindowImpl CreateWindow() => throw new NotSupportedException();

        IWindowImpl IWindowingPlatform.CreateEmbeddableWindow()
        {
            throw new NotImplementedException();
        }

        public ITrayIconImpl? CreateTrayIcon()
        {
            return null;
        }

        public static KeyboardDevice Keyboard => s_keyboard ??
            throw new InvalidOperationException("BlazorWindowingPlatform not registered.");

        public static void Register()
        {
            var instance = new BlazorWindowingPlatform();
            s_keyboard = new KeyboardDevice();
            AvaloniaLocator.CurrentMutable
                .Bind<IClipboard>().ToSingleton<ClipboardStub>()
                .Bind<ICursorFactory>().ToSingleton<CursorFactoryStub>()
                .Bind<IKeyboardDevice>().ToConstant(s_keyboard)
                .Bind<IPlatformSettings>().ToConstant(instance)
                .Bind<IPlatformThreadingInterface>().ToConstant(instance)
                .Bind<IRenderLoop>().ToConstant(new RenderLoop())
                .Bind<IRenderTimer>().ToConstant(ManualTriggerRenderTimer.Instance)
                .Bind<ISystemDialogImpl>().ToSingleton<SystemDialogsStub>()
                .Bind<IWindowingPlatform>().ToConstant(instance)
                .Bind<IPlatformIconLoader>().ToSingleton<IconLoaderStub>()
                .Bind<PlatformHotkeyConfiguration>().ToSingleton<PlatformHotkeyConfiguration>();
        }

        public Size DoubleClickSize { get; } = new Size(2, 2);

        public TimeSpan DoubleClickTime { get; } = TimeSpan.FromMilliseconds(500);

        public void RunLoop(CancellationToken cancellationToken)
        {
            throw new NotSupportedException();
        }

        public IDisposable StartTimer(DispatcherPriority priority, TimeSpan interval, Action tick)
        {
            return GetRuntimePlatform()
                .StartSystemTimer(interval, () =>
                {
                    Dispatcher.UIThread.RunJobs(priority);
                    tick();
                });
        }

        public void Signal(DispatcherPriority priority)
        {
            if (_signaled)
                return;

            _signaled = true;

            IDisposable? disp = null;

            disp = GetRuntimePlatform()
                .StartSystemTimer(TimeSpan.FromMilliseconds(1),
                    () =>
                    {
                        _signaled = false;
                        disp?.Dispose();

                        Signaled?.Invoke(null);
                    });
        }

        public bool CurrentThreadIsLoopThread
        {
            get
            {
                return true; // Blazor is single threaded.
            }
        }

        public event Action<DispatcherPriority?>? Signaled;

        private static IRuntimePlatform GetRuntimePlatform()
        {
            return AvaloniaLocator.Current.GetRequiredService<IRuntimePlatform>();
        }
    }
}


text:
package uk.co.samholder.genetiq.representation.vector;

import uk.co.samholder.genetiq.util.GenerationRange;
import java.util.Random;
import uk.co.samholder.genetiq.population.Populator;

/**
 * A random vector populator.
 * @author Sam Holder
 */
public class RandomVectorPopulator implements Populator<Vector>
{
    private Random random;
    private GenerationRange[] generationRanges;

    public RandomVectorPopulator(Random random, int dimensionality) {
        generationRanges = new GenerationRange[dimensionality];
        this.random = random;
    }

    public RandomVectorPopulator(Random random, int dimensionality, float minGeneratedValue, float maxGeneratedValue) {
        this(random, dimensionality);
        for (int i=0; i<dimensionality; i++) {
            generationRanges[i] = new GenerationRange(minGeneratedValue, maxGeneratedValue);
        }
    }

    public RandomVectorPopulator(Random random, GenerationRange ... ranges) {
        this(random, ranges.length);
        generationRanges = ranges;
    }

    @Override
    public Vector getIndividual() {
        Vector vector = new Vector(generationRanges.length);
        for (int i=0; i<generationRanges.length; i++) {
            vector.setValue(i, generationRanges[i].Generate(random));
        }
        return vector;
    }
}


text:
package temportalist.origin.internal.client

import net.minecraftforge.fml.relauncher.{Side, SideOnly}
import temportalist.origin.api.client.EnumHUDOverlay
import temportalist.origin.foundation.client.IModClient
import temportalist.origin.foundation.common.IModPlugin
import temportalist.origin.internal.common.Origin

/**
  *
  * Created by TheTemportalist on 4/9/2016.
  *
  * @author TheTemportalist
  */
@SideOnly(Side.CLIENT)
object Client extends IModClient {

	override def getMod: IModPlugin = Origin

	/**
	  * This needs to be called in [[temportalist.origin.foundation.common.IProxy.preInit]]
	  */
	override def preInit(): Unit = {
		super.preInit()
		this.registerOverlay(OverlayHealth, EnumHUDOverlay.PRE)
	}

}


text:
require 'spec_helper'

# Specs in this file have access to a helper object that includes
# the AppointmentsHelper. For example:
#
# describe AppointmentsHelper do
#   describe "string concat" do
#     it "concats two strings with spaces" do
#       helper.concat_strings("this","that").should == "this that"
#     end
#   end
# end
describe AppointmentsHelper do
  pending "add some examples to (or delete) #{__FILE__}"
end


text:
<?xml version="1.0" encoding="utf-8"?>

<resources>

    <string name="error_orgs_load">Грешка при зареждане на профила и организациите</string>
    <string name="error_issues_load">Грешка при зареждане на заданията</string>
    <string name="error_repos_load">Грешка при зареждане на хранилищата</string>
    <string name="error_repo_load">Грешка при зареждане на хранилището</string>
    <string name="error_gist_load">Грешка при зареждане на Gist</string>
    <string name="error_news_load">Грешка при зареждане на новините</string>
    <string name="error_followers_load">Грешка при зареждане на феновете</string>
    <string name="error_people_load">Грешка при зареждане на хората</string>
    <string name="error_person_load">Грешка при зареждане на лицето</string>
    <string name="error_gist_file_load">Грешка при зареждане на съдържанието на Gist</string>
    <string name="error_gists_load">Грешка при зареждане на наличните Gist</string>
    <string name="error_issue_load">Грешка при зареждане на заданието</string>
    <string name="error_collaborators_load">Грешка при зареждане на сътрудниците</string>
    <string name="error_milestones_load">Грешка при зареждане на етапите</string>
    <string name="error_labels_load">Грешка при зареждане на етикетите</string>
    <string name="error_bookmarks_load">Грешка при зареждане на показалците</string>
    <string name="error_members_load">Грешка при зареждане на членовете</string>
    <string name="error_commits_load">Грешка при зареждане на промените</string>
    <string name="error_commit_load">Грешка при зареждане на промяната</string>
    <string name="error_file_load">Грешка при зареждане на файла</string>
    <string name="error_code_load">Грешка при зареждане на кода</string>
    <string name="error_refs_load">Грешка при зареждане на разклоненията и маркерите</string>

    <string name="loading_gist">Зарежда се Gist…</string>
    <string name="random_gist">Зарежда се произволен Gist…</string>
    <string name="loading_more_issues">Зареждат се още задания…</string>
    <string name="loading_issues">Зареждат се заданията…</string>
    <string name="loading_comments">Зареждат се коментарите…</string>
    <string name="loading_repositories">Зареждат се хранилищата…</string>
    <string name="loading_issue">Зарежда се заданието…</string>
    <string name="loading_news">Зареждат се новините…</string>
    <string name="loading_followers">Зареждат се феновете…</string>
    <string name="loading_people">Зареждат се хората…</string>
    <string name="loading_gists">Зареждат се Gists…</string>
    <string name="loading_collaborators">Зареждат се сътрудниците…</string>
    <string name="loading_milestones">Зареждат се етапите…</string>
    <string name="loading_labels">Зареждат се етикетите…</string>
    <string name="loading_commits">Зареждат се промените…</string>
    <string name="loading_files_and_comments">Зареждат се файловете и коментарите…</string>
    <string name="loading_refs">Зареждат се разклоненията и маркерите…</string>

    <string name="no_bookmarks">Няма показалци</string>
    <string name="no_repositories">Няма хранилища</string>
    <string name="no_issues">Няма задания</string>
    <string name="no_gists">Няма налични Gist</string>
    <string name="no_people">Няма хора</string>
    <string name="no_followers">Няма фенове</string>
    <string name="no_members">Няма членове</string>
    <string name="no_news">Няма новини</string>
    <string name="no_commits">Няма промени</string>

    <string name="updating_assignee">Обновяване на изпълнителя…</string>
    <string name="updating_issue">Обновяване на заданието…</string>
    <string name="updating_labels">Обновяване на етикетите…</string>
    <string name="updating_milestone">Обновяване на етапа…</string>

    <string name="app_name">GitHub</string>
    <string name="news">Новини</string>
    <string name="issues">Задания</string>
    <string name="gists">Gists</string>
    <string name="commits">Промени</string>
    <string name="find_repositories">Търсене на хранилища</string>
    <string name="find_issues">Търсене на задания</string>
    <string name="search_title">Търсене…</string>
    <string name="clear_search_history">Изтриване на миналите търсения</string>
    <string name="search_history_cleared">Миналите търсения са изтрити</string>
    <string name="login_activity_authenticating">Легитимиране…</string>
    <string name="creating_gist">Създава се нов Gist…</string>
    <string name="create">Създаване</string>
    <string name="create_gist">Създаване на Gist</string>
    <string name="gist_content_hint">puts \'Hello World!\'</string>
    <string name="make_public">общодостъпен</string>
    <string name="gist_file_name_hint">file.rb</string>
    <string name="gist">Gist</string>
    <string name="comments">Коментари</string>
    <string name="files">Файлове</string>
    <string name="open">Отваряне</string>
    <string name="random">Случаен</string>
    <string name="file_name">Име на файла</string>
    <string name="file_content">Съдържание</string>
    <string name="new_gist">Нов Gist</string>
    <string name="filter">Филтър</string>
    <string name="bookmark">Показалец</string>
    <string name="comment">Добавяне на коментар</string>
    <string name="delete">Изтриване</string>
    <string name="refresh">Опресняване</string>
    <string name="dashboard_issues_title">Табло със задания</string>
    <string name="bookmarks">Показалци</string>
    <string name="gists_title">Gists</string>
    <string name="issue_title">Задание #</string>
    <string name="pull_request_title">Заявка за промяна #</string>
    <string name="gist_title">Gist\u0020</string>
    <string name="filter_issues_title">Филтриране на заданията</string>
    <string name="create_comment_title">Добавяне на коментар</string>
    <string name="comment_hint">Напишете коментар</string>
    <string name="show_more">Още…</string>
    <string name="repositories">Хранилища</string>
    <string name="issues_title">Задания</string>
    <string name="edit_labels">Промяна на етикетите</string>
    <string name="milestone_prefix">Етап:</string>
    <string name="edit_milestone">Промяна на етапа</string>
    <string name="edit_assignee">Промяна на изпълнителя</string>
    <string name="description">Описание</string>
    <string name="gist_description_hint">Gist, създаден с Android</string>
    <string name="title">Заглавие</string>
    <string name="edit">Редактиране</string>
    <string name="star">Любим</string>
    <string name="starring_gist">Отбелязване на този Gist като любим…</string>
    <string name="unstar">Премахване от любими</string>
    <string name="unstarring_gist">Премахване на този Gist от любимите…</string>
    <string name="accounts_label">Accounts</string>
    <string name="select_assignee">Възлагане</string>
    <string name="select_milestone">Включване в етап</string>
    <string name="select_labels">Маркиране с етикети</string>
    <string name="select_ref">Избиране на разклонение или маркер</string>
    <string name="no_milestone">Няма етапи</string>
    <string name="unassigned">Няма изпълнител</string>
    <string name="assigned">е назначен</string>
    <string name="no_gists_found">Не е намерен такъв Gist</string>
    <string name="confirm_gist_delete_title">Потвърдете изтриването</string>
    <string name="confirm_gist_delete_message">Наистина ли искате да изтриете този Gist?</string>
    <string name="deleting_gist">Изтрива се Gist…</string>
    <string name="creating_comment">Добавя се коментар…</string>
    <string name="confirm_bookmark_delete_message">Наистина ли искате да премахнете този показалец?</string>
    <string name="issue_dashboard">Табло със задания</string>
    <string name="new_issue">Ново задание</string>
    <string name="anonymous">Анонимен</string>
    <string name="message_filter_saved">Филтърът на заданията е запазаен като показалец</string>
    <string name="recent">Доскорошни</string>
    <string name="section_issue_status">Състояние:</string>
    <string name="status_open">Отворен</string>
    <string name="status_closed">Приключен</string>
    <string name="section_issue_assigned">Възложен на:</string>
    <string name="assignee_anyone">Който и да е</string>
    <string name="section_issue_milestone">Етап:</string>
    <string name="none">Няма</string>
    <string name="section_issue_labels">Етикети:</string>
    <string name="log_in">Влизане</string>
    <string name="signup_link">За първи път в GitHub? Щракнете тук за записване</string>
    <string name="connection_failed">Не може да се осъществи връзка с GitHub.</string>
    <string name="invalid_login_or_password">Моля, въведете коректно име и парола</string>
    <string name="invalid_password">Моля, въведете коректна парола.</string>
    <string name="password">Парола</string>
    <string name="login_or_email">Име или имейл</string>
    <string name="followers">Фенове</string>
    <string name="following">Следва</string>
    <string name="followers_self">Фенове</string>
    <string name="following_self">Следвате</string>
    <string name="members">Членове</string>
    <string name="closing_issue">Заданието се затваря…</string>
    <string name="reopening_issue">Заданието се връща за доработка…</string>
    <string name="avatar">Портрет</string>
    <string name="creating_issue">Заданието се създава…</string>
    <string name="prefix_created">създаден на\u0020</string>
    <string name="prefix_updated">обновен на\u0020</string>
    <string name="prefix_opened">отворено на\u0020</string>
    <string name="clear">Изчистване</string>
    <string name="open_issues">Отворени задания</string>
    <string name="closed_issues">Приключени задания</string>
    <string name="confirm_bookmark_delete_title">Премахване на показалеца</string>
    <string name="save">Запис</string>
    <string name="apply">Прилагане</string>
    <string name="labels_prefix">Етикети:</string>
    <string name="assignee">Изпълнител</string>
    <string name="milestone">Етап</string>
    <string name="labels">Етикети</string>
    <string name="issue_confirm_close_message">Наистина ли искате да приключите това задание?</string>
    <string name="issue_confirm_reopen_message">Наистина ли искате върнете това задание обратно за доработка?</string>
    <string name="issue_confirm_close_title">Приключване на заданието</string>
    <string name="issue_confirm_reopen_title">Връщане на заданието за доработка</string>
    <string name="closed">Приключено</string>
    <string name="no_description_given">Без описание</string>
    <string name="close">Приключване</string>
    <string name="reopen">Връщане за доработка</string>
    <string name="title_invalid_github_url">Невалиден адрес</string>
    <string name="message_invalid_github_url">Този адрес не може да бъде зареден:\n{0}</string>
    <string name="recently_viewed">ПОСЛЕДНО ПОСЕТЕНИ</string>
    <string name="cancel">Отказ</string>
    <string name="authenticator_conflict_title">Конфликт между приложенията</string>
    <string name="authenticator_conflict_message">Друго приложение е вече настроено за удостоверяване към GitHub.\n\nТекущото приложение може да се използва след като премахнете другото приложение от профила си в GitHub и опресните настройките.</string>
    <string name="opening_repository">Отваряне на {0}…</string>
    <string name="commit_compare_title">Сравняване на промени</string>
    <string name="commit_prefix">Промяна\u0020</string>
    <string name="parent_prefix">Произлязла от\u0020</string>
    <string name="authored">създадена на</string>
    <string name="committed">изпратена на</string>
    <string name="diff_line_message">Какво искаш да направиш?</string>
    <string name="comment_on_line">Добавяне на коментар към реда</string>
    <string name="view_entire_file">Показване на целия файл</string>
    <string name="comparing_commits">Сравняване на {0} промени</string>
    <string name="enable_wrapping">С пренасяне</string>
    <string name="disable_wrapping">Без пренасяне</string>
    <string name="code">Код</string>

    <string name="tab_repositories">хранилища</string>
    <string name="tab_news">новини</string>
    <string name="tab_following_self">следите</string>
    <string name="tab_followers_self">фенове</string>
    <string name="tab_following">следи</string>
    <string name="tab_followers">фенове</string>
    <string name="tab_members">членове</string>
    <string name="tab_code">код</string>
    <string name="tab_commits">промени</string>
    <string name="tab_issues">задания</string>
    <string name="tab_watched">наблюдавани</string>
    <string name="tab_assigned">назначени</string>
    <string name="tab_created">създадени</string>
    <string name="tab_mentioned">споменати</string>
    <string name="tab_mine">мои</string>
    <string name="tab_starred">любими</string>
    <string name="tab_all">всички</string>

    <string name="share">Сподели</string>
    <string name="show_password">Покажи паролата</string>

</resources>


text:
package org.metaworks.spring;

import java.rmi.RemoteException;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.metaworks.dao.TransactionContext;
import org.springframework.beans.factory.annotation.Autowired;

@Aspect
public class TransactionContextAdvice {

    @Before("execution(* org.springframework.transaction.PlatformTransactionManager.commit(..))")
    public void beforeCommit() throws java.rmi.RemoteException {
    	try {
			TransactionContext.getThreadLocalInstance().commit();
		} catch (Exception e) {
			throw new RemoteException(e.getMessage(), e);
		}
    }

    @Before("execution(* org.springframework.transaction.PlatformTransactionManager.rollback(..))")
    public void beforeRollback() throws java.rmi.RemoteException {
    	try {
	    	TransactionContext.getThreadLocalInstance().rollback();
		} catch (Exception e) {
			throw new RemoteException(e.getMessage(), e);
		}
   }
}


text:
#include "base/intmath.hh"
#include "mem/ruby/slicc_interface/RubySlicc_Util.hh"
#include "mem/ruby/system/DirectoryMemory.hh"
#include "mem/ruby/system/System.hh"

using namespace std;

int DirectoryMemory::m_num_directories = 0;
int DirectoryMemory::m_num_directories_bits = 0;
uint64_t DirectoryMemory::m_total_size_bytes = 0;
int DirectoryMemory::m_numa_high_bit = 0;

DirectoryMemory::DirectoryMemory(const Params *p)
    : SimObject(p)
{
    m_version = p->version;
    m_size_bytes = p->size;
    m_size_bits = floorLog2(m_size_bytes);
    m_num_entries = 0;
    m_use_map = p->use_map;
    m_map_levels = p->map_levels;
    m_numa_high_bit = p->numa_high_bit;
}

void
DirectoryMemory::init()
{
    m_num_entries = m_size_bytes / RubySystem::getBlockSizeBytes();

    if (m_use_map) {
        int entry_bits = floorLog2(m_num_entries);
        assert(entry_bits >= m_map_levels);
        m_sparseMemory = new SparseMemory(entry_bits, m_map_levels);
    } else {
        m_entries = new Directory_Entry*[m_num_entries];
        for (int i = 0; i < m_num_entries; i++)
            m_entries[i] = NULL;
        m_ram = g_system_ptr->getMemoryVector();
    }

    m_num_directories++;
    m_num_directories_bits = floorLog2(m_num_directories);
    m_total_size_bytes += m_size_bytes;

    if (m_numa_high_bit == 0) {
        m_numa_high_bit = RubySystem::getMemorySizeBits();
    }
    assert(m_numa_high_bit != 0);
}

DirectoryMemory::~DirectoryMemory()
{
    // free up all the directory entries
    if (m_entries != NULL) {
        for (uint64 i = 0; i < m_num_entries; i++) {
            if (m_entries[i] != NULL) {
                delete m_entries[i];
            }
        }
        delete [] m_entries;
    } else if (m_use_map) {
        delete m_sparseMemory;
    }
}

void
DirectoryMemory::printConfig(ostream& out) const
{
    out << "DirectoryMemory module config: " << m_name << endl
        << "  version: " << m_version << endl
        << "  memory_bits: " << m_size_bits << endl
        << "  memory_size_bytes: " << m_size_bytes << endl
        << "  memory_size_Kbytes: " << double(m_size_bytes) / (1<<10) << endl
        << "  memory_size_Mbytes: " << double(m_size_bytes) / (1<<20) << endl
        << "  memory_size_Gbytes: " << double(m_size_bytes) / (1<<30) << endl;
}

// Static method
void
DirectoryMemory::printGlobalConfig(ostream & out)
{
    out << "DirectoryMemory Global Config: " << endl;
    out << "  number of directory memories: " << m_num_directories << endl;
    if (m_num_directories > 1) {
        out << "  number of selection bits: " << m_num_directories_bits << endl
            << "  selection bits: " << m_numa_high_bit
            << "-" << m_numa_high_bit-m_num_directories_bits
            << endl;
    }
    out << "  total memory size bytes: " << m_total_size_bytes << endl;
    out << "  total memory bits: " << floorLog2(m_total_size_bytes) << endl;
}

uint64
DirectoryMemory::mapAddressToDirectoryVersion(PhysAddress address)
{
    if (m_num_directories_bits == 0)
        return 0;

    uint64 ret = address.bitSelect(m_numa_high_bit - m_num_directories_bits,
                                   m_numa_high_bit);
    return ret;
}

bool
DirectoryMemory::isPresent(PhysAddress address)
{
    bool ret = (mapAddressToDirectoryVersion(address) == m_version);
    return ret;
}

uint64
DirectoryMemory::mapAddressToLocalIdx(PhysAddress address)
{
    uint64 ret = address.bitRemove(m_numa_high_bit - m_num_directories_bits,
                                   m_numa_high_bit)
        >> (RubySystem::getBlockSizeBits());
    return ret;
}

Directory_Entry&
DirectoryMemory::lookup(PhysAddress address)
{
    assert(isPresent(address));
    Directory_Entry* entry;
    uint64 idx;
    DEBUG_EXPR(CACHE_COMP, HighPrio, address);

    if (m_use_map) {
        if (m_sparseMemory->exist(address)) {
            entry = m_sparseMemory->lookup(address);
            assert(entry != NULL);
        } else {
            // Note: SparseMemory internally creates a new Directory Entry
            m_sparseMemory->add(address);
            entry = m_sparseMemory->lookup(address);
        }
    } else {
        idx = mapAddressToLocalIdx(address);
        assert(idx < m_num_entries);
        entry = m_entries[idx];

        if (entry == NULL) {
            entry = new Directory_Entry();
            entry->getDataBlk().assign(m_ram->getBlockPtr(address));
            m_entries[idx] = entry;
        }
    }

    return *entry;
}

#if 0
Directory_Entry&
DirectoryMemory::lookup(PhysAddress address)
{
    assert(isPresent(address));
    Index index = address.memoryModuleIndex();

    if (index < 0 || index > m_size) {
        WARN_EXPR(address.getAddress());
        WARN_EXPR(index);
        WARN_EXPR(m_size);
        ERROR_MSG("Directory Memory Assertion: accessing memory out of range");
    }
    Directory_Entry* entry = m_entries[index];

    // allocate the directory entry on demand.
    if (entry == NULL) {
        entry = new Directory_Entry;
        entry->getDataBlk().assign(m_ram->getBlockPtr(address));

        // store entry to the table
        m_entries[index] = entry;
    }

    return *entry;
}
#endif

void
DirectoryMemory::invalidateBlock(PhysAddress address)
{
    if (m_use_map) {
        assert(m_sparseMemory->exist(address));
        m_sparseMemory->remove(address);
    }
#if 0
    else {
        assert(isPresent(address));

        Index index = address.memoryModuleIndex();

        if (index < 0 || index > m_size) {
            ERROR_MSG("Directory Memory Assertion: "
                      "accessing memory out of range.");
        }

        if (m_entries[index] != NULL){
            delete m_entries[index];
            m_entries[index] = NULL;
        }
    }
#endif
}

void
DirectoryMemory::print(ostream& out) const
{
}

void
DirectoryMemory::printStats(ostream& out) const
{
    if (m_use_map) {
        m_sparseMemory->printStats(out);
    }
}

DirectoryMemory *
RubyDirectoryMemoryParams::create()
{
    return new DirectoryMemory(this);
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Bieter Eye Care Center Services and Products</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/business-casual.css" rel="stylesheet">

    <link href="http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Josefin+Slab:100,300,400,600,700,100italic,300italic,400italic,600italic,700italic" rel="stylesheet" type="text/css">

Bieter Eye Center

8617 W. Pt. Douglas Rd. S. Suite #110 Cottage Grove, MN 55016

Phone: 651-769-1020 Fax: 651-769-1021

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                Bieter Eye Center

                        Home

                        Contact Us

                        About

                        Services and Products

                        Optos

                        Why Use Our Optical?

                        Insurance Info

                        Promotions

                        Schedule An Appointment

                        Patient Forms

General Patient Information Form

Patient Financial Policy Form

2015 Promotions

We have a great package for all of our "young" patients out there! This promotion is for anyone who fits a frame from our children's section. When you purchase a pair of glasses, you get a second complete pair for $100! A spare pair is essential for active kids and sunglasses are included, too!

When you purchase 2 pairs of glasses on the same day, you will receive a FREE FRAME on the second pair purchased. The lenses will be the exact same quality as in the first pair. Take advantage of this great savings!!

Bieter Bucks Promotion

We appreciate your referrals! Refer a patient and receive $10 in Bieter Bucks! Accumulate up to $50/year towards goods!

Other Ongoing Promotions from Bieter Eye Center

 When you purchase a year's supply of contacts from us, receive a FREE FRAME with the purchase of a pair of glasses, up to $150!!!

 We offer every discount and rebate available for savings on your contact lens purchase.

 For those of you who do not have any insurance, please call us and we will discuss options to save money on your exam, glasses, and/or contacts.

(Note that the deals and discounts that we offer can not be used in conjunction with any insurance or discounts you may have through your insurance. We will help determine the best savings for you.)

Copyright © Your Website 2014


text:
package aceim.app.dataentity;

import aceim.api.dataentity.ProtocolServiceFeature;
import aceim.api.utils.Logger;
import aceim.app.service.ProtocolService;
import android.content.res.Resources;
import android.os.Parcel;
import android.os.Parcelable;

public class ProtocolResources extends PluginResources {

	private String protocolServiceName;
	private String protocolName;
	private String protocolVersion;
	private String apiVersion;

	private ProtocolServiceFeature[] mFeatures;

	public ProtocolResources(ProtocolService service) {

		super(service.getProtocolServicePackageName(), null);

		fillResources(service);
	}

	private void fillResources(ProtocolService service) {
		try {
			Resources r = getNativeResourcesForProtocol(service.getContext().getPackageManager());

			mFeatures = service.getProtocol().getProtocolFeatures();
			protocolName = service.getProtocol().getProtocolName();

			this.protocolServiceName = r.getString(service.getServiceInfo().applicationInfo.labelRes);
		} catch (Exception e) {
			Logger.log(e);
			this.protocolServiceName = service.getServiceClassName();
		}
	}

	public ProtocolResources(Parcel in) {
		super(in);
		this.protocolName = in.readString();
		this.protocolServiceName = in.readString();
		this.protocolVersion = in.readString();
		this.apiVersion = in.readString();

		Parcelable[] p = in.readParcelableArray(ProtocolServiceFeature.class.getClassLoader());

		if (p == null) {
			p = new Parcelable[0];
		}

		this.mFeatures = new ProtocolServiceFeature[p.length];

		for (int i=0; i<p.length; i++) {
			this.mFeatures[i] = (ProtocolServiceFeature) p[i];
		}
	}

	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		super.writeToParcel(dest, flags);
		dest.writeString(protocolName);
		dest.writeString(protocolServiceName);
		dest.writeString(protocolVersion);
		dest.writeString(apiVersion);
		dest.writeParcelableArray(mFeatures, flags);
	}

	public static final Parcelable.Creator<ProtocolResources> CREATOR = new Parcelable.Creator<ProtocolResources>() {
		public ProtocolResources createFromParcel(Parcel in) {
			in.readString();
			return new ProtocolResources(in);
		}

		public ProtocolResources[] newArray(int size) {
			return new ProtocolResources[size];
		}
	};

	public int getProtocolServiceIconId() {
		return 0;
	}

	/**
	 * @return the protocolName
	 */
	public String getProtocolName() {
		return protocolName;
	}

	@Override
	public String toString() {
		return protocolServiceName;
	}

	public ProtocolServiceFeature[] getFeatures() {
		return mFeatures;
	}

	public ProtocolServiceFeature getFeature(String featureId){
		if (mFeatures == null || mFeatures.length < 1 || featureId == null) {
			return null;
		}

		for (ProtocolServiceFeature feature : mFeatures) {
			if (feature.getFeatureId().equals(featureId)) {
				return feature;
			}
		}

		return null;
	}

	public ProtocolServiceFeature getFeature(int featureIdHash) {
		if (mFeatures == null || mFeatures.length < 1 || featureIdHash == 0) {
			return null;
		}

		for (ProtocolServiceFeature feature : mFeatures) {
			if (feature.getFeatureId().hashCode() == featureIdHash) {
				return feature;
			}
		}

		return null;
	}

	/**
	 * @return the protocolVersion
	 */
	public String getProtocolVersion() {
		return protocolVersion;
	}

	/**
	 * @param protocolVersion the protocolVersion to set
	 */
	public void setProtocolVersion(String protocolVersion) {
		this.protocolVersion = protocolVersion;
	}

	/**
	 * @return the apiVersion
	 */
	public String getApiVersion() {
		return apiVersion;
	}

	/**
	 * @param apiVersion the apiVersion to set
	 */
	public void setApiVersion(String apiVersion) {
		this.apiVersion = apiVersion;
	}
}


text:
/**
 * The utility sets up the default README.md based on the PARTNER environment variable
 *
 * For example `PARTNER=cloud9 npm install` will replace README.md with README.cloud9.md
 */
var fs = require('fs');
var path = require('path');

if (process.env.PARTNER) {
  var readme = path.join(__dirname, '../README.md'); // README.md
  var slReadme = path.join(__dirname, '../README.strongloop.md'); // README.strongloop.md
  var partnerReadme = path.join(__dirname, '../README.' + process.env.PARTNER + '.md'); // README.<partner>.md, for example README.cloud9.md
  // If the provider specific README exists
  if (fs.existsSync(partnerReadme)) {
    // Rename README.md to be README.strongloop.md
    if (fs.existsSync(readme)) {
      fs.renameSync(readme, slReadme);
      console.log(readme, '-->', slReadme);
    }
    // Rename README.<partner>.md to be README.md
    fs.renameSync(partnerReadme, readme);
    console.log(partnerReadme, '-->', readme);
  }
}


text:
package org.apidesign.demo.minesweeper;

public class BrowserMain {
    private BrowserMain() {
    }

    public static void main(String... args) throws Exception {
        Main.onPageLoad();
    }
}


text:
import React from 'react';
import Actions from '../actions/Actions';
import PersonStore from '../stores/PersonStore';
import Remarkable from 'remarkable';

// The markdown converter using remarkable
const md = new Remarkable();

/**
  * The react component that lists all the people
  */
export default class PeopleList extends React.Component {
  // Initialize props and state
  constructor(props) {
    super(props);
    this.onStoreChange = this.onStoreChange.bind(this);
    this.state = this._getStateFromStore()
  }
  // Get the array from the store by running the static method `getPeople()` on the store
  _getStateFromStore() {
    return PersonStore.getPeople()
  }
  // Set the state when the store changes
  onStoreChange() {
    this.setState(this._getStateFromStore);
  }
  // Listen for changes from the store
  componentDidMount() {
    PersonStore.listen(this.onStoreChange);
  }
  // Unlisten for changes from the store
  componentWillUnmount() {
    PersonStore.unlisten(this.onStoreChange);
  }
  // Send the delete person action so the person gets delted
  deletePerson(index) {
    Actions.deletePerson(index)
  }
  // Render the actual component
  render() {
    // Map the array to react representation of the data
    var peopleNodes = this.state.people.map((person, i) => {
      return (

Name: {person.name}

Description:

          <button className='btn btn-danger' onClick={this.deletePerson.bind(this, i)}>Delete</button>

      )
    });
    // Return the list of people and peopleNodes (the array which we mapped)
    return (

List

        {peopleNodes}

    )
  }
}


text:
from urllib2 import urlopen, URLError
from json import loads, dumps
from datetime import datetime, time
from calendar import TimeEncoding, day_abbr

from html_templates import html_weather

__all__ = ["weather_data"]

locales = {
    "en": "en_US.utf8",
    "ru": "ru_RU.utf8",
    "uk": "uk_UA.utf8"
}

def wwo_query(city, lang, num_day=4):

    class WWOparse():
        def __init__(self, location, init_lang, number_day):
            self.__key = "wqwuamhcnha5rpf4cng4qyjn"
            self.__baseurl = ("http://api.worldweatheronline.com/free/v1/" +
                              "weather.ashx?q={q}" +
                              "&format=json" +
                              "&num_of_days={nd}" +
                              "&key={key}" +
                              "&lang={lang}")
            self.__query = self.__baseurl.format(q=location, nd=number_day,
                                                 key=self.__key, lang=init_lang)

        def query(self):
            try:
                response = loads(urlopen(self.__query).read())["data"]
            except URLError:
                return "Failed in provaider"
            if "error" in response:
                return response["error"]
            else:
                return response

    return WWOparse(city, lang, num_day).query()

def parse_date(date_str):
    date = map(int, date_str.split("-"))
    if len(date) != 3:
        return datetime.utcnow()
    else:
        return datetime(date[0], date[1], date[2])

def parse_time(time_str):
    times, prefix = time_str.split()
    add_hours = 0 if prefix == "AM" else 12
    h, minute = map(int, times.split(":"))
    return datetime.combine(datetime.today(), time(h + add_hours, minute))

def get_day_name(day_no, lang):
    locale = locales[lang]
    with TimeEncoding(locale):
        s = day_abbr[day_no - 1]
        return s

def gen_weather_future(dict_weather, temp_degree="C"):
    day_temp = "tempMax{d}".format(d=temp_degree) if temp_degree in "CF" else "tempMaxC"
    night_temp = "tempMin{d}".format(d=temp_degree) if temp_degree in "CF" else "tempMinC"
    return [{"date": parse_date(weather_day["date"]).isoweekday(),
             "weather_ico": weather_day["weatherIconUrl"][0]["value"],
             "day_temp": weather_day[day_temp],
             "night_temp": weather_day[night_temp]} for weather_day in dict_weather["weather"]]

def gen_weather_now(dict_weather, temp_degree="C", lang="ru"):
    current = dict_weather["current_condition"][0]
    temp = "temp_{d}".format(d=temp_degree) if temp_degree in "CF" else "temp_C"
    lng = "lang_{l}".format(l=lang) if lang in ("uk", "ru") else "weatherDesc"
    location = dict_weather[u"request"][0][u"query"]
    koeff_mile_to_ms = 2.2371364653243848
    return {"temp": current[temp],
            "location": location,
            "windspeedMiles": int(float(current["windspeedMiles"])/koeff_mile_to_ms),
            "weather_ico": current["weatherIconUrl"][0]["value"],
            "precipMM": current["precipMM"],
            "weather": current[lng][0]["value"].encode("utf8")}

def gen_weather(dict_weather, temp_degree="C", lang="ru"):
    if type(dict_weather) == list:
        lang = "uk"
        dict_weather = wwo_query("Donetsk,Ukraine", lang)
    elif type(dict_weather) == str:
        return dict_weather
    return {"weather_now": gen_weather_now(dict_weather, temp_degree, lang),
            "weather_future": gen_weather_future(dict_weather, temp_degree)}

def weather_data(lang, degree, loc):
    whether_dict = gen_weather(wwo_query(loc, lang), degree, lang)
    if type(whether_dict) == str:
        return "Service temporary down"
    else:
        return html_weather.format(place=whether_dict["weather_now"]["location"],
                                   img_wh_now=whether_dict["weather_now"]["weather_ico"],
                                   current_temp=whether_dict["weather_now"]["temp"],
                                   d_w_1=get_day_name(whether_dict["weather_future"][0]["date"], lang),
                                   d_w_2=get_day_name(whether_dict["weather_future"][1]["date"], lang),
                                   d_w_3=get_day_name(whether_dict["weather_future"][2]["date"], lang),
                                   d_w_4=get_day_name(whether_dict["weather_future"][3]["date"], lang),
                                   img_wh_1=whether_dict["weather_future"][0]["weather_ico"],
                                   img_wh_2=whether_dict["weather_future"][1]["weather_ico"],
                                   img_wh_3=whether_dict["weather_future"][2]["weather_ico"],
                                   img_wh_4=whether_dict["weather_future"][3]["weather_ico"],
                                   d_t_1=whether_dict["weather_future"][0]["day_temp"],
                                   d_t_2=whether_dict["weather_future"][1]["day_temp"],
                                   d_t_3=whether_dict["weather_future"][2]["day_temp"],
                                   d_t_4=whether_dict["weather_future"][3]["day_temp"],
                                   n_t_1=whether_dict["weather_future"][0]["night_temp"],
                                   n_t_2=whether_dict["weather_future"][1]["night_temp"],
                                   n_t_3=whether_dict["weather_future"][2]["night_temp"],
                                   n_t_4=whether_dict["weather_future"][3]["night_temp"],
                                   pogoda=whether_dict["weather_now"]["weather"],
                                   wind=whether_dict["weather_now"]["windspeedMiles"],
                                   deg=str(degree),
                                   water_mm=whether_dict["weather_now"]["precipMM"]), whether_dict


text:
<?php

namespace mako\tests\unit\database\query;

use \mako\database\query\Query;

use \Mockery as m;

/**
 * @group unit
 */

class MySQLBuilderTest extends \PHPUnit_Framework_TestCase
{
	/**
	 *
	 */

	public function tearDown()
	{
		m::close();
	}

	/**
	 *
	 */

	protected function getConnection()
	{
		$connection = m::mock('\mako\database\Connection');

		$connection->shouldReceive('getDialect')->andReturn('mysql');

		return $connection;
	}

	/**
	 *
	 */

	protected function getBuilder($table = 'foobar')
	{
		return (new Query($this->getConnection()))->table($table);
	}

	/**
	 *
	 */

	public function testBasicSelect()
	{
		$query = $this->getBuilder();

		$query = $query->getCompiler()->select();

		$this->assertEquals('SELECT * FROM `foobar`', $query['sql']);
		$this->assertEquals(array(), $query['params']);
	}
}


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

[RequireComponent (typeof (Rigidbody))]
public class GravityBody : MonoBehaviour {

	private static List<GravityAttractor> planets = new List<GravityAttractor>();
	public float gravForce;

	void Awake () {
		foreach (GameObject planet in GameObject.FindGameObjectsWithTag("planet")) {
			planets.Add(planet.GetComponent<GravityAttractor>());
		}
		//planets.Add(GameObject.FindGameObjectWithTag("planet").GetComponent<GravityAttractor>());
		GetComponent<Rigidbody>().useGravity = false;
		GetComponent<Rigidbody>().freezeRotation = true;
	}

	void Start() {
		GravityAttractor.AddObject (this);
	}

	void OnDestroy(){
		GravityAttractor.RemoveObject (this);
	}

	void FixedUpdate () {
		foreach (GravityAttractor planet in planets) {
			//Debug.Log("Distance between player and: "+planet.name+ " is: "+Vector3.Distance(planet.transform.position, GetComponent<Rigidbody>().position));
			//Debug.Log("Mass of Planet: "+plane t.name+ " is: "+planet.GetComponent<Rigidbody> ().mass);
			Debug.Log ("Gravitational Force of: " + planet.name + " on the player is: " + (0.06 * planet.GetComponent<Rigidbody> ().mass) / Mathf.Pow(0.00001f + (Vector3.Distance (planet.transform.position, GetComponent<Rigidbody> ().position)),2));
			//Debug.Log ("Planet name is: " + planet.name);
			gravForce = (float)(0.06 * planet.GetComponent<Rigidbody> ().mass) / Mathf.Pow(0.00001f + (Vector3.Distance (planet.transform.position, GetComponent<Rigidbody> ().position)),2);
			planet.Attract (GetComponent<Rigidbody> (), gravForce);
		}
		planets.Sort (delegate(GravityAttractor x, GravityAttractor y) {
			return (int)Vector3.Distance (x.transform.position, GetComponent<Rigidbody> ().position).CompareTo(Vector3.Distance (y.transform.position, GetComponent<Rigidbody> ().position));
		});
		planets[0].Capture (GetComponent<Rigidbody> ());
	}

}


text:
package de.einwesen.porttunnel.net;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.commons.logging.LogFactory;

import de.einwesen.porttunnel.log.ConditionalStackLog;
import de.einwesen.porttunnel.log.ConditionalStackLog.STACK_LOGLEVEL;

/**
 * Forwards traffic on a local port to an Destination port.
 *
 * @author EinWesen
 *
 */
public class ConnectionProcessor implements Runnable {

	private final int localPort;
	private final String remoteHost;
	private final int remotePort;
	private final TunnelSocketFactory socketFactory;
	private boolean isRunning = false;

	private ServerSocket srvSocket = null;

	/**
	 * @param localPort
	 * @param remoteHost
	 * @param remotePort
	 * @param socketFactory
	 */
	public ConnectionProcessor(int localPort, String remoteHost, int remotePort, TunnelSocketFactory socketFactory) {
		this.localPort = localPort;
		this.remoteHost = remoteHost;
		this.remotePort = remotePort;
		this.socketFactory = socketFactory;
	}

	private static final ConditionalStackLog LOGGER = ConditionalStackLog.getInstance(LogFactory.getLog(ConnectionProcessor.class));

	@Override
	public void run() {

		LOGGER.info("Fowarding traffic to: " + remoteHost + ":" + remotePort );
		LOGGER.info("Connection Type: " + socketFactory.getConnectionTypeString() );

		try  {
			srvSocket = this.socketFactory.openSocket(remoteHost, remotePort);
			LOGGER.info("Listening on: " + srvSocket.getLocalSocketAddress() );
		} catch (IOException e) {
			LOGGER.fatal("Can not open local socket", e, STACK_LOGLEVEL.TRACE);
		}

		if (srvSocket != null) {
			isRunning = true;
			while (isRunning) {
				try {
					LOGGER.trace("Waiting for connection...");
					final Socket clientSocket = srvSocket.accept();
					LOGGER.info("Incoming from " + clientSocket.getRemoteSocketAddress() + " . Connecting to target...");

					// Try to create a tunnel to the destination
					Socket targetSocket = null;

					try {
						targetSocket = new Socket(remoteHost, remotePort);

						//Start sending to target first
						final TrafficProcessor source2Target = new TrafficProcessor(clientSocket, targetSocket, 1024);
						source2Target.setSourceName(clientSocket.getRemoteSocketAddress().toString());
						source2Target.setTargetName(remoteHost + ":" + remotePort);

						new Thread(source2Target, TrafficProcessor.class.getSimpleName() + " " + source2Target.getSourceName() + " -> " + source2Target.getTargetName()).start();

						final TrafficProcessor target2source = new TrafficProcessor(targetSocket, clientSocket, 1024);
						target2source.setTargetName(clientSocket.getRemoteSocketAddress().toString());
						target2source.setSourceName(remoteHost + ":" + remotePort);

						new Thread(target2source, TrafficProcessor.class.getSimpleName() + " " + target2source.getSourceName() + " -> " + target2source.getTargetName()).start();

					} catch (Throwable e) {
						LOGGER.error("Could not connect to target. Closing incoming connection.", e,  STACK_LOGLEVEL.DEBUG);
						try {
							clientSocket.close();
						} catch (Throwable e1) {
							LOGGER.trace("Could not close incoming connection", e1);
						}
					}

				} catch (Throwable e) {
					LOGGER.error("Error waiting for connection", e,  STACK_LOGLEVEL.DEBUG);
				}
			}

		}

		isRunning = false;

	}

	public void stopRunning() {
		if (isRunning) {
			try {
				this.srvSocket.close();
			} catch (IOException e) {
				LOGGER.trace("Could not close server connection", e);
			}
			isRunning = false;
		}
	}

}


text:
namespace Microsoft.Azure.Management.Network.Models
{

    /// <summary>
    /// Defines values for IPAllocationMethod.
    /// </summary>
    public static class IPAllocationMethod
    {
        public const string Static = "Static";
        public const string Dynamic = "Dynamic";
    }
}


text:
package io.gatling.http.fetch

import io.gatling.BaseSpec

import org.asynchttpclient.uri.Uri

class CssParserSpec extends BaseSpec {

  val rootURI = Uri.create("http://akka.io/")

  def rulesUri(css: String) = CssParser.extractResources(rootURI, css).map(_.url)

  "parsing CSS" should "handle an empty CSS" in {
    rulesUri("") shouldBe empty
  }

  it should "fetch imports" in {
    val css = """
        @import url("import1.css");
        body{background-image: url('backgrounds/blizzard.png');}
        @import url("import2.css");"""

    rulesUri(css) shouldBe Seq("http://akka.io/import1.css", "http://akka.io/import2.css")
  }

  it should "ignore commented imports with a simple CSS" in {
    val css = """
        /*@import url("import1.css");*/
        body{background-image: url('backgrounds/blizzard.png');}
        @import url("import2.css");"""

    rulesUri(css) shouldBe Seq("http://akka.io/import2.css")
  }

  def extractUrl(s: String): Option[String] =
    CssParser.extractUrl(s, 0, s.length)

  "extractUrl" should "handle unquoted url" in {
    extractUrl("import2.css") shouldBe Some("import2.css")
  }

  it should "handle unquoted url surrounded with whitespaces" in {
    extractUrl(" import2.css ") shouldBe Some("import2.css")
  }

  it should "handle double quoted url" in {
    extractUrl("\"import2.css\"") shouldBe Some("import2.css")
  }

  it should "handle double quoted url surrounded with whitespaces" in {
    extractUrl("\" import2.css \"") shouldBe Some("import2.css")
  }

  it should "handle single quoted url" in {
    extractUrl("'import2.css'") shouldBe Some("import2.css")
  }

  it should "handle single quoted url surrounded with whitespaces" in {
    extractUrl("' import2.css '") shouldBe Some("import2.css")
  }

  it should "handle empty unquoted url" in {
    extractUrl("") shouldBe None
  }

  it should "handle empty unquoted url surrounded with whitespaces" in {
    extractUrl("  ") shouldBe None
  }

  it should "handle empty double quoted url" in {
    extractUrl("\"\"") shouldBe None
  }

  it should "handle empty double quoted url surrounded with whitespaces" in {
    extractUrl("\"  \"") shouldBe None
  }

  it should "handle empty single quoted url" in {
    extractUrl("''") shouldBe None
  }

  it should "handle empty single quoted url surrounded with whitespaces" in {
    extractUrl("'  '") shouldBe None
  }
}


text:
package programmersguide.workingwithocr.performocronimage.java;

import com.aspose.ocr.*;

public class PerformOCROnImage
{
    public static void main(String[] args) throws Exception
    {
        // The path to the documents directory.
        String dataDir = "src/programmersguide/workingwithocr/performocronimage/data/";

        /// Set the paths
        String imagePath = dataDir + "Sampleocr.bmp";

        // Create an instance of OcrEngine
        OcrEngine ocr = new OcrEngine();

        // Set image file
        ocr.setImage(ImageStream.fromFile(imagePath));

        // Perform OCR and get extracted text
        try {
            if (ocr.process()) {
                System.out.println("\ranswer -> " + ocr.getText());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}