text:
package org.oscm.billingservice.business.calculation.revenue;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import org.oscm.billingservice.business.calculation.revenue.model.PriceModelInput;
import org.oscm.billingservice.business.model.billingresult.BillingDetailsType;
import org.oscm.billingservice.business.model.billingresult.PriceModelsType;
import org.oscm.billingservice.dao.BillingDataRetrievalServiceBean;
import org.oscm.billingservice.dao.model.OrganizationAddressData;
import org.oscm.billingservice.dao.model.VatRateDetails;
import org.oscm.billingservice.dao.model.XParameterData;
import org.oscm.billingservice.dao.model.XParameterIdData;
import org.oscm.billingservice.dao.model.XParameterPeriodPrimitiveType;
import org.oscm.billingservice.service.model.BillingInput;
import org.oscm.dataservice.local.DataService;
import org.oscm.domobjects.BillingResult;
import org.oscm.domobjects.PriceModelHistory;
import org.oscm.domobjects.ProductHistory;
import org.oscm.domobjects.SubscriptionHistory;
import org.oscm.domobjects.UsageLicenseHistory;
import org.oscm.domobjects.UserGroupHistory;
import org.oscm.test.DateTimeHandling;
import org.oscm.test.ReflectiveAccess;
import org.oscm.types.exceptions.BillingRunFailed;
import org.oscm.internal.types.enumtypes.ParameterType;
import org.oscm.internal.types.enumtypes.ParameterValueType;
import org.oscm.internal.types.enumtypes.PriceModelType;
import org.oscm.internal.types.enumtypes.PricingPeriod;
import org.oscm.internal.types.enumtypes.SubscriptionStatus;

/**
 * @author weiser
 *
 */
public class CreateBillingDataForOrganizationTest {

    // Java double has a precision of 15 significant digits.
    private final static double ASSERT_DOUBLE_DELTA = 0.000000000000009D;

    private RevenueCalculatorBean bb;
    private PriceModelHistory pmh;
    private ProductHistory ph;
    private DataService dm;

    @Before
    public void setup() throws Exception {
        bb = spy(new RevenueCalculatorBean());
        bb.bdr = mock(BillingDataRetrievalServiceBean.class);
        dm = mock(DataService.class);
        ReflectiveAccess.set(bb.bdr, "dm", dm);

        doReturn(new UserGroupHistory()).when(bb.bdr).getLastValidGroupHistory(
                anyLong(), anyLong());
        when(
                bb.bdr.loadOrganizationBillingDataFromHistory(anyLong(),
                        anyLong())).thenReturn(
                new OrganizationAddressData("a", "n", "e", "id"));
        when(bb.bdr.loadVATForCustomer(anyLong(), anyLong(), anyLong()))
                .thenReturn(new VatRateDetails());

        doReturn(Long.valueOf(1)).when(bb.bdr)
                .loadPriceModelKeyForSubscriptionHistory(
                        any(SubscriptionHistory.class));

        pmh = new PriceModelHistory();
        pmh.setType(PriceModelType.PRO_RATA);
        pmh.setPeriod(PricingPeriod.WEEK);
        pmh.setFreePeriod(0);
        pmh.setModdate(new Date());

        doReturn(pmh).when(bb.bdr).loadOldestPriceModelHistory(anyLong(),
                anyLong());
        when(bb.bdr.loadLatestPriceModelHistory(any(SubscriptionHistory.class)))
                .thenReturn(pmh);

        doReturn(new Date(0)).when(bb.bdr).loadPriceModelStartDate(anyLong());

        ph = new ProductHistory();
        ph.getDataContainer().setProductId("AService");
        when(
                bb.bdr.loadProductTemplateHistoryForSubscriptionHistory(
                        any(SubscriptionHistory.class), anyLong())).thenReturn(
                ph);
    }

    @Test
    public void createBillingDataForOrganization_EmptyList() throws Exception {
        // given
        // when
        BillingDetailsType doc = createBillingDataForOrganization(1, 1, 10, 20,
                0, new BillingResult(), true,
                new ArrayList<SubscriptionHistory>(), "EUR");

        // then
        assertNull(doc);
        verifyZeroInteractions(bb.bdr, dm);
    }

    private BillingDetailsType createBillingDataForOrganization(
            long organizationKey, long subscriptionKey, long startOfPeriod,
            long endOfPeriod, long cutOffDate, BillingResult billingResult,
            boolean storeResultXML, List<SubscriptionHistory> subHistEntries,
            String currency) throws BillingRunFailed {
        BillingInput.Builder billingInput = new BillingInput.Builder();
        billingInput.setOrganizationKey(organizationKey);
        billingInput.setSubscriptionKey(subscriptionKey);
        billingInput.setBillingPeriodStart(startOfPeriod);
        billingInput.setBillingPeriodEnd(endOfPeriod);
        billingInput.setCutOffDate(cutOffDate);
        billingInput.setStoreBillingResult(storeResultXML);
        billingInput.setSubscriptionHistoryEntries(subHistEntries);
        billingInput.setCurrencyIsoCode(currency);

        return bb.createBillingDataForOrganization(billingInput.build(),
                billingResult);
    }

    @Test
    public void createBillingDataForOrganization_ProRataDeactivatedBeforePeriod()
            throws Exception {
        // given
        long billingPeriodStart = DateTimeHandling
                .calculateMillis("2013-03-01 00:00:00");
        long billingPeriodEnd = DateTimeHandling
                .calculateMillis("2013-04-01 00:00:00");

        SubscriptionHistory sh = new SubscriptionHistory();
        sh.setModdate(DateTimeHandling.calculateDate("2013-02-28 23:59:59"));
        sh.setObjKey(1);
        sh.setOrganizationObjKey(1);
        sh.getDataContainer().setStatus(SubscriptionStatus.DEACTIVATED);

        // when
        BillingDetailsType doc = createBillingDataForOrganization(1, 1,
                billingPeriodStart, billingPeriodEnd, 0, new BillingResult(),
                true, Arrays.asList(sh), "EUR");

        // then
        assertNull(doc);
    }

    @Test
    public void createBillingDataForOrganization_FreeOfChargeDeactivatedBeforePeriod()
            throws Exception {
        // given
        pmh.setType(PriceModelType.FREE_OF_CHARGE);

        long billingPeriodStart = DateTimeHandling
                .calculateMillis("2013-03-01 00:00:00");
        long billingPeriodEnd = DateTimeHandling
                .calculateMillis("2013-04-01 00:00:00");

        SubscriptionHistory sh = new SubscriptionHistory();
        sh.setModdate(DateTimeHandling.calculateDate("2013-02-28 23:59:59"));
        sh.setObjKey(1);
        sh.setOrganizationObjKey(1);
        sh.getDataContainer().setStatus(SubscriptionStatus.DEACTIVATED);

        // when
        BillingDetailsType doc = createBillingDataForOrganization(1, 1,
                billingPeriodStart, billingPeriodEnd, 0, new BillingResult(),
                true, Arrays.asList(sh), "EUR");

        // then
        assertNull(doc);
    }

    @Test
    public void createBillingDataForOrganization_PerUnitDeactivatedBeforePeriod()
            throws Exception {
        // given
        pmh.setType(PriceModelType.PER_UNIT);

        long billingPeriodStart = DateTimeHandling
                .calculateMillis("2013-03-01 00:00:00");
        long billingPeriodEnd = DateTimeHandling
                .calculateMillis("2013-04-01 00:00:00");

        SubscriptionHistory sh = new SubscriptionHistory();
        sh.setModdate(DateTimeHandling.calculateDate("2013-02-24 23:59:59"));
        sh.setObjKey(1);
        sh.setOrganizationObjKey(1);
        sh.getDataContainer().setStatus(SubscriptionStatus.DEACTIVATED);

        // when
        BillingDetailsType doc = createBillingDataForOrganization(1, 1,
                billingPeriodStart, billingPeriodEnd, 0, new BillingResult(),
                true, Arrays.asList(sh), "EUR");

        // then
        assertNull(doc);
    }

    @Test
    public void createBillingDataForOrganization_PerUnitDeactivatedBetweenTimeUnitStartAndBillingStart()
            throws Exception {

        // given
        pmh.setType(PriceModelType.PER_UNIT);

        doAnswer(new Answer<BigDecimal>() {
            @Override
            public BigDecimal answer(InvocationOnMock invocation) {
                Object[] args = invocation.getArguments();
                PriceModelsType pmType = (PriceModelsType) args[2];
                pmType.getPriceModel()
                        .add(new org.oscm.billingservice.business.model.billingresult.PriceModelType());
                return CostCalculator.ZERO_NORMALIZED;
            }
        }).when(bb).billPriceModel(any(BillingInput.class),
                any(PriceModelInput.class), any(PriceModelsType.class),
                any(BillingResult.class));

        long billingPeriodStart = DateTimeHandling
                .calculateMillis("2013-03-01 00:00:00");
        long billingPeriodEnd = DateTimeHandling
                .calculateMillis("2013-04-01 00:00:00");

        SubscriptionHistory sh1 = new SubscriptionHistory();
        sh1.setModdate(DateTimeHandling.calculateDate("2013-02-15 03:00:00"));
        sh1.setObjKey(1);
        sh1.setOrganizationObjKey(1);
        sh1.getDataContainer().setActivationDate(
                Long.valueOf(DateTimeHandling
                        .calculateMillis("2013-02-15 03:00:00")));
        sh1.getDataContainer().setStatus(SubscriptionStatus.ACTIVE);
        sh1.setUserGroupObjKey(Long.valueOf(100L));

        SubscriptionHistory sh2 = new SubscriptionHistory();
        sh2.setModdate(DateTimeHandling.calculateDate("2013-02-27 13:11:00"));
        sh2.setObjKey(1);
        sh2.setOrganizationObjKey(1);
        sh2.getDataContainer().setActivationDate(
                Long.valueOf(DateTimeHandling
                        .calculateMillis("2013-02-15 03:00:00")));
        sh2.getDataContainer().setStatus(SubscriptionStatus.DEACTIVATED);
        sh2.setUserGroupObjKey(Long.valueOf(200L));

        // when
        BillingDetailsType doc = createBillingDataForOrganization(1, 1,
                billingPeriodStart, billingPeriodEnd, 0, new BillingResult(),
                true, Arrays.asList(sh2, sh1), "EUR");

        // then
        assertNotNull(doc);
        assertEquals(1, doc.getSubscriptions().getSubscription().size());
        assertEquals(0.0, doc.getOverallCosts().getGrossAmount().doubleValue(),
                0);
    }

    @Test
    public void createBillingDataForOrganization_DeactivatedInPeriod()
            throws Exception {
        // given
        long billingPeriodStart = DateTimeHandling
                .calculateMillis("2013-03-01 00:00:00");
        long billingPeriodEnd = DateTimeHandling
                .calculateMillis("2013-04-01 00:00:00");

        SubscriptionHistory sh1 = new SubscriptionHistory();
        sh1.setModdate(DateTimeHandling.calculateDate("2013-02-15 03:00:00"));
        sh1.setObjKey(1);
        sh1.setOrganizationObjKey(1);
        sh1.getDataContainer().setActivationDate(
                Long.valueOf(DateTimeHandling
                        .calculateMillis("2013-02-15 03:00:00")));
        sh1.getDataContainer().setStatus(SubscriptionStatus.ACTIVE);
        sh1.setUserGroupObjKey(Long.valueOf(100L));

        SubscriptionHistory sh2 = new SubscriptionHistory();
        sh2.setModdate(DateTimeHandling.calculateDate("2013-03-15 13:00:00"));
        sh2.setObjKey(1);
        sh2.setOrganizationObjKey(1);
        sh2.getDataContainer().setActivationDate(
                Long.valueOf(DateTimeHandling
                        .calculateMillis("2013-02-15 03:00:00")));
        sh2.getDataContainer().setStatus(SubscriptionStatus.DEACTIVATED);
        sh2.setUserGroupObjKey(Long.valueOf(200L));

        // when
        BillingDetailsType doc = createBillingDataForOrganization(1, 1,
                billingPeriodStart, billingPeriodEnd, 0, new BillingResult(),
                true, Arrays.asList(sh1, sh2), "EUR");

        // then
        assertNotNull(doc);
        assertEquals(1, doc.getSubscriptions().getSubscription().size());
        assertEquals(0.0, doc.getOverallCosts().getGrossAmount().doubleValue(),
                0);
    }

    /**
     * Calculates the factors for period fee, user assignment and parameter
     * assignment.
     *
     * Note: The cut off day is the 26, we calculate from 22.2. until 26.2. For
     * pro rata calculation the month has 31 days starting 26.1. until 26.2. All
     * factors must be calculated on that base, not on 29 days which the
     * February 2012 has!
     */
    @Test
    public void createBillingDataForOrganization_CuttOffDay26()
            throws Exception {
        // given
        SubscriptionHistory sh1 = new SubscriptionHistory();
        sh1.setModdate(new Date(DateTimeHandling
                .calculateMillis("2012-02-24 00:00:00")));
        sh1.setObjKey(1);
        sh1.setCutOffDay(26);
        sh1.setOrganizationObjKey(1);
        sh1.getDataContainer().setActivationDate(
                Long.valueOf(sh1.getModdate().getTime()));
        sh1.getDataContainer().setStatus(SubscriptionStatus.ACTIVE);
        sh1.setUserGroupObjKey(Long.valueOf(100L));

        pmh.setPeriod(PricingPeriod.MONTH);
        UsageLicenseHistory ul = new UsageLicenseHistory();
        ul.setModdate(new Date(DateTimeHandling
                .calculateMillis("2012-02-25 00:00:00")));
        when(bb.bdr.loadUsageLicenses(anyLong(), anyLong(), anyLong()))
                .thenReturn(Arrays.asList(ul));
        XParameterData pd = new XParameterData();
        pd.getIdDataInstance("ert", ParameterType.SERVICE_PARAMETER,
                ParameterValueType.INTEGER);
        XParameterIdData id = pd.getIdData().iterator().next();
        XParameterPeriodPrimitiveType v = new XParameterPeriodPrimitiveType(id,
                null, null);
        v.setValue("1");
        v.setStartTime(DateTimeHandling.calculateMillis("2012-02-25 12:00:00"));
        v.setEndTime(DateTimeHandling.calculateMillis("2012-02-26 00:00:00"));
        id.getPeriodValues().add(v);
        pd.setPeriod(PricingPeriod.MONTH);
        when(
                bb.bdr.loadParameterData(any(BillingInput.class),
                        any(PriceModelInput.class))).thenReturn(pd);

        // when
        BillingDetailsType doc = createBillingDataForOrganization(1, 1,
                DateTimeHandling.calculateMillis("2012-02-22 00:00:00"),
                DateTimeHandling.calculateMillis("2012-02-26 00:00:00"),
                DateTimeHandling.calculateMillis("2012-01-26 00:00:00"),
                new BillingResult(), true, Arrays.asList(sh1), "EUR");

        // then
        assertNotNull(doc);
        assertEquals(1, doc.getSubscriptions().getSubscription().size());
        org.oscm.billingservice.business.model.billingresult.PriceModelType pm = doc
                .getSubscriptions().getSubscription().get(0).getPriceModels()
                .getPriceModel().get(0);
        assertEquals(0.06896551724137931, pm.getPeriodFee().getFactor()
                .doubleValue(), ASSERT_DOUBLE_DELTA);
        assertEquals(0.0344827586206897, pm.getUserAssignmentCosts()
                .getFactor().doubleValue(), ASSERT_DOUBLE_DELTA);
        assertEquals(0.0172413793103448,
                pm.getParameters().getParameter().get(0).getPeriodFee()
                        .getFactor().doubleValue(), ASSERT_DOUBLE_DELTA);
        assertEquals(0.0, doc.getOverallCosts().getGrossAmount().doubleValue(),
                0);
    }

    /* Bug10095 */
    @Test
    public void createBillingDataForOrganization_SubscriptionBeforeBillingStartTime()
            throws Exception {
        // given

        SubscriptionHistory sh1 = new SubscriptionHistory();
        sh1.setModdate(new Date(DateTimeHandling
                .calculateMillis("2012-01-25 00:00:00")));
        sh1.setObjKey(1);
        sh1.setCutOffDay(26);
        sh1.setOrganizationObjKey(1);
        sh1.getDataContainer().setActivationDate(
                Long.valueOf(sh1.getModdate().getTime()));
        sh1.getDataContainer().setStatus(SubscriptionStatus.DEACTIVATED);
        sh1.setUserGroupObjKey(Long.valueOf(100L));

        SubscriptionHistory sh2 = new SubscriptionHistory();
        sh2.setModdate(new Date(DateTimeHandling
                .calculateMillis("2012-01-24 00:00:00")));
        sh2.setObjKey(1);
        sh2.setCutOffDay(26);
        sh2.setOrganizationObjKey(1);
        sh2.getDataContainer().setActivationDate(
                Long.valueOf(sh2.getModdate().getTime()));
        sh2.getDataContainer().setStatus(SubscriptionStatus.ACTIVE);
        sh2.setUserGroupObjKey(Long.valueOf(200L));

        pmh.setType(PriceModelType.PER_UNIT);
        pmh.setPeriod(PricingPeriod.MONTH);
        pmh.setModdate(new Date());

        XParameterData pd = new XParameterData();
        pd.getIdDataInstance("ert", ParameterType.SERVICE_PARAMETER,
                ParameterValueType.INTEGER);
        XParameterIdData id = pd.getIdData().iterator().next();
        XParameterPeriodPrimitiveType v = new XParameterPeriodPrimitiveType(id,
                null, null);
        v.setValue("1");
        v.setStartTime(DateTimeHandling.calculateMillis("2012-01-24 00:00:00"));
        v.setEndTime(DateTimeHandling.calculateMillis("2012-01-25 00:00:00"));
        id.getPeriodValues().add(v);
        pd.setPeriod(PricingPeriod.MONTH);
        when(
                bb.bdr.loadParameterData(any(BillingInput.class),
                        any(PriceModelInput.class))).thenReturn(pd);

        // when
        BillingDetailsType doc = createBillingDataForOrganization(1, 1,
                DateTimeHandling.calculateMillis("2012-01-26 00:00:00"),
                DateTimeHandling.calculateMillis("2012-02-26 00:00:00"),
                DateTimeHandling.calculateMillis("2012-01-26 00:00:00"),
                new BillingResult(), true, Arrays.asList(sh1, sh2), "EUR");

        // then
        assertNotNull(doc);
        assertEquals(1, doc.getSubscriptions().getSubscription().size());
        org.oscm.billingservice.business.model.billingresult.PriceModelType pm = doc
                .getSubscriptions().getSubscription().get(0).getPriceModels()
                .getPriceModel().get(0);
        assertEquals(BigDecimal.valueOf(1.0), pm.getPeriodFee().getFactor());
        assertEquals(1.0322D, pm.getParameters().getParameter().get(0)
                .getPeriodFee().getFactor().doubleValue(), 0.001);
    }
}


text:
package com.yougou.h5center.push.impl;

import com.yougou.h5center.push.config.base.BasePushConfig;

/**
 * @author long.yl.
 * @Date 2016/6/1
 */
public class Context {

    private PushStrategy strategy;

    //构造函数,确定推送策略
    public Context(PushStrategy strategy){
        this.strategy = strategy;
    }

    public boolean push(BasePushConfig pushConfig) throws Exception{
        return this.strategy.push(pushConfig);
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""Module for working with external libraries.

Portions of this code are adapted from MDTraj and are released under the
following license.

##############################################################################
# MDTraj is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 2.1
# of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with MDTraj. If not, see <http://www.gnu.org/licenses/>.
##############################################################################
"""
import importlib
import inspect
import os
import sys
import textwrap
import warnings
from unittest import SkipTest

from pkg_resources import resource_filename

class DelayImportError(ImportError, SkipTest):
    """Error to allow better import handling."""

    pass

MESSAGES = dict()
MESSAGES[
    "gsd"
] = """
The code at {filename}:{line_number} requires the "gsd" package

gsd can be installed with conda using:

# conda install -c conda-forge gsd
"""

MESSAGES[
    "nglview"
] = """
The code at {filename}:{line_number} requires the "nglview" package

nglview can be installed using:

# conda install -c conda-forge nglview

or

# pip install nglview
"""

MESSAGES[
    "py3Dmol"
] = """
The code at {filename}:{line_number} requires the "py3Dmol" package

py3Dmol can be installed using:

# conda install -c conda-forge py3Dmol

or

# pip install py3Dmol
"""

MESSAGES[
    "rdkit"
] = """
The code at {filename}:{line_number} requires the "rdkit" package

rdkit can be installed with conda using:

# conda install -c conda-forge rdkit

or from source following instructions at:

https://www.rdkit.org/docs/Install.html#installation-from-source
"""

MESSAGES[
    "openbabel"
] = """
The code at {filename}:{line_number} requires the "openbabel" package

openbabel can be installed with conda using:

# conda install -c conda-forge openbabel

or from source following instructions at:

# http://openbabel.org/docs/current/UseTheLibrary/PythonInstall.html
"""

MESSAGES["pybel"] = MESSAGES["openbabel"]

MESSAGES[
    "mdtraj"
] = """
The code at {filename}:{line_number} requires the "mdtraj" package
mdtraj can be installed using:
# conda install -c conda-forge mdtraj
or
# pip install mdtraj
"""

MESSAGES[
    "foyer"
] = """
The code at {filename}:{line_number} requires the "foyer" package

foyer can be installed using:

# conda install -c conda-forge foyer

or

# pip install foyer
"""

MESSAGES[
    "garnett"
] = """
The code at {filename}:{line_number} requires the "garnett" package

garnett can be installed with conda using:

# conda install -c conda-forge garnett
"""

MESSAGES[
    "pycifrw"
] = """
The code at {filename}:{line_number} requires the "pycifrw" package

pycifrw can be installed with conda using:

# conda install -c conda-forge pycifrw
"""

MESSAGES[
    "protobuf"
] = """
The code at {filename}:{line_number} requires the "protobuf" package

protobuf can be installed using:

# conda install -c conda-forge protobuf

or

# pip install protobuf
"""

def import_(module):
    """Import a module and issue a nice message to stderr if it isn't installed.

    Parameters
    ----------
    module : str
        The module you'd like to import, as a string

    Returns
    -------
    module : {module, object}
        The module object

    Examples
    --------
    >>> # the following two lines are equivalent. the difference is that the
    >>> # second will check for an ImportError and print you a very nice
    >>> # user-facing message about what's wrong (where you can install the
    >>> # module from, etc) if the import fails
    >>> import tables
    >>> tables = import_('tables')

    Notes
    -----
    The pybel/openbabel block is meant to resolve compatibility between
    openbabel 2.x and 3.0.  There may be other breaking changes but the change
    in importing them is the major one we are aware of. For details, see
    https://open-babel.readthedocs.io/en/latest/UseTheLibrary/migration.
    html#python-module
    """
    if module == "pybel":
        try:
            return importlib.import_module("openbabel.pybel")
        except ModuleNotFoundError:
            pass
        try:
            pybel = importlib.import_module("pybel")
            msg = (
                "openbabel 2.0 detected and will be dropped in a future "
                "release. Consider upgrading to 3.x."
            )
            warnings.warn(msg, DeprecationWarning)
            return pybel
        except ModuleNotFoundError:
            pass
    if module == "openbabel":
        try:
            return importlib.import_module("openbabel.openbabel")
        except ModuleNotFoundError:
            pass
        try:
            openbabel = importlib.import_module("openbabel")
            msg = (
                "openbabel 2.0 detected and will be dropped in a future "
                "release. Consider upgrading to 3.x."
            )
            warnings.warn(msg, DeprecationWarning)
            return pybel
        except ModuleNotFoundError:
            pass
    try:
        return importlib.import_module(module)
    except ImportError as e:
        try:
            message = MESSAGES[module]
        except KeyError:
            message = (
                "The code at {filename}:{line_number} requires the "
                f"{module} package"
            )
            e = ImportError(f"No module named {module}")

        (
            frame,
            filename,
            line_number,
            function_name,
            lines,
            index,
        ) = inspect.getouterframes(inspect.currentframe())[1]

        m = message.format(
            filename=os.path.basename(filename), line_number=line_number
        )
        m = textwrap.dedent(m)

        bar = (
            "\033[91m"
            + "#" * max(len(line) for line in m.split(os.linesep))
            + "\033[0m"
        )

        print("", file=sys.stderr)
        print(bar, file=sys.stderr)
        print(m, file=sys.stderr)
        print(bar, file=sys.stderr)
        raise DelayImportError(m)

try:
    import intermol

    has_intermol = True
    del intermol
except ImportError:
    has_intermol = False

try:
    import gsd

    has_gsd = True
    del gsd
except ImportError:
    has_gsd = False

try:
    from openbabel import openbabel

    has_openbabel = True
    del openbabel
except ImportError:
    has_openbabel = False

try:
    import mdtraj

    has_mdtraj = True
    del mdtraj
except ImportError:
    has_mdtraj = False
try:
    import foyer

    has_foyer = True
    del foyer
except ImportError:
    has_foyer = False

try:
    import networkx

    has_networkx = True
    del networkx
except ImportError:
    has_networkx = False

try:
    import hoomd

    has_hoomd = True
    del hoomd
except ImportError:
    has_hoomd = False

try:
    import py3Dmol

    has_py3Dmol = True
    del py3Dmol
except ImportError:
    has_py3Dmol = False

try:
    from google import protobuf

    has_protobuf = True
    del protobuf
except ImportError:
    has_protobuf = False

try:
    import garnett

    has_garnett = True
    del garnett
except ImportError:
    has_garnett = False

try:
    import CifFile

    has_pycifrw = True
    del CifFile
except ImportError:
    has_pycifrw = False

try:
    import rdkit

    has_rdkit = True
    del rdkit
except ImportError:
    has_rdkit = False

def get_fn(name):
    """Get the full path to one of the reference files shipped for utils.

    In the source distribution, these files are in ``mbuild/utils/reference``,
    but on installation, they're moved to somewhere in the user's python
    site-packages directory.

    Parameters
    ----------
    name : str
        Name of the file to load (with respect to the reference/ folder).
    """
    fn = resource_filename("mbuild", os.path.join("utils", "reference", name))
    if not os.path.exists(fn):
        raise IOError("Sorry! {} does not exists.".format(fn))
    return fn

def run_from_ipython():
    """Get whether python is being run interactively."""
    try:
        __IPYTHON__
        return True
    except NameError:
        return False


text:
#ifndef _NORMALIZE_BOUNDS_TACTIC_H_
#define _NORMALIZE_BOUNDS_TACTIC_H_

#include"params.h"
class ast_manager;
class tactic;

tactic * mk_normalize_bounds_tactic(ast_manager & m, params_ref const & p = params_ref());

/*
  ADD_TACTIC("normalize-bounds", "replace a variable x with lower bound k <= x with x' = x - k.", "mk_normalize_bounds_tactic(m, p)")
*/

#endif


text:
<?php

class Test
{
    /**
     * @param \MyClass $class
     * @param string   $string
     * @param int      $int
     * @param int      $int2
     * @param bool     $bool
     * @param bool     $bool2
     * @param float    $float
     *
     * @return int
     */
    public function myFunction(MyClass $class, string $string, int $int, integer $int2, bool $bool, boolean $bool2, float $float)
    {
        //HI I AM A COMMENT
        return 5;
    }
}


text:
/***********************************************************************
    created:    Sun, 6th April 2014
    author:     Lukas E Meindl
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#ifndef _CEGUIDirect3D11ShaderWrapper_h_
#define _CEGUIDirect3D11ShaderWrapper_h_

#include "CEGUI/RendererModules/Direct3D11/Renderer.h"
#include "CEGUI/RendererModules/Direct3D11/Shader.h"
#include "CEGUI/ShaderWrapper.h"
#include "CEGUI/ShaderParameterBindings.h"
#include <string>

#include "D3D11.h"

#if defined(_MSC_VER)
#   pragma warning(push)
#   pragma warning(disable : 4251)
#endif

// Start of CEGUI namespace section
namespace CEGUI
{
class ShaderParameterBindings;
class ShaderParameter;
class Direct3D11Shader;

//----------------------------------------------------------------------------//
struct Direct3D11ParamDesc
{
    UINT d_boundLocation;
    UINT d_boundSize;
    ShaderType d_shaderType;
    ShaderParamType d_shaderParamType;
};

//----------------------------------------------------------------------------//
class D3D11_GUIRENDERER_API Direct3D11ShaderWrapper : public ShaderWrapper
{
public:
    Direct3D11ShaderWrapper(Direct3D11ShaderPtr&& shader, Direct3D11Renderer* renderer);

    ~Direct3D11ShaderWrapper();

    //Implementation of ShaderWrapper interface
    void prepareForRendering(const ShaderParameterBindings* shaderParameterBindings);

    //! Adds a shader uniform variable to the list of variables
    void addUniformVariable(const std::string& variableName, ShaderType shaderType, ShaderParamType paramType);

    //! Creates a per-object buffer for a parameter
    void createPerObjectBuffer(ShaderType shaderType);

    //! Returns the vertex shader buffer pointer
    void* getVertShaderBufferPointer() const;
    //! Returns the vertex shader buffer size
    SIZE_T getVertShaderBufferSize() const;

protected:
    //! Prepare the uniform variable mapping
    void prepareUniformVariableMapping(unsigned char*& resourceDataVS, unsigned char*& resourceDataPS);
    //! Finish the uniform variable mapping
    void finishUniformVariableMapping();

    //! The D3D DeviceContext
    ID3D11DeviceContext* d_deviceContext;
    //! The D3D Device
    ID3D11Device* d_device;

    //! The D3DBuffer used to update the uniform variables of the vertex shader
    ID3D11Buffer* d_perObjectUniformVarBufferVert;
    //! The D3DBuffer used to update the uniform variables of the pixel shader
    ID3D11Buffer* d_perObjectUniformVarBufferPixel;

    //! The underlying HLSL shader program, consisting of a vertex and fragment shader, that this class wraps the access to
    Direct3D11ShaderPtr d_shader;

    //! A map of parameter names and the related constant variables
    std::map<std::string, Direct3D11ParamDesc> d_uniformVariables;
    //! Last states of the set shader parameters
    std::map<std::string, ShaderParameter*> d_shaderParameterStates;
};

}

#endif


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "completed_projects".
 *
 * @property integer $id
 * @property string $title
 * @property string $text
 * @property string $date
 * @property string $date_complete
 * @property integer $client_id
 * @property integer $user_id
 * @property integer $status
 * @property string $technologies
 * @property integer $days
 * @property integer $hours
 * @property string $comment
 *
 * @property User $user
 * @property User $client
 */
class CompletedProjects extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'completed_projects';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
//            [['title', 'text', 'date', 'status'], 'required'],
            [['text', 'technologies', 'comment'], 'string'],
            [['date', 'date_complete'], 'safe'],
            [['client_id', 'user_id', 'manager_id', 'qa_id', 'status', 'days', 'hours'], 'integer'],
            [['title'], 'string', 'max' => 255],
            [['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
            [['client_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['client_id' => 'id']],
            [['manager_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['manager_id' => 'id']],
            [['qa_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['qa_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Заголовок',
            'text' => 'Описание',
            'date' => 'Дата создания',
            'date_complete' => 'Дата завершения',
            'client_id' => 'Клиент',
            'user_id' => 'Пользователь',
            'manager_id' => 'Менеджер',
            'qa_id' => 'Тестировщик',
            'status' => 'Статус',
            'technologies' => 'Технологии',
            'days' => 'Дней работы',
            'hours' => 'Часов работы',
            'comment' => 'Отзыв',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getClient()
    {
        return $this->hasOne(User::className(), ['id' => 'client_id']);
    }

    public function getManager()
    {
        return $this->hasOne(User::className(), ['id' => 'manager_id']);
    }

    public function getQa()
    {
        return $this->hasOne(User::className(), ['id' => 'qa_id']);
    }

    public function getJoinClientName()
    {
        if (isset($this->client->surname) && isset($this->client->name)){
            return $this->client->surname . ' ' . $this->client->name;
        } else { return ''; }
    }

    public function getJoinDeveloperName()
    {
        if (isset($this->user->surname) && isset($this->user->name)){
            return $this->user->surname . ' ' . $this->user->name;
        } else { return ''; }
    }

    public function getJoinManagerName()
    {
        if (isset($this->manager->surname) && isset($this->manager->name))
        {
            return $this->manager->surname . ' ' . $this->manager->name;
        } else { return ''; }
    }

    public function getJoinQaName()
    {
        if (isset($this->qa->surname) && isset($this->qa->name)){
            return $this->qa->surname . ' ' . $this->qa->name;
        } else { return ''; }
    }

    //Подсчет количества выполненных проектов
    public function countCompletedProjects()
    {
        return CompletedProjects::find()->count();
    }

}


text:
@implementation SMAUpdateResponse

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns:xi="http://www.w3.org/2001/XInclude">
	<product id="bigJack">
		<price locale="US">4.20</price>
		<price>4.35</price>
		<name>Big Jack</name>
		<description locale="en">Hamburger: two 1.5 oz 100% beef patties,
			American cheese, iceberg lettuce, pickles, and onions,
			served in a three part sesame seed bun.
		</description>
		<description locale="fr">Hamburger incluant deux steaks
			de bœuf haché de 40 grammes, laitue,
			cheddar fondu, tranches de cornichons et d'oignons, le tout dans un pain au sésame.
		</description>
	</product>
	<product id="largeFries">
		<price locale="US">1.45</price>
		<price>1.50</price>
		<name locale="en_US">Liberty Fries - Large</name>
		<name locale="en">French Fries - Large</name>
		<name locale="fr">Frites - grand format</name>
		<description locale="en_US">Crispy Liberty fries.</description>
		<description locale="en">Crispy French fries.</description>
		<description locale="fr">Frites croustillantes.</description>
	</product>
	<product id="largeCola">
		<price locale="US">1.25</price>
		<price>1.30</price>
		<name locale="en">Cola Cola - Large</name>
		<name locale="fr">Cola Cola - grand format</name>
		<description locale="en">The original, refreshing ice-cold taste you love.</description>
		<description locale="fr">Le goût authentique, rafraîchissant que vous adorez.</description>
	</product>
	<xi:include href="XIncludeTest.jaxb.bigJackTrio.xml"/>
</catalog>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

	<title>caIntegrator: Refine Query</title>
	<LINK href="bigStyle.css" rel="stylesheet" type="text/css">

<form name="form1" action="#" method="get">

	Home >
	            Build Query >
                Refine Query >
                Select Presentation >
                Generate Report

Please refine your query below

Group Your Queries

					Query Name
					Not
					(
					Query Description
					)
					and/or

						<select id="1" onchange="javascript:showName(this,document.getElementById('q1'));">
							<option> </option>
							<option value="Fold change: 2x ; Gene: EGFR...">EGFR up-regulation</option>
							<option value="Chromosome abberation status: Amplified  Gene: EGFR...">EGFR amplification</option>
							<option value="Gene Name: *  Chromosome abberation status: Amplified  Map Location: 7P11.2 ...">other genes in region</option>
						</select>

						   Refine [?]

						<input type="checkbox" class="radio" name="not">

						<select class="paren">
							<option> </option>
							<option> ( </option>
						</select>

						<select class="paren">
							<option> </option>
							<option> ) </option>
						</select>

						<select>
							<option> </option>
							<option>and</option>
							<option>or</option>
						</select>

						<select id = "2" onchange="javascript:showName(this, document.getElementById('q2'));">
							<option> </option>
							<option value="Fold change: 2x ; Gene: EGFR...">EGFR up-regulation</option>
							<option value="Chromosome abberation status: Amplified ; Gene: EGFR...">EGFR amplification</option>
							<option value="Gene Name: * ; Chromosome abberation status: Amplified ; Map Location: 7P11.2 ...">other genes in region</option>
						</select>

						   Refine [?]

						<input type="checkbox" class="radio" name="not">

						<select class="paren">
							<option> </option>
							<option> ( </option>
						</select>

						<select class="paren">
							<option> </option>
							<option> ) </option>
						</select>

						<select>
							<option> </option>
							<option>and</option>
							<option>or</option>
						</select>

						<select id ="3" onchange="javascript:showName(this, document.getElementById('q3'));">
							<option> </option>
							<option value="Fold change: 2x ; Gene: EGFR...">EGFR up-regulation</option>
							<option value="Chromosome abberation status: Amplified ; Gene: EGFR...">EGFR amplification</option>
							<option value="Gene: * ; Map Location: 7P11.2 ...">other genes in region</option>
						</select>

						   Refine [?]

						<input type="checkbox" class="radio" name="not">

						<select class="paren">
							<option> </option>
							<option> ( </option>
						</select>

						<select class="paren">
							<option> </option>
							<option> ) </option>
						</select>

						<select>
							<option> </option>
							<option>and</option>
							<option>or</option>
						</select>

			[add more rows]

				<input type="reset" value="reset query" class="xbutton">
				  <input type="button" class="xbutton" value="validate query" onclick="javascript:setQuery('Query:\n(EGFR up-regulation and EGFR amplification) and Other Genes in region\n\nValidation Results:\nThis is a valid query!');" onmouseover="return overlib('Based on your selections above, your query will appear in the box below.  Please verify its accuracy.  Click \'Reset\' to clear the query.', CAPTION, 'Help');" onmouseout="return nd();">

					<textarea style="width:700px; height:75px;" name="query"></textarea>

				<input type="button" class="xbutton" value="back" onclick="javascript:history.back();">
				<input type="button" class="xbutton" value="save and continue" onclick="javascript:location.href='present.html';">

</form>


text:
<config
    xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
    xmlns='http://www.ehcache.org/v3'
    xmlns:mnm='http://www.ehcache.org/v3/management'
    xsi:schemaLocation="http://www.ehcache.org/v3 ../../../../xml/src/main/resources/ehcache-core.xsd
                        http://www.ehcache.org/v3/management ../../main/resources/ehcache-management-ext.xsd">

  <service>
    <mnm:management cache-manager-alias="my-cache-manager-name">
      <mnm:tags>
        <mnm:tag>webapp-name</mnm:tag>
        <mnm:tag>jboss-1</mnm:tag>
        <mnm:tag>server-node-1</mnm:tag>
      </mnm:tags>
    </mnm:management>
  </service>

  <cache alias="my-cache-1">
    <key-type>java.lang.String</key-type>
    <value-type>java.lang.String</value-type>
    <heap unit="entries">20</heap>
  </cache>

</config>


text:
using Ko.Navigation.CefGlue.Tests.Infra;
using Tests.Universal.NavigationTests;
using Xunit;
using Xunit.Abstractions;

namespace Ko.Navigation.CefGlue.Tests
{
    [Collection("Cef Window Integrated")]
    public class DoubleNavigation_Animation_Ko_Cef_Tests : DoubleNavigation_AnimationTests
    {
        public DoubleNavigation_Animation_Ko_Cef_Tests(CefGlueKoContext context, ITestOutputHelper testOutputHelper) :
            base(context, testOutputHelper)
        {
        }
    }
}


text:
package org.sakaiproject.content.impl.serialize.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;

import org.sakaiproject.content.api.ResourceType;
import org.sakaiproject.content.api.GroupAwareEntity.AccessMode;
import org.sakaiproject.content.impl.serialize.api.SerializableCollectionAccess;
import org.sakaiproject.entity.api.serialize.EntityParseException;
import org.sakaiproject.entity.api.serialize.EntitySerializer;
import org.sakaiproject.entity.api.serialize.SerializableEntity;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.api.TimeService;
import org.sakaiproject.util.ByteStorageConversion;
import org.sakaiproject.util.serialize.Type1BaseResourcePropertiesSerializer;

/**
 * <pre>
 *      Serializes ContentCollections using a Type1 block serializer, outputs a string with
 *      char in the byte range 0-255 that can be saved in a CBLOB or BLOB or on file.
 *      These MUST be saved as UTF8.
 *      If you need to modify this class think very carefully about what data might be in production databases.
 *      DO NOT add new fields to existing blocks
 *      DO NOT remove fields from blocks.
 *      If you need more structure add new unique blocks.
 *      If you need to change the structure, create a Type2 class and change the Type number so that type 1
 *      serializations continue to work.
 *
 *      The general structure of a serialization is
 *      char 1-6 : BLOB_ID identifying the blob.
 *      First Int: Type Number (int)
 *      Next Int: Block number identifying block
 *      The contents and length of the block is determined by the serailizer writing the block
 *      When the serializer has finished writing the block the next int should be the next block number.
 *
 *      BLOB_ID's MUST be unique over all BLOBS.
 *      TYPE Numbers MUST be unique within BLOBS of the same type
 *      BLOCK Numbers MUST be unique within Types, but SHOULD be unique within BLOBS of the same type.
 *      For variable lenght data, always serialize the length before the data. (eg number of elements, size of byte[])
 *      For UTF Strings that are likely to be over 64K, you MUST serialize as lenght:UTF8byte[] as writeUTF will only
 *      handle 64K
 *
 *      This structure is shared with the Type1ResoruceSerializer
 *      BLOCK1
 *      General Attributes
 *      BLOCK2
 *      release and retract dates
 *      BLOCK3 (varialble)
 *      Groups
 *      BLOCK4
 *      Properties (managed by a seperate serializer
 *      BLOCK_END
 * </pre>
 *
 * @author ieb
 */
public class Type1BaseContentCollectionSerializer implements EntitySerializer
{
	public static final String BLOB_ID = "CHSBCE";

	private static final byte[] BYTE_BLOB_ID = new byte[] { 'C', 'H', 'S', 'B', 'C', 'E' };

	// These are block markers in the serialization, DO NOT reuse,
	// create a new type or new block.
	// If you re-use you will have to provide data migration
	public static final int TYPE1 = 1;

	public static final int BLOCK1 = 10;

	public static final int BLOCK2 = 11;

	public static final int BLOCK3 = 12;

	public static final int BLOCK4 = 13;

	public static final int BLOCK_END = 2;

	private Type1BaseResourcePropertiesSerializer baseResourcePropertiesSerializer = new Type1BaseResourcePropertiesSerializer();

	private TimeService timeService;

	/**
	 * @deprecated
	 * @param se
	 * @param serialized
	 * @throws EntityParseException
	 */
	private void parseString(SerializableEntity se, String serialized)
			throws EntityParseException
	{

		if (!(se instanceof SerializableCollectionAccess))
		{
			throw new EntityParseException("Cant serialize " + se
					+ " as it is not a SerializableCollection ");
		}
		SerializableCollectionAccess sc = (SerializableCollectionAccess) se;
		try
		{

			if (!serialized.startsWith(BLOB_ID))
			{
				throw new EntityParseException(
						"Data Block does not belong to this serializer got ["
								+ serialized.substring(0, BLOB_ID.length())
								+ "] expected [" + BLOB_ID + "]");
			}
			char[] cbuf = serialized.toCharArray();
			byte[] sb = new byte[cbuf.length - BLOB_ID.length()];

			ByteStorageConversion.toByte(cbuf, BLOB_ID.length(), sb, 0, sb.length);
			ByteArrayInputStream baos = new ByteArrayInputStream(sb);
			DataInputStream ds = new DataInputStream(baos);
			doParse(sc, ds);
		}
		catch (EntityParseException epe)
		{
			throw epe;
		}
		catch (Exception ex)
		{
			throw new EntityParseException("Failed to parse entity", ex);
		}

	}

	public void parse(SerializableEntity se, byte[] buffer)
			throws EntityParseException
	{
		if (!(se instanceof SerializableCollectionAccess))
		{
			throw new EntityParseException("Cant serialize " + se
					+ " as it is not a SerializableCollection ");
		}
		SerializableCollectionAccess sc = (SerializableCollectionAccess) se;
		for (int i = 0; i < BYTE_BLOB_ID.length; i++)
		{
			if (buffer[i] != BYTE_BLOB_ID[i])
			{
				throw new EntityParseException(
						"Data Block does not belong to this serializer got ["
								+ new String(buffer,0,BYTE_BLOB_ID.length) + "] expected [" + new String(BYTE_BLOB_ID) + "]");
			}
		}
		try
		{
			ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
			DataInputStream ds = new DataInputStream(bais);
			byte[] signature = new byte[BYTE_BLOB_ID.length];
			ds.read(signature);
			doParse(sc, ds);
		}
		catch (EntityParseException epe)
		{
			throw epe;
		}
		catch (Exception ex)
		{
			throw new EntityParseException("Failed to parse entity", ex);
		}

	}

	/**
	 * @deprecated
	 * @param se
	 * @return
	 * @throws EntityParseException
	 */
	private String serializeString(SerializableEntity se) throws EntityParseException
	{
		if (!(se instanceof SerializableCollectionAccess))
		{
			throw new EntityParseException("Cant serialize " + se
					+ " as it is not a SerializableCollectionAccess ");
		}
		SerializableCollectionAccess sc = (SerializableCollectionAccess) se;

		try
		{
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			DataOutputStream ds = new DataOutputStream(baos);

			doSerialize(sc, ds);

			ds.flush();
			baos.flush();
			byte[] op = baos.toByteArray();
			char[] opc = new char[op.length + BLOB_ID.length()];
			int bid = BLOB_ID.length();

			ByteStorageConversion.toChar(op, 0, opc, bid, op.length);

			for (int i = 0; i < bid; i++)
			{
				opc[i] = BLOB_ID.charAt(i);
			}
			return new String(opc);
		}
		catch (Exception ex)
		{
			throw new EntityParseException("Failed to serialize entity ", ex);
		}
	}

	public byte[] serialize(SerializableEntity se)
			throws EntityParseException
	{
		if (!(se instanceof SerializableCollectionAccess))
		{
			throw new EntityParseException("Cant serialize " + se
					+ " as it is not a SerializableCollectionAccess ");
		}
		SerializableCollectionAccess sc = (SerializableCollectionAccess) se;
		try
		{
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			DataOutputStream ds = new DataOutputStream(baos);
			ds.write(BYTE_BLOB_ID);
			doSerialize(sc, ds);
			ds.flush();
			baos.flush();
			byte[] b = baos.toByteArray();
			baos.close();
			return b;
		}
		catch (Exception ex)
		{
			throw new EntityParseException("Failed to serialize entity ", ex);
		}

	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.sakaiproject.entity.api.serialize.EntitySerializer#accept(java.lang.String)
	 */
	public boolean accept(byte[] buffer)
	{
		if ( buffer == null || buffer.length < BYTE_BLOB_ID.length ) {
			return false;
		}
		for (int i = 0; i < BYTE_BLOB_ID.length; i++)
		{
			if (buffer[i] != BYTE_BLOB_ID[i])
			{
				return false;
			}
		}
		return true;
	}

	/**
	 * @return the timeService
	 */
	public TimeService getTimeService()
	{
		return timeService;
	}

	/**
	 * @param timeService
	 *        the timeService to set
	 */
	public void setTimeService(TimeService timeService)
	{
		this.timeService = timeService;
	}

	private void doParse(SerializableCollectionAccess sc, DataInputStream ds)
			throws EntityParseException, IOException
	{

		String id = null;
		AccessMode access = AccessMode.INHERITED;
		boolean hidden = false;
		String resourceType = ResourceType.TYPE_FOLDER;
		Time releaseDate = null;
		Time retractDate = null;
		Collection<String> groups = new Vector<String>();

		int type = ds.readInt();
		if (type == TYPE1)
		{
			boolean finished = false;
			while (!finished)
			{
				int block = ds.readInt();
				switch (block)
				{
					case BLOCK1:
					{
						id = ds.readUTF();
						if (!ResourceType.TYPE_FOLDER.equals(ds.readUTF()))
						{
							throw new EntityParseException("Data block is not of tye "
									+ ResourceType.TYPE_FOLDER);
						}
						access = AccessMode.fromString(ds.readUTF());
						if (access == null || AccessMode.SITE == access)
						{
							access = AccessMode.INHERITED;
						}
						hidden = ds.readBoolean();

						resourceType = ResourceType.TYPE_FOLDER;

					}
						break;
					case BLOCK2:
					{
						long rd = ds.readLong();
						if (rd != -1)
						{
							releaseDate = timeService.newTime(rd);
						}
						else
						{
							releaseDate = null;
						}
						rd = ds.readLong();
						if (rd != -1)
						{
							retractDate = timeService.newTime(rd);
						}
						else
						{
							retractDate = null;
						}
					}
						break;
					case BLOCK3:
						int sz = ds.readInt();
						for (int i = 0; i < sz; i++)
						{
							groups.add(ds.readUTF());
						}
						if ( sz > 0 )
						{
							access = AccessMode.GROUPED;
						}
						break;
					case BLOCK4:
						baseResourcePropertiesSerializer.parse(sc
								.getSerializableProperties(), ds);
						break;
					case BLOCK_END:
						finished = true;
						break;
				}
			}
		}
		else
		{
			throw new EntityParseException("Unrecognised Record Type " + type);
		}
		sc.setSerializableId(id);
		sc.setSerializableAccess(access);
		sc.setSerializableHidden(hidden);
		sc.setSerializableResourceType(resourceType);
		sc.setSerializableReleaseDate(releaseDate);
		sc.setSerializableRetractDate(retractDate);
		sc.setSerializableGroups(groups);

	}

	private void doSerialize(SerializableCollectionAccess sc, DataOutputStream ds)
			throws EntityParseException, IOException
	{
		String id = sc.getSerializableId();
		boolean hidden = sc.getSerializableHidden();
		AccessMode access = sc.getSerializableAccess();
		Time releaseDate = sc.getSerializableReleaseDate();
		Time retractDate = sc.getSerializableRetractDate();
		Collection<String> groups = sc.getSerializableGroup();

		ds.writeInt(TYPE1);
		ds.writeInt(BLOCK1);
		ds.writeUTF(id);
		ds.writeUTF(ResourceType.TYPE_FOLDER);

		if (access == null || AccessMode.SITE == access)
		{
			access = AccessMode.INHERITED;
		}

		ds.writeUTF(access.toString());
		ds.writeBoolean(hidden);
		ds.writeInt(BLOCK2);
		if (!hidden && releaseDate != null)
		{
			ds.writeLong(releaseDate.getTime());
		}
		else
		{
			ds.writeLong(-1);
		}
		if (!hidden && retractDate != null)
		{
			ds.writeLong(retractDate.getTime());
		}
		else
		{
			ds.writeLong(-1);
		}
		if (groups != null)
		{
			ds.writeInt(BLOCK3);
			ds.writeInt(groups.size());
			for (Iterator igroup = groups.iterator(); igroup.hasNext();)
			{
				String groupRef = (String) igroup.next();
				ds.writeUTF(groupRef);
			}
		}

		ds.writeInt(BLOCK4);
		baseResourcePropertiesSerializer.serialize(sc.getSerializableProperties(), ds);
		ds.writeInt(BLOCK_END);

	}

}


text:
package records

import (
	"fmt"
	"net"
	"regexp"
	"strconv"
	"strings"
)

var dnsValidationRegex = regexp.MustCompile(`^[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*$`)

func validateEnabledServices(c *Config) error {
	if !c.DNSOn && !c.HTTPOn {
		return fmt.Errorf("Either DNS or HTTP server should be on")
	}
	if len(c.Masters) == 0 && c.Zk == "" {
		return fmt.Errorf("Specify Mesos masters or Zookeeper in config.json")
	}
	return nil
}

// validateMasters checks that each master in the list is a properly formatted host:port or IP:port pair.
// duplicate masters in the list are not allowed.
// returns nil if the masters list is empty, or else all masters in the list are valid.
func validateMasters(ms []string) error {
	if err := validateUniqueStrings(ms, normalizeMaster); err != nil {
		return fmt.Errorf("Error validating masters: %v", err)
	}
	return nil
}

func normalizeMaster(hostPort string) (string, error) {
	host, port, err := net.SplitHostPort(hostPort)
	if err != nil {
		return "", fmt.Errorf("Illegal host:port specified: %v. Error: %v", hostPort, err)
	}
	if ip := net.ParseIP(host); ip != nil {
		//TODO(jdef) distinguish between intended hostnames and invalid ip addresses
		host = ip.String()
	}
	if !validPortString(port) {
		return "", fmt.Errorf("Illegal host:port specified: %v", hostPort)
	}
	return net.JoinHostPort(host, port), nil
}

// validateResolvers checks that each resolver in the list is a properly formatted IP or IP:port pair.
// duplicate resolvers in the list are not allowed.
// returns nil if the resolver list is empty, or else all resolvers in the list are valid.
func validateResolvers(rs []string) error {
	if err := validateUniqueStrings(rs, normalizeResolver); err != nil {
		return fmt.Errorf("Error validating resolvers: %v", err)
	}
	return nil
}

func validateDomainName(domain string) error {
	if !dnsValidationRegex.MatchString(domain) {
		return fmt.Errorf("Invalid domain name: %s", domain)
	}
	return nil
}

func validateZoneResolvers(zrs map[string][]string, mesosDomain string) (
	err error) {

	allDomains := make([]string, 0, len(zrs)+1)

	for domain, rs := range zrs {
		if len(rs) == 0 {
			return fmt.Errorf("ZoneResolver %v is empty", domain)
		}
		err = validateDomainName(domain)
		if err != nil {
			return err
		}

		err = validateResolvers(rs)
		if err != nil {
			return
		}
		if domain == mesosDomain {
			return fmt.Errorf("Can't specify ZoneResolver for Mesos domain (%v)",
				mesosDomain)
		}
		allDomains = append(allDomains, "."+domain)
	}
	allDomains = append(allDomains, "."+mesosDomain)
	for _, a := range allDomains {
		for _, b := range allDomains {
			if (a != b) &&
				strings.HasSuffix(a, b) {
				return fmt.Errorf("Ambiguous zone resolvers: %v is masked by %v",
					a, b)
			}
		}
	}
	return
}

func normalizeResolver(hostPort string) (string, error) {
	host, port, err := net.SplitHostPort(hostPort)
	if err != nil {
		host = hostPort
		port = "53"
	}
	if ip := net.ParseIP(host); ip != nil {
		host = ip.String()
	} else {
		return "", fmt.Errorf("Illegal ip specified: %v", host)
	}

	if !validPortString(port) {
		return "", fmt.Errorf("Illegal host:port specified: %v", hostPort)
	}
	return net.JoinHostPort(host, port), nil
}

// validateUniqueStrings runs a normalize function on each string in a list and
// retuns an error if any duplicates are found.
func validateUniqueStrings(strings []string, normalize func(string) (string, error)) error {
	valid := make(map[string]struct{}, len(strings))
	for _, str := range strings {
		normalized, err := normalize(str)
		if err != nil {
			return err
		}
		if _, found := valid[normalized]; found {
			return fmt.Errorf("Duplicate found: %v", str)
		}
		valid[normalized] = struct{}{}
	}
	return nil
}

// validateIPSources checks validity of ip sources
func validateIPSources(srcs []string) error {
	if len(srcs) == 0 {
		return fmt.Errorf("empty ip sources")
	}
	if len(srcs) != len(unique(srcs)) {
		return fmt.Errorf("duplicate ip source specified")
	}
	for _, src := range srcs {
		switch src {
		case "host", "docker", "mesos", "netinfo":
		default:
			return fmt.Errorf("invalid ip source %q", src)
		}
	}

	return nil
}

// validPortString retuns true if the given port string is
// an integer between 1 and 65535, false otherwise.
func validPortString(portString string) bool {
	port, err := strconv.Atoi(portString)
	return err == nil && port > 0 && port <= 65535
}


text:
/**
 *
 Global access to configuration by {@link com.flexdms.flexims.config.Configs}

 *
Expose Configuration for client to Client by listening for {@link com.flexdms.flexims.resource.GlobalJsContext}

 *
Maintain Configs integrity by listening for Entity modification event for {@link com.flexdms.flexims.config.ConfigItem}

 *
Integrate Config as a Config Source for DeltaSpkie

 */
package com.flexdms.flexims.config;


text:
/**
 * created by Maxim Orlov on 18 Nov 2014
 */
package logic2;

public class MakeBricks {
	public boolean makeBricks(int small, int big, int goal) {
		if (goal > big * 5 + small) {
			return false;
		}

		if (goal % 5 > small) {
			return false;
		}

		return true;
	}
}


text:
<?php

/**
 *      [Discuz!] (C)2001-2099 Comsenz Inc.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      $Id: table_portal_article_related.php 27833 2012-02-15 08:04:51Z zhangguosheng $
 */

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

class table_portal_article_related extends discuz_table
{
	public function __construct() {

		$this->_table = 'portal_article_related';
		$this->_pk    = 'aid';

		parent::__construct();
	}

	public function delete_by_aid_raid($aid, $raid = null) {
		return ($aid = dintval($aid, true)) ? DB::delete($this->_table, DB::field('aid', $aid).($raid = dintval($raid) ? ' OR '.DB::field('raid', $raid) : '')) : false;
	}

	public function insert_batch($aid, $list) {
		$replaces = array();
		if(($aid = dintval($aid))) {
			$displayorder = 0;
			unset($list[$aid]);
			foreach($list as $value) {
				if(($value['aid'] = dintval($value['aid']))) {
					$replaces[] = "('$aid', '$value[aid]', '$displayorder')";
					$replaces[] = "('$value[aid]', '$aid', '0')";
					$displayorder++;
				}
			}
		}
		if($replaces) {
			DB::query('REPLACE INTO '.DB::table($this->_table).' (aid,raid,displayorder) VALUES '.implode(',', $replaces));
		}
	}

	public function fetch_all_by_aid($aid) {
		return ($aid = dintval($aid)) ? DB::fetch_all('SELECT * FROM %t WHERE aid=%d ORDER BY displayorder', array($this->_table, $aid), 'raid') : array();
	}
}

?>


text:
package com.amazonaws.services.ram.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.ram.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * ResourceShareAssociation JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ResourceShareAssociationJsonUnmarshaller implements Unmarshaller<ResourceShareAssociation, JsonUnmarshallerContext> {

    public ResourceShareAssociation unmarshall(JsonUnmarshallerContext context) throws Exception {
        ResourceShareAssociation resourceShareAssociation = new ResourceShareAssociation();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("resourceShareArn", targetDepth)) {
                    context.nextToken();
                    resourceShareAssociation.setResourceShareArn(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("resourceShareName", targetDepth)) {
                    context.nextToken();
                    resourceShareAssociation.setResourceShareName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("associatedEntity", targetDepth)) {
                    context.nextToken();
                    resourceShareAssociation.setAssociatedEntity(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("associationType", targetDepth)) {
                    context.nextToken();
                    resourceShareAssociation.setAssociationType(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("status", targetDepth)) {
                    context.nextToken();
                    resourceShareAssociation.setStatus(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("statusMessage", targetDepth)) {
                    context.nextToken();
                    resourceShareAssociation.setStatusMessage(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("creationTime", targetDepth)) {
                    context.nextToken();
                    resourceShareAssociation.setCreationTime(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
                }
                if (context.testExpression("lastUpdatedTime", targetDepth)) {
                    context.nextToken();
                    resourceShareAssociation.setLastUpdatedTime(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
                }
                if (context.testExpression("external", targetDepth)) {
                    context.nextToken();
                    resourceShareAssociation.setExternal(context.getUnmarshaller(Boolean.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return resourceShareAssociation;
    }

    private static ResourceShareAssociationJsonUnmarshaller instance;

    public static ResourceShareAssociationJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new ResourceShareAssociationJsonUnmarshaller();
        return instance;
    }
}


text:
{% extends 'BDEShowcase::main-layout.html.twig'%}
	{%block body%}

 Faire    des    rencontres

 La     <acronym title="Maison Des élèves">MDE</acronym>,     le     coeur     de     la     vie     etudiante

		A l'EMN on ne s'arrête jamais et on est toujours sûr de rencontrer quelqu'un à la MDE (prononcer "meudeu") pour une partie de billard
		de babyfoot ou même des sports plus exotiques comme le bière-pong. Et tout ça avec des bières à un prix raisonnable à portée de main au bar
		des élèves fraîchement pimpé: j'ai nommé le Traquenard.

		C'est également la bas que seront organisées de nombreuses soirées et ça commence dès l'intégration! Soirée mousse, sauvage, super-héros etc..
		sortez simplement votre plus beau sourire et déguisements et notre équipe technique se charge de vous faire passer une bonne soirée!

		Enfin, plus sérieusement c'est aussi là bas que se trouvent les différents bureaux d'élèves ou les salles allouées aux associations.
		On y trouve également le bureau de Mr. Salmon et des autres employés qui peuvent vous aider si vous avez des questions à propos des logements.

		En bref, pour toutes ces raisons et bien d'autres, la MDE reste le lieu incontournable de l'école et il faut la laisser propre.

 L'integration

 Les     Events

 Le Gala

 Le Cartel

 Les    Campagnes,    un    moment    fort

 S'impliquer

 Devenir délégué

 Les associations

 A toi d'innover!

					En plus de tout de nombreux événements exceptionnels sont proposés tout au long de l'année: concours

	{%endblock%}


text:
package visualiser;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.border.EtchedBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Visualiser {
	private Container container;

	private VisualisationPanel vp;

	private JPanel infoPanel;
	private JLabel infoLabel;

	private JMenuBar menuBar;
	private JMenu fileMenu;
	private JMenuItem loadProblemItem, loadSolutionItem, exitItem; // assumeDirectSolutionItem
	private JMenu animationMenu;
	private JMenuItem initialiseItem, playPauseItem, stopItem;
	private JMenu displayMenu;
	private JMenuItem problemItem, solutionItem;

	private JPanel animationControls;
	private JSlider manualSlider;
	private JSlider framerateSlider;

	private JSpinner samplingSpinner;

	protected ImageIcon createImageIcon(String path, String description) {
		java.net.URL imgURL = getClass().getResource(path);
		if (imgURL != null) {
			return new ImageIcon(imgURL, description);
		} else {
			return new ImageIcon(path, description);
		}
	}

	private JButton playPauseButton, stopButton;
	private ImageIcon playIcon = createImageIcon("play.gif", "Play");
	private ImageIcon pauseIcon = createImageIcon("pause.gif", "Pause");
	private ImageIcon stopIcon = createImageIcon("stop.gif", "Stop");

	private boolean animating;
	private boolean wasPlaying = false;
	private boolean playing;
	private boolean hasProblem;
	private boolean hasSolution;

	private static final int FRAMERATE_MIN = 1;
	private static final int FRAMERATE_MAX = 200;
	private static final int FRAMERATE_INIT = 50;

	private static final int SAMPLING_PERIOD_INIT = 100;

	private File defaultPath;

	private class MenuListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			String cmd = e.getActionCommand();
			if (cmd.equals("Problem")) {
				setAnimating(false);
				vp.setDisplayingSolution(false);
				setInfoText();
				vp.repaint();
			} else if (cmd.equals("Solution")) {
				setAnimating(false);
				vp.setDisplayingSolution(true);
				setInfoText();
				vp.repaint();
			} else if (cmd.equals("Load problem")) {
				setAnimating(false);
				loadProblem();
			} else if (cmd.equals("Load solution")) {
				setAnimating(false);
				loadSolution();
			} else if (cmd.equals("Exit")) {
				container.setVisible(false);
				System.exit(0);
			} else if (cmd.equals("Initialise")) {
				setAnimating(true);
			} else if (cmd.equals("Play")) {
				playPause();
			} else if (cmd.equals("Pause")) {
				playPause();
			} else if (cmd.equals("Stop")) {
				setAnimating(false);
			}
		}
	}

	private class ResizeListener implements ComponentListener {
		@Override
		public void componentResized(ComponentEvent e) {
			updateTickSpacing();
		}

		@Override
		public void componentHidden(ComponentEvent e) {
		}

		@Override
		public void componentMoved(ComponentEvent e) {
		}

		@Override
		public void componentShown(ComponentEvent e) {
		}
	}

	private ResizeListener resizeListener = new ResizeListener();
	private MenuListener menuListener = new MenuListener();

	private ChangeListener manualSliderListener = new ChangeListener() {
		@Override
		public void stateChanged(ChangeEvent e) {
			if (!manualSlider.getValueIsAdjusting() && wasPlaying) {
				wasPlaying = false;
				if (manualSlider.getValue() < manualSlider.getMaximum()) {
					vp.playPauseAnimation();
				}
			}
			vp.gotoFrame(manualSlider.getValue());
		}
	};

	private MouseListener manualSliderClickListener = new MouseListener() {
		@Override
		public void mousePressed(MouseEvent e) {
			if (playing) {
				wasPlaying = true;
				vp.playPauseAnimation();
			}
		}

		@Override
		public void mouseReleased(MouseEvent e) {
		}

		@Override
		public void mouseClicked(MouseEvent e) {
		}

		@Override
		public void mouseEntered(MouseEvent e) {
		}

		@Override
		public void mouseExited(MouseEvent e) {
		}
	};

	private ChangeListener framerateListener = new ChangeListener() {
		@Override
		public void stateChanged(ChangeEvent e) {
			vp.setFramerate(framerateSlider.getValue());
		}
	};

	private ChangeListener samplingListener = new ChangeListener() {
		@Override
		public void stateChanged(ChangeEvent e) {
			vp.setSamplingPeriod((Integer) samplingSpinner.getValue());
		}
	};

	private ActionListener playPauseListener = new ActionListener() {
		@Override
		public void actionPerformed(ActionEvent arg0) {
			playPause();
		}
	};

	private ActionListener stopListener = new ActionListener() {
		@Override
		public void actionPerformed(ActionEvent arg0) {
			setAnimating(false);
		}
	};

	public Visualiser(Container container, File defaultPath) {
		this.container = container;
		this.defaultPath = defaultPath;
		createComponents();
	}

	public Visualiser(Container container) {
		this.container = container;
		try {
			this.defaultPath = new File(".").getCanonicalFile();
		} catch (IOException e) {
			this.defaultPath = null;
		}
		createComponents();
	}

	private void createComponents() {
		vp = new VisualisationPanel(this);
		JPanel wp = new JPanel(new BorderLayout());
		wp.add(vp, BorderLayout.CENTER);
		container.setLayout(new BorderLayout());
		wp.setBorder(BorderFactory.createCompoundBorder(
				BorderFactory.createEmptyBorder(5, 10, 10, 10),
				BorderFactory.createEtchedBorder(EtchedBorder.LOWERED)));
		container.add(wp, BorderLayout.CENTER);

		infoPanel = new JPanel();
		infoPanel.setLayout(new FlowLayout());

		infoLabel = new JLabel("No problem to display.");
		samplingSpinner = new JSpinner(new SpinnerNumberModel(
				SAMPLING_PERIOD_INIT, 1, null, 1));
		samplingSpinner.addChangeListener(samplingListener);
		samplingSpinner.setPreferredSize(new Dimension(50, 20));
		samplingSpinner.setVisible(false);
		vp.setSamplingPeriod(SAMPLING_PERIOD_INIT);
		infoPanel.add(infoLabel);
		infoPanel.add(samplingSpinner);

		container.add(infoPanel, BorderLayout.NORTH);

		createMenus();
		createAnimationControls();
	}

	private void createMenus() {
		menuBar = new JMenuBar();
		createFileMenu();
		createDisplayMenu();
		createAnimationMenu();
		if (container instanceof JFrame) {
			((JFrame) container).setJMenuBar(menuBar);
		} else if (container instanceof JApplet) {
			((JApplet) container).setJMenuBar(menuBar);
		}
	}

	private void createFileMenu() {
		fileMenu = new JMenu("File");
		fileMenu.setMnemonic(KeyEvent.VK_F);
		fileMenu.getAccessibleContext().setAccessibleDescription(
				"Load configs or close the app.");
		menuBar.add(fileMenu);

		loadProblemItem = new JMenuItem("Load problem");
		loadProblemItem.setMnemonic(KeyEvent.VK_P);
		loadProblemItem.addActionListener(menuListener);
		fileMenu.add(loadProblemItem);

		loadSolutionItem = new JMenuItem("Load solution");
		loadSolutionItem.setMnemonic(KeyEvent.VK_S);
		loadSolutionItem.addActionListener(menuListener);
		loadSolutionItem.setEnabled(false);
		fileMenu.add(loadSolutionItem);

		fileMenu.addSeparator();
		exitItem = new JMenuItem("Exit");
		exitItem.setMnemonic(KeyEvent.VK_X);
		exitItem.addActionListener(menuListener);
		fileMenu.add(exitItem);
	}

	private void createDisplayMenu() {
		displayMenu = new JMenu("Display");
		displayMenu.setMnemonic(KeyEvent.VK_D);
		fileMenu.getAccessibleContext().setAccessibleDescription(
				"Display the problem and solution.");
		menuBar.add(displayMenu);

		problemItem = new JMenuItem("Problem");
		problemItem.setMnemonic(KeyEvent.VK_P);
		problemItem.addActionListener(menuListener);
		problemItem.setEnabled(false);
		displayMenu.add(problemItem);

		solutionItem = new JMenuItem("Solution");
		solutionItem.setMnemonic(KeyEvent.VK_S);
		solutionItem.addActionListener(menuListener);
		solutionItem.setEnabled(false);
		displayMenu.add(solutionItem);
	}

	private void createAnimationMenu() {
		animationMenu = new JMenu("Animation");
		animationMenu.setMnemonic(KeyEvent.VK_A);
		fileMenu.getAccessibleContext().setAccessibleDescription(
				"Manage the animation.");
		menuBar.add(animationMenu);
		animationMenu.setEnabled(false);

		initialiseItem = new JMenuItem("Initialise");
		initialiseItem.setMnemonic(KeyEvent.VK_I);
		initialiseItem.addActionListener(menuListener);
		animationMenu.add(initialiseItem);

		playPauseItem = new JMenuItem("Play");
		playPauseItem.setMnemonic(KeyEvent.VK_P);
		playPauseItem.addActionListener(menuListener);
		animationMenu.add(playPauseItem);

		stopItem = new JMenuItem("Stop");
		stopItem.setMnemonic(KeyEvent.VK_T);
		stopItem.addActionListener(menuListener);
		stopItem.setEnabled(false);
		animationMenu.add(stopItem);
	}

	private void createAnimationControls() {
		Font sliderFont = new Font("Arial", Font.PLAIN, 12);

		animationControls = new JPanel();
		animationControls.setLayout(new BoxLayout(animationControls,
				BoxLayout.PAGE_AXIS));

		JLabel manualLabel = new JLabel("Frame #");
		manualLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
		manualSlider = new JSlider(JSlider.HORIZONTAL);
		manualSlider.setPaintTicks(true);
		manualSlider.setPaintLabels(true);
		manualSlider.setFont(sliderFont);
		manualSlider.addChangeListener(manualSliderListener);
		manualSlider.addMouseListener(manualSliderClickListener);
		manualSlider.setMinorTickSpacing(1);
		manualSlider.addComponentListener(resizeListener);

		JLabel framerateLabel = new JLabel("Framerate");
		framerateLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
		framerateSlider = new JSlider(JSlider.HORIZONTAL, FRAMERATE_MIN,
				FRAMERATE_MAX, FRAMERATE_INIT);
		framerateSlider.setMajorTickSpacing(10);
		framerateSlider.setMinorTickSpacing(1);
		framerateSlider.setPaintTicks(true);
		framerateSlider.setPaintLabels(true);
		framerateSlider.setLabelTable(framerateSlider.createStandardLabels(10,
				10));
		framerateSlider.setFont(sliderFont);
		framerateSlider.addChangeListener(framerateListener);
		JPanel frameratePanel = new JPanel();
		frameratePanel.setLayout(new BoxLayout(frameratePanel,
				BoxLayout.PAGE_AXIS));
		frameratePanel.add(framerateLabel);
		frameratePanel.add(Box.createRigidArea(new Dimension(0, 2)));
		frameratePanel.add(framerateSlider);

		playPauseButton = new JButton(playIcon);
		playPauseButton.addActionListener(playPauseListener);
		stopButton = new JButton(stopIcon);
		stopButton.addActionListener(stopListener);

		animationControls.add(new JSeparator(JSeparator.HORIZONTAL));
		animationControls.add(Box.createRigidArea(new Dimension(0, 2)));
		animationControls.add(manualLabel);
		animationControls.add(Box.createRigidArea(new Dimension(0, 2)));
		animationControls.add(manualSlider);
		animationControls.add(Box.createRigidArea(new Dimension(0, 5)));
		JPanel p2 = new JPanel();
		p2.setLayout(new BoxLayout(p2, BoxLayout.LINE_AXIS));
		p2.add(playPauseButton);
		p2.add(Box.createRigidArea(new Dimension(10, 0)));
		p2.add(stopButton);
		p2.add(frameratePanel);
		animationControls.add(p2);
		animationControls.setVisible(false);
		animationControls.setBorder(BorderFactory.createEmptyBorder(0, 10, 5,
				10));
		container.add(animationControls, BorderLayout.SOUTH);
	}

	private File askForFile() {
		JFileChooser fc = new JFileChooser(defaultPath);
		int returnVal = fc.showOpenDialog(container);
		if (returnVal != JFileChooser.APPROVE_OPTION) {
			return null;
		}
		return fc.getSelectedFile();
	}

	private void showFileError(File f) {
		JOptionPane.showMessageDialog(container,
				"Error loading " + f.getName(), "File I/O Error",
				JOptionPane.ERROR_MESSAGE);
	}

	private void loadProblem(File f) {
		try {
			vp.getProblemSetup().loadProblem(f.getPath());
			setHasProblem(true);
		} catch (IOException e1) {
			showFileError(f);
			setHasProblem(false);
		}
	}

	private void loadProblem() {
		File f = askForFile();
		if (f == null) {
			return;
		}
		loadProblem(f);
	}

	private void loadSolution(File f) {
		try {
			vp.getProblemSetup().loadSolution(f.getPath());
			setHasSolution(true);
		} catch (IOException e1) {
			showFileError(f);
			setHasSolution(false);
		}
	}

	private void loadSolution() {
		File f = askForFile();
		if (f == null) {
			return;
		}
		loadSolution(f);
	}

	private void playPause() {
		if (!animating) {
			setAnimating(true);
		}
		vp.playPauseAnimation();
	}

	private void setInfoText() {
		if (!hasProblem) {
			infoLabel.setText("No problem to display.");
			samplingSpinner.setVisible(false);
		} else if (animating) {
			infoLabel
					.setText("Play the animation, or use the slider to control it manually.");
			samplingSpinner.setVisible(false);
		} else if (vp.isDisplayingSolution()) {
			infoLabel.setText("Displaying the solution; sampling period:");
			samplingSpinner.setVisible(true);
		} else {
			infoLabel
					.setText("Displaying the problem: blue = initial, green = goal, red = obstacle. Base is circled.");
			samplingSpinner.setVisible(false);
		}
	}

	private void setHasProblem(boolean hasProblem) {
		this.hasProblem = hasProblem;
		loadSolutionItem.setEnabled(hasProblem);
		problemItem.setEnabled(hasProblem);
		setHasSolution(false);
		setInfoText();
		vp.repaint();
	}

	public boolean hasProblem() {
		return hasProblem;
	}

	private void setHasSolution(boolean hasSolution) {
		this.hasSolution = hasSolution;
		solutionItem.setEnabled(hasSolution);
		animationMenu.setEnabled(hasSolution);
		vp.setDisplayingSolution(hasSolution);
		setAnimating(hasSolution);
		setInfoText();
		vp.repaint();
	}

	public boolean hasSolution() {
		return hasSolution;
	}

	private void setAnimating(boolean animating) {
		if (animating) {
			vp.initAnimation();
		} else {
			vp.stopAnimation();
		}
		if (this.animating == animating) {
			return;
		}
		this.animating = animating;
		stopItem.setEnabled(animating);
		animationControls.setVisible(animating);
		container.validate();
		vp.calculateTransform();
		vp.repaint();
		setInfoText();
	}

	public void setPlaying(boolean playing) {
		if (this.playing == playing) {
			return;
		}
		this.playing = playing;
		if (playing) {
			playPauseItem.setText("Pause");
			playPauseButton.setIcon(pauseIcon);
		} else {
			playPauseItem.setText("Play");
			playPauseButton.setIcon(playIcon);
		}
		playPauseButton.repaint();
	}

	public void updateMaximum() {
		int maximum = vp.getProblemSetup().getPath().size() - 1;
		manualSlider.setMaximum(maximum);
		updateTickSpacing();
	}

	public void updateSliderSpacing(JSlider slider) {
		int width = slider.getBounds().width;
		int max = slider.getMaximum();
		int spacing = 1;
		int mode = 1;
		double pxPerLabel = (double) width * spacing / max;
		if (pxPerLabel <= 0) {
			return;
		}
		while (pxPerLabel <= 30) {
			if (mode == 1) {
				spacing *= 2;
				pxPerLabel *= 2;
				mode = 2;
			} else if (mode == 2) {
				spacing = spacing * 5 / 2;
				pxPerLabel *= 2.5;
				mode = 5;
			} else {
				spacing *= 2;
				pxPerLabel *= 2;
				mode = 1;
			}
		}
		slider.setMajorTickSpacing(spacing);
		int min = slider.getMinimum();
		if (min % spacing > 0) {
			min += (spacing - (min % spacing));
		}
		slider.setLabelTable(slider.createStandardLabels(spacing, min));
	}

	public void updateTickSpacing() {
		updateSliderSpacing(manualSlider);
		updateSliderSpacing(framerateSlider);
	}

	public void setFrameNumber(int frameNumber) {
		manualSlider.setValue(frameNumber);
	}

	public static void main(String[] args) {
		JFrame frame = new JFrame("Assignment 1 visualiser");
		Visualiser vis = new Visualiser(frame);
		if (args.length > 0) {
			vis.loadProblem(new File(args[0]));
			if (vis.hasProblem() && args.length >= 2) {
				vis.loadSolution(new File(args[1]));
			}
		}
		frame.setSize(700, 766);
		frame.setLocation(300, 100);
		frame.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		frame.setVisible(true);
	}
}


text:
package org.eclipse.rdf4j.spring.uuidsource.simple;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @since 4.0.0
 * @author Florian Kleedorfer
 */
@Configuration
@ConditionalOnProperty(prefix = "rdf4j.spring.uuidsource.simple", name = "enabled")
@EnableConfigurationProperties(SimpleRepositoryUUIDSourceProperties.class)
public class SimpleRepositoryUUIDSourceConfig {
	@Bean
	public SimpleRepositoryUUIDSource getSimpleRepositoryUUIDSource() {
		return new SimpleRepositoryUUIDSource();
	}
}


text:
QUnit.test( "Get Name", function( assert ) {
  cheer.getName('Alex');
  assert.equal( cheer.name, 'Alex');

  cheer.getName('Eliza');
  assert.equal( cheer.name, 'Eliza');
});

QUnit.test( "preamble", function( assert ) {
  cheer.getName('Bob');
  assert.equal( cheer.preamble(), 'Your name is Bob');

  cheer.getName('Betty');
  assert.equal( cheer.preamble(), 'Your name is Betty');

});

QUnit.test( "postamble", function( assert ) {
  cheer.getName('Jack');
  assert.equal( cheer.postamble(), 'Jack is Great!!!');

  cheer.getName('Jill');
  assert.equal( cheer.postamble(), 'Jill is Great!!!');

});

QUnit.test( "create Arrays from string", function( assert ) {
  cheer.getName('Alex');
  assert.equal( cheer.nameArray()[0], 'A');

  cheer.getName('Autumn');
  assert.equal( cheer.nameArray()[5], 'N');

});

QUnit.test( "Test dom append", function( assert ) {
  cheer.getName('Alex');
  cheer.appendDom();
  var firstLine = $('ul li:first-child' ).text();
  assert.equal( firstLine, 'Your name is Alex');

  cheer.getName('Autumn');
  cheer.appendDom();
  var firstLine = $('ul li:first-child' ).text();
  assert.equal( firstLine, 'Your name is Autumn');
});


text:
package derpatiel.manafluidics.spell;

import derpatiel.manafluidics.spell.parameters.SpellParameterChoices;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.World;

import java.util.Collection;

public abstract class BlockTargetedSpell extends SpellBase {

    public int spellRange = 5;

    public BlockTargetedSpell(String name, int level, int castingCost, SpellAttribute... attributes) {
        super(name, level, castingCost,attributes);
    }

    @Override
    public boolean doCast(World worldIn, EntityPlayer castingPlayer, boolean boosted, Collection<SpellParameterChoices> parameters){
        boolean flag = false;
            RayTraceResult result = castingPlayer.rayTrace(spellRange, 1.0f);
            if (result.typeOfHit == RayTraceResult.Type.BLOCK) {
                BlockPos hitBlockPos = result.getBlockPos();
                EnumFacing hitFace = result.sideHit;
                flag = doCastOnHit(hitBlockPos,hitFace,worldIn,castingPlayer,boosted,parameters);
            }
        return flag;
    }

    public abstract boolean doCastOnHit(BlockPos hitBlock, EnumFacing hitFace, World world, EntityPlayer player, boolean boosted, Collection<SpellParameterChoices> parameters);
}