text:
"""Test the icat.query module.
"""

import datetime
import re
import warnings
import pytest
import icat
import icat.config
from icat.query import Query
from conftest import getConfig, icat_version, require_icat_version, UtcTimezone

@pytest.fixture(scope="module")
def client(setupicat):
    client, conf = getConfig()
    client.login(conf.auth, conf.credentials)
    return client

# Note: the number of objects returned in the queries and their
# attributes obviously depend on the content of the ICAT and need to
# be kept in sync with the reference input used in the setupicat
# fixture.  This content also depends on the version of ICAT server we
# are talking to and the ICAT schema this server provides.
#
# Note: the exact query string is considered an implementation detail
# that is deliberately not tested here.  We limit the tests to check
# the presence of some key fragments in the various clauses of the
# queries.

investigation = None
tzinfo = UtcTimezone() if UtcTimezone else None

# The the actual number of rules in the test data differs with the
# ICAT version.
have_icat_5 = 0 if icat_version < "5.0" else 1
all_rules = 110 + 48*have_icat_5
grp_rules = 50 + 30*have_icat_5

@pytest.mark.dependency(name='get_investigation')
def test_query_simple(client):
    """A simple query for an investigation by name.
    """
    # The investigation is reused in other tests.
    global investigation
    name = "10100601-ST"
    query = Query(client, "Investigation", conditions={"name":"= '%s'" % name})
    print(str(query))
    assert "Investigation" in query.select_clause
    assert query.join_clause is None
    assert "name" in query.where_clause
    assert query.order_clause is None
    assert query.include_clause is None
    assert query.limit_clause is None
    res = client.search(query)
    assert len(res) == 1
    investigation = res[0]
    assert investigation.BeanName == "Investigation"
    assert investigation.name == name

def test_query_datafile(client):
    """Query a datafile by its name, dataset name, and investigation name.
    """
    dfdata = {
        'name': "e208945.nxs",
        'dataset': "e208945",
        'investigation': "12100409-ST"
    }
    conditions = {
        "name": "= '%s'" % dfdata['name'],
        "dataset.name": "= '%s'" % dfdata['dataset'],
        "dataset.investigation.name": "= '%s'" % dfdata['investigation'],
    }
    query = Query(client, "Datafile", conditions=conditions)
    print(str(query))
    assert "Datafile" in query.select_clause
    assert "investigation" in query.join_clause
    assert dfdata['investigation'] in query.where_clause
    assert query.order_clause is None
    assert query.include_clause is None
    assert query.limit_clause is None
    qstr = str(query)
    res = client.search(query)
    assert len(res) == 1
    df = res[0]
    assert df.BeanName == "Datafile"
    assert df.name == dfdata['name']

    # Same example, but use placeholders in the query string now.
    conditions = {
        "name": "= '%(name)s'",
        "dataset.name": "= '%(dataset)s'",
        "dataset.investigation.name": "= '%(investigation)s'",
    }
    query = Query(client, "Datafile", conditions=conditions)
    print(str(query))
    print(str(query) % dfdata)
    assert str(query) % dfdata == qstr
    res = client.search(str(query) % dfdata)
    assert len(res) == 1
    assert res[0] == df

@pytest.mark.dependency(depends=['get_investigation'])
def test_query_investigation_includes(client):
    """Query lots of information about one single investigation.
    """
    includes = { "facility", "type.facility", "investigationInstruments",
                 "investigationInstruments.instrument.facility", "shifts",
                 "keywords", "publications", "investigationUsers",
                 "investigationUsers.user", "investigationGroups",
                 "investigationGroups.grouping", "parameters",
                 "parameters.type.facility" }
    query = Query(client, "Investigation",
                  conditions={"id": "= %d" % investigation.id},
                  includes=includes)
    print(str(query))
    assert "Investigation" in query.select_clause
    assert query.join_clause is None
    assert "id" in query.where_clause
    assert "investigationInstruments" in query.include_clause
    res = client.search(query)
    assert len(res) == 1
    inv = res[0]
    assert inv.BeanName == "Investigation"
    assert inv.id == investigation.id
    assert inv.name == investigation.name
    assert inv.facility.BeanName == "Facility"
    assert inv.type.facility.BeanName == "Facility"
    assert len(inv.investigationInstruments) > 0
    assert len(inv.investigationUsers) > 0
    assert len(inv.investigationGroups) > 0

@pytest.mark.dependency(depends=['get_investigation'])
def test_query_instruments(client):
    """Query the instruments related to a given investigation.
    """
    query = Query(client, "Instrument",
                  order=["name"],
                  conditions={ "investigationInstruments.investigation.id":
                               "= %d" % investigation.id },
                  includes={"facility", "instrumentScientists.user"})
    print(str(query))
    assert "Instrument" in query.select_clause
    assert "investigation" in query.join_clause
    assert "id" in query.where_clause
    assert "name" in query.order_clause
    assert "instrumentScientists" in query.include_clause
    res = client.search(query)
    assert len(res) == 1
    instr = res[0]
    assert instr.BeanName == "Instrument"
    assert instr.facility.BeanName == "Facility"

@pytest.mark.dependency(depends=['get_investigation'])
def test_query_datafile_by_investigation(client):
    """The datafiles related to a given investigation in natural order.
    """
    query = Query(client, "Datafile", order=True,
                  conditions={ "dataset.investigation.id":
                               "= %d" % investigation.id },
                  includes={"dataset", "datafileFormat.facility",
                            "parameters.type.facility"})
    print(str(query))
    assert "Datafile" in query.select_clause
    assert "investigation" in query.join_clause
    assert "id" in query.where_clause
    assert "datafileFormat" in query.include_clause
    res = client.search(query)
    assert len(res) == 4

def test_query_relateddatafile(client):
    """RelatedDatafile is the entity type with the most complicated
    natural order.
    """
    query = Query(client, "RelatedDatafile", order=True)
    print(str(query))
    assert "RelatedDatafile" in query.select_clause
    assert query.where_clause is None
    assert query.order_clause is not None
    assert query.include_clause is None
    assert query.limit_clause is None
    res = client.search(query)
    assert len(res) == 1

def test_query_datacollection(client):
    """There is no sensible order for DataCollection, fall back to id.
    """
    query = Query(client, "DataCollection", order=True)
    print(str(query))
    assert "DataCollection" in query.select_clause
    assert query.join_clause is None
    assert query.where_clause is None
    assert "id" in query.order_clause
    assert query.include_clause is None
    assert query.limit_clause is None
    res = client.search(query)
    assert len(res) == 3 + 2*have_icat_5

def test_query_datafiles_datafileformat(client, recwarn):
    """Datafiles ordered by format.
    Note: this raises a QueryNullableOrderWarning, see below.
    """
    recwarn.clear()
    query = Query(client, "Datafile",
                  order=['datafileFormat', 'dataset', 'name'])
    w = recwarn.pop(icat.QueryNullableOrderWarning)
    assert issubclass(w.category, icat.QueryNullableOrderWarning)
    assert "datafileFormat" in str(w.message)
    print(str(query))
    assert "Datafile" in query.select_clause
    assert "datafileFormat" in query.join_clause
    assert query.where_clause is None
    assert query.order_clause is not None
    assert query.include_clause is None
    assert query.limit_clause is None
    res = client.search(query)
    assert len(res) == 10 + have_icat_5

@pytest.mark.dependency(depends=['get_investigation'])
def test_query_order_direction(client):
    """We may add an ordering direction qualifier.

    This has been added in Issue #48.
    """
    # Try without specifying the ordering direction first:
    query = Query(client, "Datafile",
                  order=["name"],
                  conditions={ "dataset.investigation.id":
                               "= %d" % investigation.id })
    print(str(query))
    assert "Datafile" in query.select_clause
    assert "investigation" in query.join_clause
    assert "id" in query.where_clause
    assert "name" in query.order_clause
    res = client.search(query)
    assert len(res) == 4
    # Ascending order is the default, so we should get the same result:
    query = Query(client, "Datafile",
                  order=[("name", "ASC")],
                  conditions={ "dataset.investigation.id":
                               "= %d" % investigation.id })
    print(str(query))
    assert client.search(query) == res
    # Descending order should give the reverse result:
    query = Query(client, "Datafile",
                  order=[("name", "DESC")],
                  conditions={ "dataset.investigation.id":
                               "= %d" % investigation.id })
    print(str(query))
    assert list(reversed(client.search(query))) == res
    # We may even combine different ordering directions on multiple
    # attributes of the same query:
    query = Query(client, "Datafile",
                  order=[("dataset.name", "DESC"), ("name", "ASC")],
                  conditions={ "dataset.investigation.id":
                               "= %d" % investigation.id })
    print(str(query))
    assert sorted(client.search(query), key=lambda df: df.name) == res

def test_query_order_direction_relation(client):
    """An ordering direction qualifier on a many to one relation.

    The ordering direction qualifier has been added in Issue #48.
    """
    # As a reference to compare with, get all datasets with their
    # datafiles in their natural order:
    query = Query(client, "Dataset", order=True, includes=["datafiles"])
    dss = client.search(query)
    # Now, get all datafiles sorted by dataset in descending and name
    # in ascending order:
    query = Query(client, "Datafile", order=[("dataset", "DESC"), "name"])
    print(str(query))
    assert "Datafile" in query.select_clause
    assert "dataset" in query.join_clause
    assert query.where_clause is None
    assert "name" in query.order_clause
    dff = client.search(query)
    # verify:
    offs = 0
    for ds in reversed(dss):
        # There is no guarantee on the order of the included datafiles
        dsdfs = sorted(ds.datafiles, key=icat.entity.Entity.__sortkey__)
        l = len(dsdfs)
        assert dff[offs:offs+l] == dsdfs
        offs += l

def test_query_condition_greaterthen(client):
    """Other relations then equal may be used in the conditions too.
    """
    condition = {"datafileCreateTime": ">= '2012-01-01'"}
    query = Query(client, "Datafile", conditions=condition)
    print(str(query))
    assert "Datafile" in query.select_clause
    assert query.join_clause is None
    assert "datafileCreateTime" in query.where_clause
    res = client.search(query)
    assert len(res) == 4 + have_icat_5
    condition = {"datafileCreateTime": "< '2012-01-01'"}
    query = Query(client, "Datafile", conditions=condition)
    print(str(query))
    res = client.search(query)
    assert len(res) == 6

def test_query_condition_list(client):
    """We may also add a list of conditions on a single attribute.
    """
    condition = {"datafileCreateTime": [">= '2012-01-01'", "< '2013-01-01'"]}
    query = Query(client, "Datafile", conditions=condition)
    print(str(query))
    assert "Datafile" in query.select_clause
    assert query.join_clause is None
    assert "datafileCreateTime" in query.where_clause
    qstr = str(query)
    res = client.search(query)
    assert len(res) == 3 + have_icat_5

    # The last example also works by adding the conditions separately.
    query = Query(client, "Datafile")
    query.addConditions({"datafileCreateTime": ">= '2012-01-01'"})
    query.addConditions({"datafileCreateTime": "< '2013-01-01'"})
    print(str(query))
    assert str(query) == qstr
    res = client.search(query)
    assert len(res) == 3 + have_icat_5

@pytest.mark.dependency(depends=['get_investigation'])
def test_query_in_operator(client):
    """Using "id in (i)" rather than "id = i" also works.
    (This may be needed to work around ICAT Issue 128.)
    """
    query = Query(client, "Investigation",
                  conditions={"id": "in (%d)" % investigation.id})
    print(str(query))
    assert "Investigation" in query.select_clause
    assert query.join_clause is None
    assert "in" in query.where_clause
    res = client.search(query)
    assert len(res) == 1
    inv = res[0]
    assert inv.BeanName == "Investigation"
    assert inv.id == investigation.id
    assert inv.name == investigation.name

def test_query_condition_obj(client):
    """We may place conditions on related objects.
    This is in particular useful to test whether a relation is null.
    """
    query = Query(client, "Rule", conditions={"grouping": "IS NULL"})
    print(str(query))
    assert "Rule" in query.select_clause
    res = client.search(query)
    assert len(res) == all_rules - grp_rules

def test_query_condition_jpql_function(client):
    """Functions may be applied to field names of conditions.
    This test also applies `UPPER()` on the data to mitigate instances
    of Oracle databases which are case sensitive.
    """
    conditions = {
        "UPPER(title)": "like UPPER('%Ni-Mn-Ga flat cone%')",
        "UPPER(datasets.name)": "like UPPER('%e208341%')",
    }
    query = Query(client, "Investigation", conditions=conditions)
    print(str(query))
    assert "Investigation" in query.select_clause
    assert "datasets" in query.join_clause
    assert "UPPER" in query.where_clause
    res = client.search(query)
    assert len(res) == 1

def test_query_condition_jpql_function_namelen(client):
    """Functions may be applied to field names of conditions.
    Similar to last test, but picking another example where the effect
    of the JPQL function in the condition is easier to verify in the
    result.
    """
    conditions = { "name": "LIKE 'db/%'",
                   "LENGTH(fullName)": "> 11" }
    query = Query(client, "User", conditions=conditions)
    print(str(query))
    assert "User" in query.select_clause
    assert query.join_clause is None
    assert "LENGTH" in query.where_clause
    res = client.search(query)
    assert len(res) == 4

def test_query_condition_jpql_function_mixed(client):
    """Mix conditions with and without JPQL function on the same attribute.
    This test case failed for an early implementation of JPQL
    functions, see discussion in #89.
    """
    conditions = { "name": "LIKE 'db/%'",
                   "LENGTH(fullName)": "> 11", "fullName": "> 'C'" }
    query = Query(client, "User", conditions=conditions)
    print(str(query))
    assert "User" in query.select_clause
    assert query.join_clause is None
    assert "LENGTH" in query.where_clause
    res = client.search(query)
    assert len(res) == 3

def test_query_order_jpql_function(client):
    """Functions may be applied to attribute names in order.

    As an example, search for the User having the third longest
    fullName.  (In the example data, the longest and second longest
    fullName is somewhat ambiguous due to character encoding issues.)
    """
    query = Query(client, "User", conditions={ "name": "LIKE 'db/%'" },
                  order=[("LENGTH(fullName)", "DESC")], limit=(2,1))
    print(str(query))
    assert "User" in query.select_clause
    assert query.join_clause is None
    assert "LENGTH" in query.order_clause
    assert query.limit_clause is not None
    res = client.search(query)
    assert len(res) == 1
    assert res[0].fullName == "Nicolas Bourbaki"

def test_query_rule_order(client):
    """Rule does not have a constraint, id is included in the natural order.
    """
    query = Query(client, "Rule", order=True)
    print(str(query))
    assert "Rule" in query.select_clause
    assert query.join_clause is None
    assert query.where_clause is None
    assert "id" in query.order_clause
    res = client.search(query)
    assert len(res) == all_rules

def test_query_rule_order_group(client, recwarn):
    """Ordering rule on grouping implicitely adds a "grouping IS NOT NULL"
    condition, because it is internally implemented using an INNER
    JOIN between the tables.  The Query class emits a warning about
    this.
    """
    recwarn.clear()
    query = Query(client, "Rule", order=['grouping', 'what', 'id'])
    w = recwarn.pop(icat.QueryNullableOrderWarning)
    assert issubclass(w.category, icat.QueryNullableOrderWarning)
    assert "grouping" in str(w.message)
    print(str(query))
    assert "Rule" in query.select_clause
    assert "grouping" in query.join_clause
    assert query.where_clause is None
    assert "what" in query.order_clause
    res = client.search(query)
    assert len(res) == grp_rules

def test_query_rule_order_group_suppress_warn_cond(client, recwarn):
    """The warning can be suppressed by making the condition explicit.
    """
    recwarn.clear()
    query = Query(client, "Rule", order=['grouping', 'what', 'id'],
                  conditions={"grouping": "IS NOT NULL"})
    assert len(recwarn.list) == 0
    print(str(query))
    assert "Rule" in query.select_clause
    assert "grouping" in query.join_clause
    assert "grouping" in query.where_clause
    assert "what" in query.order_clause
    res = client.search(query)
    assert len(res) == grp_rules

def test_query_rule_order_group_suppress_warn_join(client, recwarn):
    """Another option to suppress the warning is to override the JOIN spec.
    By confirming the default INNER JOIN, we get the Rules having
    grouping NOT NULL.
    """
    recwarn.clear()
    query = Query(client, "Rule", order=['grouping', 'what', 'id'],
                  join_specs={"grouping": "INNER JOIN"})
    assert len(recwarn.list) == 0
    print(str(query))
    assert "Rule" in query.select_clause
    assert "INNER JOIN" in query.join_clause
    assert query.where_clause is None
    assert "what" in query.order_clause
    res = client.search(query)
    assert len(res) == grp_rules

def test_query_rule_order_group_left_join(client, recwarn):
    """Another option to suppress the warning is to override the JOIN spec.
    By chosing a LEFT JOIN, we get all Rules.
    """
    recwarn.clear()
    query = Query(client, "Rule", order=['grouping', 'what', 'id'],
                  join_specs={"grouping": "LEFT OUTER JOIN"})
    assert len(recwarn.list) == 0
    print(str(query))
    assert "Rule" in query.select_clause
    assert "LEFT OUTER JOIN" in query.join_clause
    assert query.where_clause is None
    assert "what" in query.order_clause
    res = client.search(query)
    assert len(res) == all_rules

def test_query_order_one_to_many(client, recwarn):
    """Sort on a related object in a one to many relation.
    This has been enabled in #84, but a warning is still emitted.
    """
    recwarn.clear()
    query = Query(client, "Investigation",
                  order=['investigationInstruments.instrument.fullName'])
    w = recwarn.pop(icat.QueryOneToManyOrderWarning)
    assert issubclass(w.category, icat.QueryOneToManyOrderWarning)
    assert "investigationInstruments" in str(w.message)
    print(str(query))
    assert "Investigation" in query.select_clause
    assert "instrument" in query.join_clause
    assert query.where_clause is None
    assert "fullName" in query.order_clause
    res = client.search(query)
    assert len(res) == 3

def test_query_order_one_to_many_warning_suppressed(client, recwarn):
    """Again, the warning can be suppressed by overriding the JOIN spec.
    """
    recwarn.clear()
    query = Query(client, "Investigation",
                  order=['investigationInstruments.instrument.fullName'],
                  join_specs={"investigationInstruments": "INNER JOIN"})
    assert len(recwarn.list) == 0
    print(str(query))
    assert "Investigation" in query.select_clause
    assert "INNER JOIN" in query.join_clause
    assert "instrument" in query.join_clause
    assert query.where_clause is None
    assert "fullName" in query.order_clause
    res = client.search(query)
    assert len(res) == 3

def test_query_order_one_to_many_duplicate(client, recwarn):
    """Note that sorting on a one to many relation may have surprising
    effects on the result list.  That is why class Query emits a
    warning.
    You may get duplicates in the result.
    """
    recwarn.clear()
    # The query without ORDER BY clause.
    query = Query(client, "Investigation")
    assert len(recwarn.list) == 0
    print(str(query))
    res = client.search(query)
    assert len(res) == 3
    reference = res
    # The same query adding a ORDER BY clause, we get two duplicates in
    # the result.
    recwarn.clear()
    query = Query(client, "Investigation", order=['investigationUsers.role'])
    w = recwarn.pop(icat.QueryOneToManyOrderWarning)
    assert issubclass(w.category, icat.QueryOneToManyOrderWarning)
    assert "investigationUsers" in str(w.message)
    print(str(query))
    res = client.search(query)
    assert len(res) > 3
    assert set(res) == set(reference)

def test_query_order_one_to_many_missing(client, recwarn):
    """Note that sorting on a one to many relation may have surprising
    effects on the result list.  That is why class Query emits a
    warning.
    You may get misses in the result.
    """
    recwarn.clear()
    # The query without ORDER BY clause.
    query = Query(client, "Sample")
    assert len(recwarn.list) == 0
    print(str(query))
    res = client.search(query)
    assert len(res) == 3
    reference = res
    # The same query adding a ORDER BY clause, one item, a sample
    # having no parameter with a string value, is missing from the result.
    recwarn.clear()
    query = Query(client, "Sample", order=['parameters.stringValue'])
    w = recwarn.pop(icat.QueryOneToManyOrderWarning)
    assert issubclass(w.category, icat.QueryOneToManyOrderWarning)
    assert "parameters" in str(w.message)
    print(str(query))
    res = client.search(query)
    assert len(res) == 2
    # We can fix it in this case using a LEFT JOIN.
    recwarn.clear()
    query = Query(client, "Sample",
                  order=['parameters.stringValue'],
                  join_specs={"parameters": "LEFT JOIN"})
    assert len(recwarn.list) == 0
    print(str(query))
    res = client.search(query)
    assert len(res) == 3
    assert set(res) == set(reference)

def test_query_order_suppress_warnings(client, recwarn):
    """Suppress all QueryWarnings.
    """
    recwarn.clear()
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", category=icat.QueryWarning)
        query = Query(client, "Investigation",
                      order=['investigationInstruments.instrument.fullName'])
    assert len(recwarn.list) == 0
    print(str(query))
    res = client.search(query)
    assert len(res) == 3

def test_query_limit(client):
    """Add a LIMIT clause to an earlier example.
    """
    query = Query(client, "Rule", order=['grouping', 'what', 'id'],
                  conditions={"grouping":"IS NOT NULL"})
    query.setLimit( (0,10) )
    print(str(query))
    assert "Rule" in query.select_clause
    assert "grouping" in query.join_clause
    assert "grouping" in query.where_clause
    assert "what" in query.order_clause
    assert query.limit_clause is not None
    res = client.search(query)
    assert len(res) == 10

def test_query_limit_placeholder(client):
    """LIMIT clauses are particular useful with placeholders.
    """
    query = Query(client, "Rule", order=['grouping', 'what', 'id'],
                  conditions={"grouping":"IS NOT NULL"})
    query.setLimit( ("%d","%d") )
    chunksize = 45
    print(str(query))
    print(str(query) % (0,chunksize))
    assert "Rule" in query.select_clause
    assert "grouping" in query.join_clause
    assert "grouping" in query.where_clause
    assert "what" in query.order_clause
    assert query.limit_clause is not None
    res = client.search(str(query) % (0,chunksize))
    assert len(res) == chunksize
    print(str(query) % (chunksize,chunksize))
    res = client.search(str(query) % (chunksize,chunksize))
    assert len(res) == grp_rules - chunksize

def test_query_non_ascii(client):
    """Test if query strings with non-ascii characters work.

    There was a bug that forced query strings to be all ascii.  The
    bug only occured with Python 2.  It was fixed in change 8d5132d.
    """
    # String literal with unicode characters that will be understood
    # by both Python 2 and Python 3.
    fullName = b'Rudolph Beck-D\xc3\xbclmen'.decode('utf8')
    query = Query(client, "User",
                  conditions={ "fullName": "= '%s'" % fullName })
    print(str(query))
    assert "User" in query.select_clause
    assert query.join_clause is None
    assert fullName in query.where_clause
    res = client.search(query)
    assert len(res) == 1

@pytest.mark.dependency(depends=['get_investigation'])
def test_query_str(client):
    """Test the __str__() operator.  It should have no side effects.

    The __str__() operator was modifying the query object under
    certain conditions (if a1.a2 was in includes but a1 not, a1 was
    added).  While this modification was most likely harmless and in
    particular did not cause any semantic change of the query, it was
    still a bug because a __str__() operator should not have any side
    effects at all.  It was fixed in changes 4688517 and 905dd8c.
    """
    query = Query(client, "Datafile", order=True,
                  conditions={ "dataset.investigation.id":
                               "= %d" % investigation.id },
                  includes={"dataset", "datafileFormat.facility",
                            "parameters.type.facility"})
    r = repr(query)
    print(str(query))
    assert "Datafile" in query.select_clause
    assert "investigation" in query.join_clause
    assert "id" in query.where_clause
    assert "datafileFormat" in query.include_clause
    assert repr(query) == r

def test_query_metaattr(client):
    """Test adding a condition on a meta attribute.  Issue #6
    """
    query = Query(client, "Datafile", conditions={ "modId": "= 'jdoe'" })
    print(str(query))
    assert "Datafile" in query.select_clause
    assert query.join_clause is None
    assert "modId" in query.where_clause
    res = client.search(query)
    assert len(res) == 0

def test_query_include_1(client):
    """Test adding an "INCLUDE 1" clause.
    """
    query = Query(client, "Investigation", includes="1")
    print(str(query))
    assert "Investigation" in query.select_clause
    assert query.join_clause is None
    assert query.where_clause is None
    assert "facility" in query.include_clause
    assert "type" in query.include_clause
    res = client.search(query)
    assert len(res) > 0
    inv = res[0]
    assert inv.BeanName == "Investigation"
    assert inv.facility.BeanName == "Facility"
    assert inv.type.BeanName == "InvestigationType"

@pytest.mark.dependency(depends=['get_investigation'])
def test_query_attribute_datafile_name(client):
    """The datafiles names related to a given investigation in natural order.

    Querying attributes rather than entire objects is a new feature
    added in Issue #28.
    """
    query = Query(client, "Datafile", attributes="name", order=True,
                  conditions={ "dataset.investigation.id":
                               "= %d" % investigation.id })
    print(str(query))
    assert "name" in query.select_clause
    assert "investigation" in query.join_clause
    assert "id" in query.where_clause
    assert query.order_clause is not None
    res = client.search(query)
    assert len(res) == 4
    for n in res:
        assert not isinstance(n, icat.entity.Entity)

@pytest.mark.dependency(depends=['get_investigation'])
def test_query_attribute_datafile_name_list(client):
    """The datafiles names related to a given investigation in natural order.

    Same as last test, but pass the attribute as a list having one
    single element.
    """
    query = Query(client, "Datafile", attributes=["name"], order=True,
                  conditions={ "dataset.investigation.id":
                               "= %d" % investigation.id })
    print(str(query))
    assert "name" in query.select_clause
    assert "investigation" in query.join_clause
    assert "id" in query.where_clause
    assert query.order_clause is not None
    res = client.search(query)
    assert len(res) == 4
    for n in res:
        assert not isinstance(n, icat.entity.Entity)

@pytest.mark.dependency(depends=['get_investigation'])
def test_query_related_obj_attribute(client):
    """We may query attributes of related objects in the SELECT clause.

    This requires icat.server 4.5 or newer to work.
    """
    require_icat_version("4.5.0", "SELECT related object's attribute")
    query = Query(client, "Datafile", attributes="datafileFormat.name",
                  conditions={ "dataset.investigation.id":
                               "= %d" % investigation.id })
    print(str(query))
    assert "name" in query.select_clause
    assert "datafileFormat" in query.join_clause
    assert "investigation" in query.join_clause
    assert "id" in query.where_clause
    res = client.search(query)
    assert len(res) == 4
    for n in res:
        assert n in ['other', 'NeXus']

def test_query_mulitple_attributes(client):
    """Query multiple attributes in the SELECT clause.
    """
    if not client._has_wsdl_type('fieldSet'):
        pytest.skip("search for multiple fields not supported by this server")

    results = [("08100122-EF", "Durol single crystal",
                datetime.datetime(2008, 3, 13, 10, 39, 42, tzinfo=tzinfo)),
               ("10100601-ST", "Ni-Mn-Ga flat cone",
                datetime.datetime(2010, 9, 30, 10, 27, 24, tzinfo=tzinfo)),
               ("12100409-ST", "NiO SC OF1 JUH HHL",
                datetime.datetime(2012, 7, 26, 15, 44, 24, tzinfo=tzinfo))]
    query = Query(client, "Investigation",
                  attributes=("name", "title", "startDate"), order=True)
    print(str(query))
    assert "name" in query.select_clause
    assert "title" in query.select_clause
    assert "startDate" in query.select_clause
    assert "facility" in query.join_clause
    assert query.order_clause is not None
    res = client.search(query)
    assert res == results

def test_query_mulitple_attributes_related_obj(client):
    """Query multiple attributes including attributes of related objects.
    """
    if not client._has_wsdl_type('fieldSet'):
        pytest.skip("search for multiple fields not supported by this server")

    results = [("08100122-EF", "e201215"),
               ("08100122-EF", "e201216"),
               ("10100601-ST", "e208339"),
               ("10100601-ST", "e208341"),
               ("10100601-ST", "e208342")]
    query = Query(client, "Dataset",
                  attributes=("investigation.name", "name"), order=True,
                  conditions={"investigation.startDate":  "< '2011-01-01'"})
    print(str(query))
    assert "name" in query.select_clause
    assert "investigation" in query.join_clause
    assert "startDate" in query.where_clause
    assert query.order_clause is not None
    res = client.search(query)
    assert res == results

def test_query_mulitple_attributes_oldicat_valueerror(client):
    """Query class should raise ValueError if multiple attributes are
    requested, but the ICAT server is too old to support this.
    """
    if client._has_wsdl_type('fieldSet'):
        pytest.skip("search for multiple fields is supported by this server")

    with pytest.raises(ValueError) as err:
        query = Query(client, "Investigation", attributes=("name", "title"))
    err_pattern = r"\bICAT server\b.*\bnot support\b.*\bmultiple attributes\b"
    assert re.search(err_pattern, str(err.value))

def test_query_mulitple_attributes_distinct(client):
    """Combine DISTINCT with a query for multiple attributes.

    This requires a special handling due to some quirks in the
    icat.server query parser.  Support for this has been added in
    #81.
    """
    if not client._has_wsdl_type('fieldSet'):
        pytest.skip("search for multiple fields not supported by this server")

    # Try the query without DISTINCT first so that we can verify the effect.
    query = Query(client, "InvestigationUser",
                  attributes=("investigation.name", "role"),
                  conditions={"investigation.name": "= '08100122-EF'"})
    print(str(query))
    res = client.search(query)
    query = Query(client, "InvestigationUser",
                  attributes=("investigation.name", "role"),
                  conditions={"investigation.name": "= '08100122-EF'"},
                  aggregate="DISTINCT")
    print(str(query))
    assert "DISTINCT" in query.select_clause
    assert "role" in query.select_clause
    assert "investigation" in query.join_clause
    assert "name" in query.where_clause
    res_dist = client.search(query)
    # The search with DISTINCT yields less items, but if we eliminate
    # duplicates, the result set is the same:
    assert len(res) > len(res_dist)
    assert set(res) == set(res_dist)

@pytest.mark.dependency(depends=['get_investigation'])
def test_query_aggregate_distinct_attribute(client):
    """Test DISTINCT on an attribute in the search result.

    Support for adding aggregate functions has been added in
    Issue #32.
    """
    require_icat_version("4.7.0", "SELECT DISTINCT in queries")
    query = Query(client, "Datafile",
                  attributes="datafileFormat.name",
                  conditions={ "dataset.investigation.id":
                               "= %d" % investigation.id })
    print(str(query))
    res = client.search(query)
    assert sorted(res) == ["NeXus", "NeXus", "other", "other"]
    query.setAggregate("DISTINCT")
    print(str(query))
    assert "DISTINCT" in query.select_clause
    assert "name" in query.select_clause
    assert "datafileFormat" in query.join_clause
    assert "id" in query.where_clause
    res = client.search(query)
    assert sorted(res) == ["NeXus", "other"]

@pytest.mark.dependency(depends=['get_investigation'])
def test_query_aggregate_distinct_related_obj(client):
    """Test DISTINCT on a related object in the search result.

    Support for adding aggregate functions has been added in
    Issue #32.
    """
    require_icat_version("4.7.0", "SELECT DISTINCT in queries")
    query = Query(client, "Datafile",
                  attributes="datafileFormat",
                  conditions={ "dataset.investigation.id":
                               "= %d" % investigation.id })
    print(str(query))
    res = client.search(query)
    assert len(res) == 4
    for n in res:
        assert isinstance(n, icat.entity.Entity)
    query.setAggregate("DISTINCT")
    print(str(query))
    assert "DISTINCT" in query.select_clause
    assert "datafileFormat" in query.select_clause
    assert "investigation" in query.join_clause
    assert "id" in query.where_clause
    res = client.search(query)
    assert len(res) == 2
    for n in res:
        assert isinstance(n, icat.entity.Entity)

@pytest.mark.dependency(depends=['get_investigation'])
@pytest.mark.parametrize(("attribute", "aggregate", "expected"), [
    (None, "COUNT", 4),
    (None, "COUNT:DISTINCT", 4),
    ("datafileFormat", "COUNT", 4),
    ("datafileFormat", "COUNT:DISTINCT", 2),
    ("datafileFormat.name", "COUNT", 4),
    ("datafileFormat.name", "COUNT:DISTINCT", 2),
    ("fileSize", "MAX", 73428),
    ("fileSize", "MIN", 394),
    ("fileSize", "SUM", 127125),
    # Note that the number of datafiles is four which is a power of
    # two.  Therefore we may assume the float representation of an
    # average of integers is exact, so we may even dare to compare the
    # float value for equality.
    ("fileSize", "AVG", 31781.25),
    ("name", "MAX", "e208341.nxs"),
    ("name", "MIN", "e208339.dat"),
    pytest.param("datafileCreateTime", "MIN",
                 datetime.datetime(2010, 10, 1, 6, 17, 48, tzinfo=tzinfo),
                 marks=pytest.mark.skipif("tzinfo is None")),
    pytest.param("datafileCreateTime", "MAX",
                 datetime.datetime(2010, 10, 5, 9, 31, 53, tzinfo=tzinfo),
                 marks=pytest.mark.skipif("tzinfo is None"))
])
def test_query_aggregate_misc(client, attribute, aggregate, expected):
    """Try some working aggregate results for the datafiles.

    Support for adding aggregate functions has been added in
    Issue #32.
    """
    if attribute is not None and "." in attribute:
        require_icat_version("4.5.0", "SELECT related object's attribute")
    if "DISTINCT" in aggregate:
        require_icat_version("4.7.0", "SELECT DISTINCT in queries")
    query = Query(client, "Datafile",
                  attributes=attribute, aggregate=aggregate,
                  conditions={ "dataset.investigation.id":
                               "= %d" % investigation.id })
    print(str(query))
    if ':' not in aggregate:
        assert aggregate in query.select_clause
    if attribute is not None and '.' not in attribute:
        assert attribute in query.select_clause
    assert "investigation" in query.join_clause
    assert "id" in query.where_clause
    res = client.search(query)
    assert len(res) == 1
    assert res[0] == expected

@pytest.mark.parametrize(("entity", "kwargs"), [
    ("Datafile", dict(attributes="name", order=True)),
    ("InvestigationUser",
     dict(attributes=("investigation.name", "role"),
          conditions={"investigation.name": "= '08100122-EF'"},
          aggregate="DISTINCT")),
    ("Datafile", dict(order=[("name", "ASC")])),
    ("Datafile", dict(conditions={
        "name": "= 'e208945.nxs'",
        "dataset.name": "= 'e208945'",
        "dataset.investigation.name": "= '12100409-ST'",
    })),
    ("Instrument", dict(order=["name"],
                        includes={"facility", "instrumentScientists.user"})),
    ("Rule", dict(order=['grouping', 'what', 'id'],
                  conditions={"grouping":"IS NOT NULL"},
                  limit=(0,10))),
    ("Rule", dict(order=['grouping', 'what', 'id'],
                  join_specs={"grouping": "LEFT OUTER JOIN"})),
])
def test_query_copy(client, entity, kwargs):
    """Test the Query.copy() method.

    Very basic test: verify that Query.copy() yields an equivalent
    query for various Query() constructor argument sets.
    """
    if ('attributes' in kwargs and len(kwargs['attributes']) > 1 and
        not client._has_wsdl_type('fieldSet')):
        pytest.skip("search for multiple fields not supported by this server")
    query = Query(client, entity, **kwargs)
    clone = query.copy()
    assert str(clone) == str(query)
    assert entity in clone.select_clause


text:
<?php
/**
 * @author Tomáš Blatný
 */

namespace Tempeus\GameModule;

use Nette\Utils\Paginator;
use Tempeus\Model\ArticleRepository;
use Tempeus\Model\CategoryRepository;

class ArticlePresenter extends BaseGamePresenter
{
	/** @var ArticleRepository @inject */
	public $articleRepository;

	/** @var CategoryRepository @inject */
	public $categoryRepository;

	public function renderDefault($page = 1)
	{
		$paginator = new Paginator();
		$paginator->itemCount = $this->articleRepository->countByGame($this->game);
		$paginator->itemsPerPage = 5;
		$paginator->page = $page;
		if($paginator->page !== $page) {
			$this->redirect('this', array('page' => $paginator->page));
		}
		$this->template->paginator = $paginator;
		$this->template->articles = $this->articleRepository->findByGameOrderedByPage($this->game, $paginator, '[published] DESC');
	}

	public function actionDetail($id)
	{
		if(!$this->template->article = $this->articleRepository->findBySlug($id)) {
			$this->flashError('Článek již neexistuje.');
			$this->redirect('default');
		}
	}

	public function actionCategory($id)
	{
		if(!$this->template->category = $category = $this->categoryRepository->findBySlug($id)) {
			$this->flashError('Kategorie již neexistuje.');
			$this->redirect('default');
		}
		$this->template->articles = $this->articleRepository->findByCategory($category, $this->game);
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8" ?>
<doctrine-mapping
    xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:gedmo="http://gediminasm.org/schemas/orm/doctrine-extensions-mapping"
    xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
                        http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

    <entity name="Ekyna\Bundle\MediaBundle\Entity\Media"
            table="media_media"
            repository-class="Ekyna\Bundle\MediaBundle\Entity\MediaRepository">

        <entity-listeners>
            <entity-listener class="Ekyna\Bundle\MediaBundle\Listener\MediaListener" />
        </entity-listeners>

        <id name="id" column="id" type="integer">
            <generator strategy="AUTO" />
        </id>

        <field name="type" type="string" column="type" length="8" />
        <field name="path" type="string" column="path" length="255" />
        <field name="size" type="integer" column="size" />
        <field name="createdAt" column="created_at" type="datetime">
            <gedmo:timestampable on="create" />
        </field>
        <field name="updatedAt" column="updated_at" type="datetime" nullable="true">
            <gedmo:timestampable on="update" />
        </field>

        <many-to-one target-entity="Ekyna\Bundle\MediaBundle\Entity\Folder" field="folder" inversed-by="medias">
            <join-column name="folder_id" referenced-column-name="id" on-delete="RESTRICT" nullable="false" />
        </many-to-one>

    </entity>

</doctrine-mapping>


text:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <com.liangfeizc.CircleView
        android:id="@+id/outer_circle"
        android:layout_width="85dp"
        android:layout_height="85dp"
        android:layout_centerVertical="true"
        app:cv_color="@color/outerCircleColor" />

    <View
        android:id="@+id/container_wrapper"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignEnd="@+id/container"
        android:layout_alignLeft="@+id/container"
        android:layout_alignRight="@+id/container"
        android:layout_alignStart="@+id/container"
        android:layout_gravity="center"
        android:layout_marginBottom="20dp"
        android:layout_marginTop="20dp"
        android:background="@drawable/indicator_background" />

    <LinearLayout
        android:id="@id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:gravity="center"
        android:orientation="horizontal" />
</merge>


text:
/*! \file ored/configuration/conventions.hpp
    \brief Currency and instrument specific conventions/defaults
    \ingroup marketdata
*/

#pragma once

#include <ql/indexes/swapindex.hpp>
#include <ql/indexes/iborindex.hpp>
#include <ql/indexes/inflationindex.hpp>
#include <qle/cashflows/subperiodscoupon.hpp> // SubPeriodsCouponType
#include <ored/utilities/xmlutils.hpp>

using std::string;
using std::map;
using ore::data::XMLSerializable;
using ore::data::XMLDocument;
using ore::data::XMLNode;

namespace ore {
namespace data {

//! Abstract base class for convention objects
/*!
  \ingroup marketdata
 */
class Convention : public XMLSerializable {
public:
    //! Supported convention types
    enum class Type {
        Zero,
        Deposit,
        Future,
        FRA,
        OIS,
        Swap,
        AverageOIS,
        TenorBasisSwap,
        TenorBasisTwoSwap,
        FX,
        CrossCcyBasis,
        CDS,
        SwapIndex,
        InflationSwap,
        SecuritySpread
    };

    //! Default destructor
    virtual ~Convention() {}

    //! \name Inspectors
    //@{
    const string& id() const { return id_; }
    Type type() const { return type_; }
    //@}

    //! \name Serialisation
    //@{
    virtual void fromXML(XMLNode* node) = 0;
    virtual XMLNode* toXML(XMLDocument& doc) = 0;
    virtual void build() = 0;
    //@}

protected:
    Convention() {}
    Convention(const string& id, Type type);
    Type type_;
    string id_;
};

//! Container for storing Zero Rate conventions
/*!
  \ingroup marketdata
 */
class ZeroRateConvention : public Convention {
public:
    //! \name Constructors
    //@{
    //! Default constructor
    ZeroRateConvention() {}
    ZeroRateConvention(const string& id, const string& dayCounter, const string& compounding,
                       const string& compoundingFrequency);
    ZeroRateConvention(const string& id, const string& dayCounter, const string& tenorCalendar,
                       const string& compounding = "Continuous", const string& compoundingFrequency = "Annual",
                       const string& spotLag = "", const string& spotCalendar = "", const string& rollConvention = "",
                       const string& eom = "");
    //@}

    //! \name Inspectors
    //@{
    //! Zero rate day counter
    const DayCounter& dayCounter() const { return dayCounter_; }
    //! Return the calendar used for converting tenor points into dates
    const Calendar& tenorCalendar() const { return tenorCalendar_; }
    //! Zero rate compounding
    Compounding compounding() const { return compounding_; }
    //! Zero rate compounding frequency
    Frequency compoundingFrequency() const { return compoundingFrequency_; }
    //! Zero rate spot lag
    Natural spotLag() const { return spotLag_; }
    //! Calendar used for spot date adjustment
    const Calendar& spotCalendar() const { return spotCalendar_; }
    //! Business day convention used in converting tenor points into dates
    BusinessDayConvention rollConvention() const { return rollConvention_; }
    //! End of month adjustment
    bool eom() { return eom_; }
    //! Flag to indicate whether the Zero Rate convention is based on a tenor input
    bool tenorBased() { return tenorBased_; }
    //@}

    //! \name Serialisation
    //@{
    virtual void fromXML(XMLNode* node);
    virtual XMLNode* toXML(XMLDocument& doc);
    virtual void build();
    //@}

private:
    DayCounter dayCounter_;
    Calendar tenorCalendar_;
    Compounding compounding_;
    Frequency compoundingFrequency_;
    Natural spotLag_;
    Calendar spotCalendar_;
    BusinessDayConvention rollConvention_;
    bool eom_;
    bool tenorBased_;

    // Strings to store the inputs
    string strDayCounter_;
    string strTenorCalendar_;
    string strCompounding_;
    string strCompoundingFrequency_;
    string strSpotLag_;
    string strSpotCalendar_;
    string strRollConvention_;
    string strEom_;
};

//! Container for storing Deposit conventions
/*!
  \ingroup marketdata
 */
class DepositConvention : public Convention {
public:
    //! \name Constructors
    //@{
    //! Default constructor
    DepositConvention() {}
    //! Index based constructor
    DepositConvention(const string& id, const string& index);
    //! Detailed constructor
    DepositConvention(const string& id, const string& calendar, const string& convention, const string& eom,
                      const string& dayCounter);
    //@}

    //! \name Inspectors
    //@{
    const string& index() const { return index_; }
    const Calendar& calendar() const { return calendar_; }
    BusinessDayConvention convention() const { return convention_; }
    bool eom() { return eom_; }
    const DayCounter& dayCounter() const { return dayCounter_; }
    bool indexBased() { return indexBased_; }
    // @}

    //! \name Serialisation
    //@{
    virtual void fromXML(XMLNode* node);
    virtual XMLNode* toXML(XMLDocument& doc);
    virtual void build();
    //@}

private:
    string index_;
    Calendar calendar_;
    BusinessDayConvention convention_;
    bool eom_;
    DayCounter dayCounter_;
    bool indexBased_;

    // Strings to store the inputs
    string strCalendar_;
    string strConvention_;
    string strEom_;
    string strDayCounter_;
};

//! Container for storing Money Market Futures conventions
/*!
  \ingroup marketdata
 */
class FutureConvention : public Convention {
public:
    //! \name Constructors
    //@{
    //! Default constructor
    FutureConvention() {}
    //! Index based constructor
    FutureConvention(const string& id, const string& index);
    //@}
    //! \name Inspectors
    //@{
    const boost::shared_ptr<IborIndex>& index() const { return index_; }
    //@}

    //! Serialisation
    //@{
    virtual void fromXML(XMLNode* node);
    virtual XMLNode* toXML(XMLDocument& doc);
    virtual void build() {}
    //@}

private:
    string strIndex_;
    boost::shared_ptr<IborIndex> index_;
};

//! Container for storing Forward rate Agreement conventions
/*!
  \ingroup marketdata
 */
class FraConvention : public Convention {
public:
    //! \name Constructors
    //@{
    //! Default constructor
    FraConvention() {}
    //! Index based constructor
    FraConvention(const string& id, const string& index);
    //@}

    //! \name Inspectors
    //@{
    const boost::shared_ptr<IborIndex>& index() const { return index_; }
    const string& indexName() const { return strIndex_; }
    //@}

    //! \name Serialisation
    //@{
    virtual void fromXML(XMLNode* node);
    virtual XMLNode* toXML(XMLDocument& doc);
    virtual void build() {}
    //@}

private:
    string strIndex_;
    boost::shared_ptr<IborIndex> index_;
};

//! Container for storing Overnight Index Swap conventions
/*!
  \ingroup marketdata
 */
class OisConvention : public Convention {
public:
    //! \name Constructors
    //@{
    //! Default constructor
    OisConvention() {}
    //! Detailed constructor
    OisConvention(const string& id, const string& spotLag, const string& index, const string& fixedDayCounter,
                  const string& paymentLag = "", const string& eom = "", const string& fixedFrequency = "",
                  const string& fixedConvention = "", const string& fixedPaymentConvention = "",
                  const string& rule = "");
    //@}

    //! \name Inspectors
    //@{
    Natural spotLag() const { return spotLag_; }
    const string& indexName() const { return strIndex_; }
    const boost::shared_ptr<OvernightIndex>& index() const { return index_; }
    const DayCounter& fixedDayCounter() const { return fixedDayCounter_; }
    Natural paymentLag() const { return paymentLag_; }
    bool eom() { return eom_; }
    Frequency fixedFrequency() const { return fixedFrequency_; }
    BusinessDayConvention fixedConvention() const { return fixedConvention_; }
    BusinessDayConvention fixedPaymentConvention() const { return fixedPaymentConvention_; }
    DateGeneration::Rule rule() const { return rule_; }
    //@}

    //! \name Serialisation
    //@{
    virtual void fromXML(XMLNode* node);
    virtual XMLNode* toXML(XMLDocument& doc);
    virtual void build();
    //@}

private:
    Natural spotLag_;
    boost::shared_ptr<OvernightIndex> index_;
    DayCounter fixedDayCounter_;
    Natural paymentLag_;
    bool eom_;
    Frequency fixedFrequency_;
    BusinessDayConvention fixedConvention_;
    BusinessDayConvention fixedPaymentConvention_;
    DateGeneration::Rule rule_;

    // Strings to store the inputs
    string strSpotLag_;
    string strIndex_;
    string strFixedDayCounter_;
    string strPaymentLag_;
    string strEom_;
    string strFixedFrequency_;
    string strFixedConvention_;
    string strFixedPaymentConvention_;
    string strRule_;
};

//! Container for storing Swap Index conventions
/*!
  \ingroup marketdata
 */
class SwapIndexConvention : public Convention {
public:
    SwapIndexConvention() {}
    SwapIndexConvention(const string& id, const string& conventions);

    const string& conventions() const { return strConventions_; }

    virtual void fromXML(XMLNode* node);
    virtual XMLNode* toXML(XMLDocument& doc);
    virtual void build(){};

private:
    string strConventions_;
};

//! Container for storing Interest Rate Swap conventions
/*!
  \ingroup marketdata
 */
class IRSwapConvention : public Convention {
public:
    //! \name Constructors
    //@{
    //! Default constructor
    IRSwapConvention() {}
    //! Detailed constructor
    IRSwapConvention(const string& id, const string& fixedCalendar, const string& fixedFrequency,
                     const string& fixedConvention, const string& fixedDayCounter, const string& index,
                     bool hasSubPeriod = false, const string& floatFrequency = "",
                     const string& subPeriodsCouponType = "");
    //@}

    //! \name Inspectors
    //@{
    const Calendar& fixedCalendar() const { return fixedCalendar_; }
    Frequency fixedFrequency() const { return fixedFrequency_; }
    BusinessDayConvention fixedConvention() const { return fixedConvention_; }
    const DayCounter& fixedDayCounter() const { return fixedDayCounter_; }
    const string& indexName() const { return strIndex_; }
    const boost::shared_ptr<IborIndex>& index() const { return index_; }
    // For sub period
    bool hasSubPeriod() const { return hasSubPeriod_; }
    Frequency floatFrequency() const { return floatFrequency_; } // returns NoFrequency for normal swaps
    QuantExt::SubPeriodsCoupon::Type subPeriodsCouponType() const { return subPeriodsCouponType_; }
    //@}

    //! \name Serialisation
    //@{
    virtual void fromXML(XMLNode* node);
    virtual XMLNode* toXML(XMLDocument& doc);
    virtual void build();
    //@}

private:
    Calendar fixedCalendar_;
    Frequency fixedFrequency_;
    BusinessDayConvention fixedConvention_;
    DayCounter fixedDayCounter_;
    boost::shared_ptr<IborIndex> index_;
    bool hasSubPeriod_;
    Frequency floatFrequency_;
    QuantExt::SubPeriodsCoupon::Type subPeriodsCouponType_;

    // Strings to store the inputs
    string strFixedCalendar_;
    string strFixedFrequency_;
    string strFixedConvention_;
    string strFixedDayCounter_;
    string strIndex_;
    string strFloatFrequency_;
    string strSubPeriodsCouponType_;
};

//! Container for storing Average OIS conventions
/*!
  \ingroup marketdata
 */
class AverageOisConvention : public Convention {
public:
    //! \name Constructors
    //@{
    //! Default constructor
    AverageOisConvention() {}
    //! Detailed constructor
    AverageOisConvention(const string& id, const string& spotLag, const string& fixedTenor,
                         const string& fixedDayCounter, const string& fixedCalendar, const string& fixedConvention,
                         const string& fixedPaymentConvention, const string& index, const string& onTenor,
                         const string& rateCutoff);
    //@}

    //! \name Inspectors
    //@{
    Natural spotLag() const { return spotLag_; }
    const Period& fixedTenor() const { return fixedTenor_; }
    const DayCounter& fixedDayCounter() const { return fixedDayCounter_; }
    const Calendar& fixedCalendar() const { return fixedCalendar_; }
    BusinessDayConvention fixedConvention() const { return fixedConvention_; }
    BusinessDayConvention fixedPaymentConvention() const { return fixedPaymentConvention_; }
    const string& indexName() const { return strIndex_; }
    const boost::shared_ptr<OvernightIndex>& index() const { return index_; }
    const Period& onTenor() const { return onTenor_; }
    Natural rateCutoff() const { return rateCutoff_; }
    //@}

    //! \name Serialisation
    //@{
    virtual void fromXML(XMLNode* node);
    virtual XMLNode* toXML(XMLDocument& doc);
    virtual void build();
    //@}
private:
    Natural spotLag_;
    Period fixedTenor_;
    DayCounter fixedDayCounter_;
    Calendar fixedCalendar_;
    BusinessDayConvention fixedConvention_;
    BusinessDayConvention fixedPaymentConvention_;
    boost::shared_ptr<OvernightIndex> index_;
    Period onTenor_;
    Natural rateCutoff_;

    // Strings to store the inputs
    string strSpotLag_;
    string strFixedTenor_;
    string strFixedDayCounter_;
    string strFixedCalendar_;
    string strFixedConvention_;
    string strFixedPaymentConvention_;
    string strIndex_;
    string strOnTenor_;
    string strRateCutoff_;
};

//! Container for storing Tenor Basis Swap conventions
/*!
  \ingroup marketdata
 */
class TenorBasisSwapConvention : public Convention {
public:
    //! \name Constructors
    //@{
    //! Default constructor
    TenorBasisSwapConvention() {}
    //! Detailed constructor
    TenorBasisSwapConvention(const string& id, const string& longIndex, const string& shortIndex,
                             const string& shortPayTenor = "", const string& spreadOnShort = "",
                             const string& includeSpread = "", const string& subPeriodsCouponType = "");
    //@}

    //! \name Inspectors
    //@{
    const boost::shared_ptr<IborIndex>& longIndex() const { return longIndex_; }
    const boost::shared_ptr<IborIndex>& shortIndex() const { return shortIndex_; }
    const Period& shortPayTenor() const { return shortPayTenor_; }
    bool spreadOnShort() const { return spreadOnShort_; }
    bool includeSpread() const { return includeSpread_; }
    QuantExt::SubPeriodsCoupon::Type subPeriodsCouponType() const { return subPeriodsCouponType_; }
    //@}

    //! \name Serialisation
    //@{
    virtual void fromXML(XMLNode* node);
    virtual XMLNode* toXML(XMLDocument& doc);
    virtual void build();
    //@}

private:
    boost::shared_ptr<IborIndex> longIndex_;
    boost::shared_ptr<IborIndex> shortIndex_;
    Period shortPayTenor_;
    bool spreadOnShort_;
    bool includeSpread_;
    QuantExt::SubPeriodsCoupon::Type subPeriodsCouponType_;

    // Strings to store the inputs
    string strLongIndex_;
    string strShortIndex_;
    string strShortPayTenor_;
    string strSpreadOnShort_;
    string strIncludeSpread_;
    string strSubPeriodsCouponType_;
};

//! Container for storing conventions for Tenor Basis Swaps quoted as a spread of two interest rate swaps
/*!
  \ingroup marketdata
 */
class TenorBasisTwoSwapConvention : public Convention {
public:
    //! \name Constructors
    //@{
    //! Default constructor
    TenorBasisTwoSwapConvention() {}
    //! Detailed constructor
    TenorBasisTwoSwapConvention(const string& id, const string& calendar, const string& longFixedFrequency,
                                const string& longFixedConvention, const string& longFixedDayCounter,
                                const string& longIndex, const string& shortFixedFrequency,
                                const string& shortFixedConvention, const string& shortFixedDayCounter,
                                const string& shortIndex, const string& longMinusShort = "");
    //@}

    //! \name Inspectors
    //@{
    const Calendar& calendar() const { return calendar_; }
    Frequency longFixedFrequency() const { return longFixedFrequency_; }
    BusinessDayConvention longFixedConvention() const { return longFixedConvention_; }
    const DayCounter& longFixedDayCounter() const { return longFixedDayCounter_; }
    const boost::shared_ptr<IborIndex>& longIndex() const { return longIndex_; }
    Frequency shortFixedFrequency() const { return shortFixedFrequency_; }
    BusinessDayConvention shortFixedConvention() const { return shortFixedConvention_; }
    const DayCounter& shortFixedDayCounter() const { return shortFixedDayCounter_; }
    const boost::shared_ptr<IborIndex>& shortIndex() const { return shortIndex_; }
    bool longMinusShort() const { return longMinusShort_; }
    //@}

    //! \name Serialisation
    //@{
    virtual void fromXML(XMLNode* node);
    virtual XMLNode* toXML(XMLDocument& doc);
    virtual void build();
    //@}

private:
    Calendar calendar_;
    Frequency longFixedFrequency_;
    BusinessDayConvention longFixedConvention_;
    DayCounter longFixedDayCounter_;
    boost::shared_ptr<IborIndex> longIndex_;
    Frequency shortFixedFrequency_;
    BusinessDayConvention shortFixedConvention_;
    DayCounter shortFixedDayCounter_;
    boost::shared_ptr<IborIndex> shortIndex_;
    bool longMinusShort_;

    // Strings to store the inputs
    string strCalendar_;
    string strLongFixedFrequency_;
    string strLongFixedConvention_;
    string strLongFixedDayCounter_;
    string strLongIndex_;
    string strShortFixedFrequency_;
    string strShortFixedConvention_;
    string strShortFixedDayCounter_;
    string strShortIndex_;
    string strLongMinusShort_;
};

//! Container for storing FX Spot quote conventions
/*!
  \ingroup marketdata
 */
class FXConvention : public Convention {
public:
    //! \name Constructors
    //@{
    //! Default constructor
    FXConvention() {}
    //! Detailed constructor
    FXConvention(const string& id, const string& spotDays, const string& sourceCurrency, const string& targetCurrency,
                 const string& pointsFactor, const string& advanceCalendar = "", const string& spotRelative = "");
    //@}

    //! \name Inspectors
    //@{
    Natural spotDays() const { return spotDays_; }
    const Currency& sourceCurrency() const { return sourceCurrency_; }
    const Currency& targetCurrency() const { return targetCurrency_; }
    Real pointsFactor() const { return pointsFactor_; }
    const Calendar& advanceCalendar() const { return advanceCalendar_; }
    bool spotRelative() const { return spotRelative_; }
    //@}

    //! \name Serialisation
    //
    virtual void fromXML(XMLNode* node);
    virtual XMLNode* toXML(XMLDocument& doc);
    virtual void build();
    //@}

private:
    Natural spotDays_;
    Currency sourceCurrency_;
    Currency targetCurrency_;
    Real pointsFactor_;
    Calendar advanceCalendar_;
    bool spotRelative_;

    // Strings to store the inputs
    string strSpotDays_;
    string strSourceCurrency_;
    string strTargetCurrency_;
    string strPointsFactor_;
    string strAdvanceCalendar_;
    string strSpotRelative_;
};

//! Container for storing Cross Currency Basis Swap quote conventions
/*!
  \ingroup marketdata
 */
class CrossCcyBasisSwapConvention : public Convention {
public:
    //! \name Constructors
    //@{
    //! Default constructor
    CrossCcyBasisSwapConvention() {}
    //! Detailed constructor
    CrossCcyBasisSwapConvention(const string& id, const string& strSettlementDays, const string& strSettlementCalendar,
                                const string& strRollConvention, const string& flatIndex, const string& spreadIndex,
                                const string& strEom = "");
    //@}

    //! \name Inspectors
    //@{
    Natural settlementDays() const { return settlementDays_; }
    const Calendar& settlementCalendar() const { return settlementCalendar_; }
    BusinessDayConvention rollConvention() const { return rollConvention_; }
    const boost::shared_ptr<IborIndex>& flatIndex() const { return flatIndex_; }
    const boost::shared_ptr<IborIndex>& spreadIndex() const { return spreadIndex_; }
    const string& flatIndexName() const { return strFlatIndex_; }
    const string& spreadIndexName() const { return strSpreadIndex_; }

    bool eom() const { return eom_; }
    //@}

    //! \name Serialisation
    //@{
    virtual void fromXML(XMLNode* node);
    virtual XMLNode* toXML(XMLDocument& doc);
    virtual void build();
    //@}
private:
    Natural settlementDays_;
    Calendar settlementCalendar_;
    BusinessDayConvention rollConvention_;
    boost::shared_ptr<IborIndex> flatIndex_;
    boost::shared_ptr<IborIndex> spreadIndex_;
    bool eom_;

    // Strings to store the inputs
    string strSettlementDays_;
    string strSettlementCalendar_;
    string strRollConvention_;
    string strFlatIndex_;
    string strSpreadIndex_;
    string strEom_;
};

//! Container for storing Credit Default Swap quote conventions
/*!
  \ingroup marketdata
 */
class CdsConvention : public Convention {
public:
    //! \name Constructors
    //@{
    //! Default constructor
    CdsConvention() {}
    //! Detailed constructor
    CdsConvention(const string& id, const string& strSettlementDays, const string& strCalendar,
                  const string& strFrequency, const string& strPaymentConvention, const string& strRule,
                  const string& dayCounter, const string& settlesAccrual, const string& paysAtDefaultTime);
    //@}

    //! \name Inspectors
    //@{
    Natural settlementDays() const { return settlementDays_; }
    const Calendar& calendar() const { return calendar_; }
    Frequency frequency() const { return frequency_; }
    BusinessDayConvention paymentConvention() const { return paymentConvention_; }
    DateGeneration::Rule rule() const { return rule_; }
    const DayCounter& dayCounter() const { return dayCounter_; }
    bool settlesAccrual() const { return settlesAccrual_; }
    bool paysAtDefaultTime() const { return paysAtDefaultTime_; }
    //@}

    //! \name Serialisation
    //@{
    virtual void fromXML(XMLNode* node);
    virtual XMLNode* toXML(XMLDocument& doc);
    virtual void build();
    //@}
private:
    Natural settlementDays_;
    Calendar calendar_;
    Frequency frequency_;
    BusinessDayConvention paymentConvention_;
    DateGeneration::Rule rule_;
    DayCounter dayCounter_;
    bool settlesAccrual_;
    bool paysAtDefaultTime_;

    // Strings to store the inputs
    string strSettlementDays_;
    string strCalendar_;
    string strFrequency_;
    string strPaymentConvention_;
    string strRule_;
    string strDayCounter_;
    string strSettlesAccrual_;
    string strPaysAtDefaultTime_;
};

class InflationSwapConvention : public Convention {
public:
    InflationSwapConvention() {}
    InflationSwapConvention(const string& id, const string& strFixCalendar, const string& strFixConvention,
                            const string& strDayCounter, const string& strIndex, const string& strInterpolated,
                            const string& strObservationLag, const string& strAdjustInfObsDates,
                            const string& strInfCalendar, const string& strInfConvention);

    const Calendar& fixCalendar() const { return fixCalendar_; }
    BusinessDayConvention fixConvention() const { return fixConvention_; }
    const DayCounter& dayCounter() const { return dayCounter_; }
    const boost::shared_ptr<ZeroInflationIndex> index() const { return index_; }
    bool interpolated() const { return interpolated_; }
    Period observationLag() const { return observationLag_; }
    bool adjustInfObsDates() const { return adjustInfObsDates_; }
    const Calendar& infCalendar() const { return infCalendar_; }
    BusinessDayConvention infConvention() const { return infConvention_; }

    virtual void fromXML(XMLNode* node);
    virtual XMLNode* toXML(XMLDocument& doc);
    virtual void build();

private:
    Calendar fixCalendar_;
    BusinessDayConvention fixConvention_;
    DayCounter dayCounter_;
    boost::shared_ptr<ZeroInflationIndex> index_;
    bool interpolated_;
    Period observationLag_;
    bool adjustInfObsDates_;
    Calendar infCalendar_;
    BusinessDayConvention infConvention_;

    // Strings to store the inputs
    string strFixCalendar_;
    string strFixConvention_;
    string strDayCounter_;
    string strIndex_;
    string strInterpolated_;
    string strObservationLag_;
    string strAdjustInfObsDates_;
    string strInfCalendar_;
    string strInfConvention_;
};

//! Repository for currency dependent market conventions
/*!
  \ingroup market
*/
class Conventions : public XMLSerializable {
public:
    //! Default constructor
    Conventions() {}

    /*! Returns the convention if found and throws if not */
    boost::shared_ptr<Convention> get(const string& id) const;
    /*! Clear all conventions */
    void clear();

    /*! Add a convention. This will overwrite an existing convention
        with the same id */
    void add(const boost::shared_ptr<Convention>& convention);

    //! \name Serilaisation
    //@{
    virtual void fromXML(XMLNode* node);
    virtual XMLNode* toXML(XMLDocument& doc);
    //@}

private:
    map<string, boost::shared_ptr<Convention>> data_;
};

//! Container for storing Bond Spread Rate conventions
/*!
\ingroup marketdata
*/
class SecuritySpreadConvention : public Convention {
public:
    //! \name Constructors
    //@{
    //! Default constructor
    SecuritySpreadConvention() {}
    SecuritySpreadConvention(const string& id, const string& dayCounter, const string& compounding,
                             const string& compoundingFrequency);
    SecuritySpreadConvention(const string& id, const string& dayCounter, const string& tenorCalendar,
                             const string& compounding = "Continuous", const string& compoundingFrequency = "Annual",
                             const string& spotLag = "", const string& spotCalendar = "",
                             const string& rollConvention = "", const string& eom = "");
    //@}

    //! \name Inspectors
    //@{
    //! Zero rate day counter
    const DayCounter& dayCounter() const { return dayCounter_; }
    //! Return the calendar used for converting tenor points into dates
    const Calendar& tenorCalendar() const { return tenorCalendar_; }
    //! Zero rate compounding
    Compounding compounding() const { return compounding_; }
    //! Zero rate compounding frequency
    Frequency compoundingFrequency() const { return compoundingFrequency_; }
    //! Zero rate spot lag
    Natural spotLag() const { return spotLag_; }
    //! Calendar used for spot date adjustment
    const Calendar& spotCalendar() const { return spotCalendar_; }
    //! Business day convention used in converting tenor points into dates
    BusinessDayConvention rollConvention() const { return rollConvention_; }
    //! End of month adjustment
    bool eom() { return eom_; }
    //! Flag to indicate whether the Zero Rate convention is based on a tenor input
    bool tenorBased() { return tenorBased_; }
    //@}

    //! \name Serialisation
    //@{
    virtual void fromXML(XMLNode* node);
    virtual XMLNode* toXML(XMLDocument& doc);
    virtual void build();
    //@}

private:
    DayCounter dayCounter_;
    Calendar tenorCalendar_;
    Compounding compounding_;
    Frequency compoundingFrequency_;
    Natural spotLag_;
    Calendar spotCalendar_;
    BusinessDayConvention rollConvention_;
    bool eom_;
    bool tenorBased_;

    // Strings to store the inputs
    string strDayCounter_;
    string strTenorCalendar_;
    string strCompounding_;
    string strCompoundingFrequency_;
    string strSpotLag_;
    string strSpotCalendar_;
    string strRollConvention_;
    string strEom_;
};
}
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='AppInfo',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=32)),
                ('icon', models.URLField()),
                ('launcher', models.URLField()),
                ('version', models.CharField(max_length=32)),
                ('bundle_id', models.CharField(max_length=100)),
            ],
        ),
    ]


text:
import React from 'react';
import { shallow } from 'enzyme'
import toJson from 'enzyme-to-json';
import Title from '../Title';

describe('<Title />', () => {
  it('should render when no text supplied', () => {
    let wrapper = shallow(<Title text=''/>);
    expect(toJson(wrapper)).toMatchSnapshot();
  });

  it('should render when string supplied', () => {
    let wrapper = shallow(<Title text='Title text'/>);
    expect(toJson(wrapper)).toMatchSnapshot();
  });

  it('should render when expression supplied', () => {
    let wrapper = shallow(<Title text={12 * 3}/>);
    expect(toJson(wrapper)).toMatchSnapshot();
  });

});


text:
import importlib

from contextlib import contextmanager

try:
    # once we drop sqlalchemy 1.2, can use create_mock_engine function
    from sqlalchemy.engine.mock import MockConnection
except ImportError:
    from sqlalchemy.engine.strategies import MockEngineStrategy
    MockConnection = MockEngineStrategy.MockConnection

def get_dialect_translator(name):
    mod = importlib.import_module('siuba.sql.dialects.{}'.format(name))
    return mod.translator

def get_dialect_funcs(name):
    #dialect = engine.dialect.name
    mod = importlib.import_module('siuba.sql.dialects.{}'.format(name))
    return mod.funcs

def get_sql_classes(name):
    mod = importlib.import_module('siuba.sql.dialects.{}'.format(name))
    win_name = name.title() + "Column"
    agg_name = name.title() + "ColumnAgg"
    return {
            'window': getattr(mod, win_name),
            'aggregate': getattr(mod, agg_name)
            }

def mock_sqlalchemy_engine(dialect):
    """
    Create a sqlalchemy.engine.Engine without it connecting to a database.

    Examples
    --------

    ::
        from siuba.sql import LazyTbl
        from siuba import _, mutate, show_query

        engine = mock_sqlalchemy_engine('postgresql')
        tbl = LazyTbl(engine, 'some_table', ['x'])

        query = mutate(tbl, y = _.x + _.x)
        show_query(query)

    """

    from sqlalchemy.engine import Engine
    from sqlalchemy.dialects import registry
    from types import ModuleType

    #  TODO: can be removed once v1.3.18 support dropped
    from sqlalchemy.engine.url import URL

    dialect_cls = registry.load(dialect)

    # there is probably a better way to do this, but for some reason duckdb
    # returns a module, rather than the dialect class itself. By convention,
    # dialect modules expose a variable named dialect, so we grab that.
    if isinstance(dialect_cls, ModuleType):
        dialect_cls = dialect_cls.dialect

    conn = MockConnection(dialect_cls(), lambda *args, **kwargs: None)

    # set a url on it, so that LazyTbl can read the backend name.
    if is_sqla_12() or is_sqla_13():
        url = URL(drivername=dialect)
    else:
        url = URL.create(drivername=dialect)

    conn.url = url

    return conn

# Temporary fix for pandas bug (https://github.com/pandas-dev/pandas/issues/35484)
from pandas.io import sql as _pd_sql

class _FixedSqlDatabase(_pd_sql.SQLDatabase):
    def execute(self, *args, **kwargs):
        return self.connectable.execute(*args, **kwargs)

# Detect duckdb for temporary workarounds -------------------------------------

def _is_dialect_duckdb(engine):
    return engine.url.get_backend_name() == "duckdb"

# Backwards compatibility for sqlalchemy 1.3 ----------------------------------

import re
import sqlalchemy

RE_VERSION=r"(?P<major>\d+)\.(?P<minor>\d+).(?P<patch>\d+)"
SQLA_VERSION=tuple(map(int, re.match(RE_VERSION, sqlalchemy.__version__).groups()))

def is_sqla_12():
    return SQLA_VERSION[:-1] == (1, 2)

def is_sqla_13():
    return SQLA_VERSION[:-1] == (1, 3)

def _sql_select(columns, *args, **kwargs):
    from sqlalchemy import sql
    if is_sqla_12() or is_sqla_13():
        # use old syntax, where columns are passed as a list
        return sql.select(columns, *args, **kwargs)

    return sql.select(*columns, *args, **kwargs)

def _sql_column_collection(columns):
    from sqlalchemy.sql.base import ColumnCollection, ImmutableColumnCollection

    data = {col.key: col for col in columns}

    if is_sqla_12() or is_sqla_13():
        return ImmutableColumnCollection(data, columns)

    return ColumnCollection(list(data.items())).as_immutable()

def _sql_add_columns(select, columns):
    if is_sqla_12() or is_sqla_13():
        for column in columns:
            select = select.column(column)
        return select

    return select.add_columns(*columns)

def _sql_with_only_columns(select, columns):
    if is_sqla_12() or is_sqla_13():
        out = select.with_only_columns(columns)
    else:
        out = select.with_only_columns(*columns)

    # ensure removing all columns doesn't remove from clause table reference
    for _from in select.froms:
        out = out.select_from(_from)

    return out

def _sql_case(*args, **kwargs):
    from sqlalchemy import sql
    if is_sqla_12() or is_sqla_13():
        return sql.case(args, **kwargs)

    return sql.case(*args, **kwargs)

# Simplify option in show_query -----------------------------------------------

def _sql_refresh(el):
    f_refresh = getattr(
        el,
        "_reset_memoizations",
        getattr(el, "_reset_exported", None)
    )

    f_refresh()

def _sql_simplify_select(select):
    from sqlalchemy import sql
    from sqlalchemy.sql.visitors import traverse, cloned_traverse

    def simplify_sel(sel):

        if isinstance(sel, sql.Select) and len(sel.froms) == 1:
            child = sel.froms[0]

            # technically should be an ordered set
            crnt_cols = set(sel.inner_columns)
            child_cols = set(child.columns)

            if len(child_cols - crnt_cols) == 0:
                remaining = list(crnt_cols - child_cols)

                star = sql.text("*")
                star._from_objects = (child,)

                sel._raw_columns = [star, *remaining]
                _sql_refresh(sel)

    # TODO: find simpler way to clone an element. We cannot use the visitors
    # argument of cloned_traverse, since it visits the inner-most element first.
    clone_el = select._clone()

    # modify in-place
    traverse(clone_el, {}, {"select": simplify_sel})

    return clone_el

def lift_inner_cols(tbl):
    cols = list(tbl.inner_columns)

    return _sql_column_collection(cols)


text:
'use strict';

describe('popover', function () {

  var $compile, $templateCache, scope, sandboxEl;

  beforeEach(module('ngSanitize'));
  beforeEach(module('jsleao.ngStrap.popover'));
  jQuery.fn.triggerHandler = function(evt) {
    return angular.element(this[0]).triggerHandler(evt);
  };

  beforeEach(inject(function (_$rootScope_, _$compile_, _$templateCache_) {
    scope = _$rootScope_;
    $compile = _$compile_;
    $templateCache = _$templateCache_;
    sandboxEl = $('
').attr('id', 'sandbox').appendTo('body');
  }));

  afterEach(function() {
    sandboxEl.remove();
    scope.$destroy();
  });

  // Templates

  var templates = {
    'default': {
      scope: {popover: {title: 'Title', content: 'Hello Popover!'}},
      element: ''
    },
    'markup-scope': {
      element: 'click me'
    },
    'markup-ngRepeat': {
      scope: {items: [{name: 'foo', popover: {title: 'Title', content: 'Hello Popover!'}}]},
      element: '

{{item.name}}

'
    },
    'options-animation': {
      element: 'hover me'
    },
    'options-placement': {
      element: 'hover me'
    },
    'options-placement-exotic': {
      element: 'hover me'
    },
    'options-trigger': {
      element: 'hover me'
    },
    'options-html': {
      scope: {popover: {title: 'Title', content: 'Hello Popover
This is a multiline message!'}},
      element: ''
    },
    'options-template': {
      scope: {popover: {title: 'Title', content: 'Hello Popover!', counter: 0}, items: ['foo', 'bar', 'baz']},
      element: 'click me'
    },
    'bsShow-attr': {
      scope: {popover: {title: 'Title', content: 'Hello Popover!'}},
      element: ''
    },
    'bsShow-binding': {
      scope: {isVisible: false, popover: {title: 'Title', content: 'Hello Popover!'}},
      element: ''
    }
  };

  function compileDirective(template, locals) {
    template = templates[template];
    angular.extend(scope, template.scope || templates['default'].scope, locals);
    var element = $(template.element).appendTo(sandboxEl);
    element = $compile(element)(scope);
    scope.$digest();
    return jQuery(element[0]);
  }

  // Tests

  describe('default', function () {

    it('should open on click', function() {
      var elm = compileDirective('default');
      expect(sandboxEl.children().length).toBe(1);
      elm.triggerHandler('click');
      expect(sandboxEl.children().length).toBe(2);
    });

    it('should close on double-click', function() {
      var elm = compileDirective('default');
      expect(sandboxEl.children().length).toBe(1);
      elm.triggerHandler('click');
      elm.triggerHandler('click');
      expect(sandboxEl.children().length).toBe(1);
    });

    it('should correctly compile inner content', function() {
      var elm = compileDirective('default');
      angular.element(elm[0]).triggerHandler('click');
      expect(sandboxEl.find('.popover-title').html()).toBe(scope.popover.title);
      expect(sandboxEl.find('.popover-content').html()).toBe(scope.popover.content);
    });

    it('should support scope as object', function() {
      var elm = compileDirective('markup-scope');
      angular.element(elm[0]).triggerHandler('click');
      expect(sandboxEl.find('.popover-title').html()).toBe(scope.popover.title);
      expect(sandboxEl.find('.popover-content').html()).toBe(scope.popover.content);
    });

    it('should support ngRepeat markup', function() {
      var elm = compileDirective('markup-ngRepeat');
      angular.element(elm.find('[bs-popover]')).triggerHandler('click');
      expect(sandboxEl.find('.popover-title').html()).toBe(scope.items[0].popover.title);
      expect(sandboxEl.find('.popover-content').html()).toBe(scope.items[0].popover.content);
    });

  });

  describe('bsShow attribute', function() {
    it('should support setting to a boolean value', function() {
      var elm = compileDirective('bsShow-attr');
      expect(sandboxEl.children().length).toBe(2);
    });

    it('should support binding', function() {
      var elm = compileDirective('bsShow-binding');
      expect(scope.isVisible).toBeFalsy();
      expect(sandboxEl.children().length).toBe(1);
      scope.isVisible = true;
      scope.$digest();
      expect(sandboxEl.children().length).toBe(2);
      scope.isVisible = false;
      scope.$digest();
      expect(sandboxEl.children().length).toBe(1);
    });

    it('should support initial value false', function() {
      var elm = compileDirective('bsShow-binding');
      expect(scope.isVisible).toBeFalsy();
      expect(sandboxEl.children().length).toBe(1);
    });

    it('should support initial value true', function() {
      var elm = compileDirective('bsShow-binding', {isVisible: true});
      expect(scope.isVisible).toBeTruthy();
      expect(sandboxEl.children().length).toBe(2);
    });

    it('should support undefined value', function() {
      var elm = compileDirective('bsShow-binding', {isVisible: undefined});
      expect(sandboxEl.children().length).toBe(1);
    });

    it('should support string value', function() {
      var elm = compileDirective('bsShow-binding', {isVisible: 'a string value'});
      expect(sandboxEl.children().length).toBe(1);
      scope.isVisible = 'TRUE';
      scope.$digest();
      expect(sandboxEl.children().length).toBe(2);
      scope.isVisible = 'dropdown';
      scope.$digest();
      expect(sandboxEl.children().length).toBe(1);
      scope.isVisible = 'datepicker,popover';
      scope.$digest();
      expect(sandboxEl.children().length).toBe(2);
    });
  });

  describe('options', function () {

    describe('animation', function () {

      it('should default to `am-fade` animation', function() {
        var elm = compileDirective('default');
        angular.element(elm[0]).triggerHandler('click');
        expect(sandboxEl.children('.popover').hasClass('am-fade')).toBeTruthy();
      });

      it('should support custom animation', function() {
        var elm = compileDirective('options-animation');
        angular.element(elm[0]).triggerHandler('click');
        expect(sandboxEl.children('.popover').hasClass('am-flip-x')).toBeTruthy();
      });

    });

    describe('placement', function () {

      it('should default to `right` placement', function() {
        var elm = compileDirective('default');
        angular.element(elm[0]).triggerHandler('click');
        expect(sandboxEl.children('.popover').hasClass('right')).toBeTruthy();
      });

      it('should support placement', function() {
        var elm = compileDirective('options-placement');
        angular.element(elm[0]).triggerHandler('click');
        expect(sandboxEl.children('.popover').hasClass('bottom')).toBeTruthy();
      });

      it('should support exotic-placement', function() {
        var elm = compileDirective('options-placement-exotic');
        angular.element(elm[0]).triggerHandler('click');
        expect(sandboxEl.children('.popover').hasClass('bottom-right')).toBeTruthy();
      });

    });

    describe('trigger', function () {

      it('should support an alternative trigger', function() {
        var elm = compileDirective('options-trigger');
        expect(sandboxEl.children('.popover').length).toBe(0);
        angular.element(elm[0]).triggerHandler('mouseenter');
        expect(sandboxEl.children('.popover').length).toBe(1);
        angular.element(elm[0]).triggerHandler('mouseleave');
        expect(sandboxEl.children('.popover').length).toBe(0);
      });

    });

    describe('html', function () {

      it('should correctly compile inner content', function() {
        var elm = compileDirective('options-html');
        angular.element(elm[0]).triggerHandler('click');
        expect(sandboxEl.find('.popover-title').html()).toBe(scope.popover.title);
        expect(sandboxEl.find('.popover-content').html()).toBe(scope.popover.content);
      });

    });

    describe('template', function () {

      it('should support custom template', function() {
        $templateCache.put('custom', '

foo: {{content}}

');
        var elm = compileDirective('options-template');
        angular.element(elm[0]).triggerHandler('click');
        expect(sandboxEl.find('.popover-content').text()).toBe('foo: ' + scope.popover.content);
      });

      it('should support template with ngRepeat', function() {
        $templateCache.put('custom', '

{{item}}

');
        var elm = compileDirective('options-template');
        angular.element(elm[0]).triggerHandler('click');
        expect(sandboxEl.find('.popover-content').text()).toBe('foobarbaz');
        // Consecutive toggles
        angular.element(elm[0]).triggerHandler('click');
        angular.element(elm[0]).triggerHandler('click');
        expect(sandboxEl.find('.popover-content').text()).toBe('foobarbaz');
      });

      it('should support template with ngClick', function() {
        $templateCache.put('custom', '

click me

');
        var elm = compileDirective('options-template');
        angular.element(elm[0]).triggerHandler('click');
        expect(angular.element(sandboxEl.find('.popover-content > .btn')[0]).triggerHandler('click'));
        expect(scope.popover.counter).toBe(1);
        // Consecutive toggles
        angular.element(elm[0]).triggerHandler('click');
        angular.element(elm[0]).triggerHandler('click');
        expect(angular.element(sandboxEl.find('.popover-content > .btn')[0]).triggerHandler('click'));
        expect(scope.popover.counter).toBe(2);
      });

    });

  });

});


text:
#pragma once

#include "ofMain.h"
#include "ofxNetwork.h"
#include "ofxSelflash.h"

#include "NetworkEvent.h"

using namespace fl2d;

class UDPSocketWrapper : public flEventDispatcher {
    public:
        static string getLocalAddress();

    protected:
        bool _usedListeners;

        //UDPソケット
        ofxUDPManager* _socket;

        bool _isBinded;
        bool _isConnected;

        string _localIp;
        int _localPort;
        string _targetIp;
        int _targetPort;
        string _remoteIp;
        int _remotePort;

        string _sendData;
        string _receivedData;

    private:

    public:
        UDPSocketWrapper();
        ~UDPSocketWrapper();

        virtual void setup();
        virtual void update();

        virtual bool bind(int port);
        virtual bool connect(string ip, int port);
        virtual int sendMessage(string message);
        virtual bool close();

        virtual bool isBinded();
        virtual bool isConnected();

        virtual string localIp();
        virtual int localPort();

        virtual string targetIp();
        virtual int targetPort();

        virtual string remoteIp();
        virtual int remotePort();

        virtual string sendData();
        virtual string receivedData();

    protected:

    private:
        void _addListeners();
        void _removeListeners();
        void _update(ofEventArgs& event) { update(); }
};


text:
| Method name                      | Implementation                                                      |
|----------------------------------|---------------------------------------------------------------------|
| Backend#Start                    | Not implemented                                                     |
| Backend#Stop                     | Not implemented                                                     |
| Backend#GraceTime                | Implemented                                                         |
| Backend#Ping                     | Implemented                                                         |
| Backend#Capacity                 | Implemented (MaxContainers = 100)                                   |
| Backend#Create                   | Implemented (except: `RootFSPath`, `ImageRef`, `Network` and the folowing limits: `Bandwidth`, `CPU` and `Pid`) |
| Backend#Destroy                  | Implemented                                                         |
| Backend#Containers               | Implemented                                                         |
| Backend#Lookup                   | Not Implemented (returns a dummy container without checking if the handle exists) |
| Backend#BulkInfo                 | Implemented -- (Only `MappedPorts`, `Properties` and `ExternalIP` are returned)   |
| Backend#BulkMetrics              | Implemented -- (Only, MemoryStat, CPUStat, DiskStat. No NetworkStat)              |
| Container#Handle                 | Implemented                                                                       |
| Container#Stop                   | Implemented (the `kill` flag is ignored, kill is the default)                     |
| Container#Info                   | Implemented (Only `MappedPorts`, `Properties` and `ExternalIP` are returned)      |
| Container#StreamIn               | Implemented                                                         |
| Container#StreamOut              | Implemented                                                         |
| Container#CurrentBandwidthLimits | Not Implemented                                                     |
| Container#CurrentCPULimits       | Not Implemented                                                     |
| Container#CurrentMemoryLimits    | Implemented                                                         |
| Container#NetIn                  | Implemented                                                         |
| Container#NetOut                 | Implemented -- (Except ICMP. ICMP is currently blocked for all containers) |
| Container#Run                    | (All flags are ignored except `Path`, `Args` and `Env`, see notes)    |
| Container#Attach                 | Not Implemented                                                       |
| Container#Metrics                | Implemented -- (Only, MemoryStat, CPUStat, DiskStat.  No NetworkStat) |
| Container#Properties             | Implemented                                                           |
| Container#Property               | Implemented                                                           |
| Container#SetProperty            | Implemented                                                           |
| Container#RemoveProperty         | Implemented                                                           |
| Container#SetGraceTime           | Implemented                                                           |
| Container#BulkNetOut             | Implemented                                                           |
| Container#CurrentDiskLimits      | Implemented                                                           |
| Container#LimitCPU               | Not Implemented (Not Part of API)                                     |
| Container#LimitDisk              | Implemented (Not Part of API)                                         |
| Container#LimitMemory            | Implemented (Not Part of API)                                         |
| Container#LimitBandwidth         | Not Implemented (Not Part of API)                                     |
| Processes#ID                     | Implemented                                                           |
| Processes#Wait                   | Implemented                                                           |
| Processes#SetTTY                 | Not Implemented                                                       |
| Processes#Signal                 | Implemented (the signal argument is ignored, the process is killed)   |

# Container

# Limitations of Container#Create

Supplying a base Docker image for your container via `RootFSPath` or `ImageRef` is not supported.
The following limits are ignored `Bandwidth`, `CPU` and `Pid`.  The `Pid` limit is hard-coded to 10.

# Limitations of Container#LimitCPU

CPU limits are not enforced.

# Limitations of Container#LimitBandwidth

Bandwidth limits are not enforced.

# Limitations of Container#Run

1. No support for `Privileged` contianers (the flag is ignored)
2. `User` flag is ignored (`garden-windows` creates a new user for each container)
3. Stdin is not supported (stdout/stderr enforce newlines)


text:
// .NAME vtkGPUInfoListArray - Internal class vtkGPUInfoList.
// .SECTION Description
// vtkGPUInfoListArray is just a PIMPL mechanism for vtkGPUInfoList.

#ifndef __vtkGPUInfoListArray_h
#define __vtkGPUInfoListArray_h

#include "vtkRenderingCoreExport.h" // For export macro
#include "vtkGPUInfo.h"
#include <vtkstd/vector> // STL Header

class vtkGPUInfoListArray
{
public:
  vtkstd::vector<vtkGPUInfo *> v;
};

#endif


text:
using System;
using System.Xml.Serialization;
using Predica.CostkillerLib.Model.Enums;

namespace Predica.CostkillerLib.Model.Entities.CostkillerXml
{
    /// <remarks/>
    [XmlRoot("document")]
    public class Document
    {
        /// <remarks/>
        [XmlElement("doc_id")]
        public int DocId { get; set; }

        /// <remarks/>
        [XmlElement("contr_id")]
        public int ContrId { get; set; }

        /// <remarks/>
        [XmlElement("contr_data_id")]
        public int ContrDataId { get; set; }

        /// <remarks/>
        [XmlElement("doc_symbol")]
        public string DocSymbol { get; set; }

        [XmlElement("doc_type")]
        public string DocType { get; set; }

        public DocumentType DocumentType => GetDocumentType();

        /// <remarks/>
        [XmlElement("doc_number")]
        public string DocNumber { get; set; }

        /// <remarks/>
        [XmlElement("correction")]
        public int CorrectionInt { get; set; }

        public bool Correction => CorrectionInt == 1;

        [XmlElement("doc_sales_date")]
        public string DocSalesDate { get; set; }

        /// <remarks/>
        [XmlElement("doc_issue_date")]
        public string DocIssueDate { get; set; }

        [XmlElement("source_document_id")]
        public int CorrectedDocumentID { get; set; }

        /// <remarks/>
        [XmlElement("doc_reg_date")]
        public string DocRegDate { get; set; }

        /// <remarks/>
        [XmlElement("gl_year")]
        public int GlYear { get; set; }

        /// <remarks/>
        [XmlElement("gl_month")]
        public int GlMonth { get; set; }

        public DateTime BillingPeriod => DateTime.Parse($"{GlYear}-{GlMonth}");

        /// <remarks/>
        [XmlElement("payment_date")]
        public string PaymentDate { get; set; }

        /// <remarks/>
        [XmlElement("payment_type")]
        public string PaymentType { get; set; }

        /// <remarks/>
        [XmlElement("net")]
        public decimal Net { get; set; }

        /// <remarks/>
        [XmlElement("vat")]
        public decimal Vat { get; set; }

        /// <remarks/>
        [XmlElement("gross")]
        public decimal Gross { get; set; }

        /// <remarks/>
        [XmlElement("amount_to_pay")]
        public decimal AmountToPay { get; set; }

        /// <remarks/>
        [XmlElement("amount_paid")]
        public decimal AmountPaid { get; set; }

        /// <remarks/>
        [XmlElement("amount_remaining")]
        public decimal AmountRemaining { get; set; }

        /// <remarks/>
        [XmlElement("iban")]
        public string Iban { get; set; }

        /// <remarks/>
        [XmlElement("currency")]
        public string Currency { get; set; }

        /// <remarks/>
        [XmlElement("transaction_desc")]
        public string TransactionDesc { get; set; }

        /// <remarks/>
        [XmlElement("status")]
        public string Status { get; set; }

        /// <remarks/>
        [XmlElement("remarks")]
        public object Remarks { get; set; }

        /// <remarks/>
        [XmlElement("contractor")]
        public DocumentContractor Contractor { get; set; }

        /// <remarks/>
        [XmlArray("items")]
        public DocumentItem[] Items { get; set; }

        public decimal exchange_rate { get; set; }

        /// <remarks/>
        public object Decrees { get; set; }

        public DocumentStatus GetDocumentStatus()
        {
            switch (Status)
            {
                case "A":
                    return DocumentStatus.Accepted;
                case "C":
                    return DocumentStatus.Corrected;
                default:
                    return DocumentStatus.Unknown;
            }
        }

        private DocumentType GetDocumentType()
        {
#if PROD
            switch (DocSymbol)
            {
                case "KO":
                case "FVS":
                case "PKD":
                    return DocumentType.Cost;
                //case "SP":
                //    return DocumentType.Sales;
                default:
                    return DocumentType.Unknown;
            }

#else
            switch (DocType)
            {
                case "C":
                    return DocumentType.Cost;
                case "S":
                    return DocumentType.Sales;
                default:
                    return DocumentType.Unknown;
            }
#endif

        }
    }
}