text:
package me.rkg.plugins.model.impl;

import com.liferay.portal.kernel.bean.AutoEscapeBeanHandler;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.json.JSON;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.ProxyUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.model.CacheModel;
import com.liferay.portal.model.impl.BaseModelImpl;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.util.PortalUtil;

import com.liferay.portlet.expando.model.ExpandoBridge;
import com.liferay.portlet.expando.util.ExpandoBridgeFactoryUtil;

import me.rkg.plugins.model.Foo;
import me.rkg.plugins.model.FooModel;
import me.rkg.plugins.model.FooSoap;

import java.io.Serializable;

import java.sql.Types;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * The base model implementation for the Foo service. Represents a row in the "RKG_Foo" database table, with each column mapped to a property of this class.
 *
 * <p>
 * This implementation and its corresponding interface {@link me.rkg.plugins.model.FooModel} exist only as a container for the default property accessors generated by ServiceBuilder. Helper methods and all application logic should be put in {@link FooImpl}.
 * </p>
 *
 * @author Brian Wing Shun Chan
 * @see FooImpl
 * @see me.rkg.plugins.model.Foo
 * @see me.rkg.plugins.model.FooModel
 * @generated
 */
@JSON(strict = true)
public class FooModelImpl extends BaseModelImpl<Foo> implements FooModel {
    /*
     * NOTE FOR DEVELOPERS:
     *
     * Never modify or reference this class directly. All methods that expect a foo model instance should use the {@link me.rkg.plugins.model.Foo} interface instead.
     */
    public static final String TABLE_NAME = "RKG_Foo";
    public static final Object[][] TABLE_COLUMNS = {
            { "uuid_", Types.VARCHAR },
            { "fooId", Types.BIGINT },
            { "groupId", Types.BIGINT },
            { "companyId", Types.BIGINT },
            { "userId", Types.BIGINT },
            { "userName", Types.VARCHAR },
            { "createDate", Types.TIMESTAMP },
            { "modifiedDate", Types.TIMESTAMP },
            { "field1", Types.VARCHAR },
            { "field2", Types.BOOLEAN },
            { "field3", Types.INTEGER },
            { "field4", Types.TIMESTAMP },
            { "field5", Types.VARCHAR }
        };
    public static final String TABLE_SQL_CREATE = "create table RKG_Foo (uuid_ VARCHAR(75) null,fooId LONG not null primary key,groupId LONG,companyId LONG,userId LONG,userName VARCHAR(75) null,createDate DATE null,modifiedDate DATE null,field1 VARCHAR(75) null,field2 BOOLEAN,field3 INTEGER,field4 DATE null,field5 VARCHAR(75) null)";
    public static final String TABLE_SQL_DROP = "drop table RKG_Foo";
    public static final String ORDER_BY_JPQL = " ORDER BY foo.field1 ASC";
    public static final String ORDER_BY_SQL = " ORDER BY RKG_Foo.field1 ASC";
    public static final String DATA_SOURCE = "liferayDataSource";
    public static final String SESSION_FACTORY = "liferaySessionFactory";
    public static final String TX_MANAGER = "liferayTransactionManager";
    public static final boolean ENTITY_CACHE_ENABLED = GetterUtil.getBoolean(com.liferay.util.service.ServiceProps.get(
                "value.object.entity.cache.enabled.me.rkg.plugins.model.Foo"),
            true);
    public static final boolean FINDER_CACHE_ENABLED = GetterUtil.getBoolean(com.liferay.util.service.ServiceProps.get(
                "value.object.finder.cache.enabled.me.rkg.plugins.model.Foo"),
            true);
    public static final boolean COLUMN_BITMASK_ENABLED = GetterUtil.getBoolean(com.liferay.util.service.ServiceProps.get(
                "value.object.column.bitmask.enabled.me.rkg.plugins.model.Foo"),
            true);
    public static long FIELD2_COLUMN_BITMASK = 1L;
    public static long GROUPID_COLUMN_BITMASK = 2L;
    public static long UUID_COLUMN_BITMASK = 4L;
    public static final long LOCK_EXPIRATION_TIME = GetterUtil.getLong(com.liferay.util.service.ServiceProps.get(
                "lock.expiration.time.me.rkg.plugins.model.Foo"));
    private static ClassLoader _classLoader = Foo.class.getClassLoader();
    private static Class<?>[] _escapedModelProxyInterfaces = new Class[] {
            Foo.class
        };
    private String _uuid;
    private String _originalUuid;
    private long _fooId;
    private long _groupId;
    private long _originalGroupId;
    private boolean _setOriginalGroupId;
    private long _companyId;
    private long _userId;
    private String _userUuid;
    private String _userName;
    private Date _createDate;
    private Date _modifiedDate;
    private String _field1;
    private boolean _field2;
    private boolean _originalField2;
    private boolean _setOriginalField2;
    private int _field3;
    private Date _field4;
    private String _field5;
    private long _columnBitmask;
    private Foo _escapedModelProxy;

    public FooModelImpl() {
    }

    /**
     * Converts the soap model instance into a normal model instance.
     *
     * @param soapModel the soap model instance to convert
     * @return the normal model instance
     */
    public static Foo toModel(FooSoap soapModel) {
        if (soapModel == null) {
            return null;
        }

        Foo model = new FooImpl();

        model.setUuid(soapModel.getUuid());
        model.setFooId(soapModel.getFooId());
        model.setGroupId(soapModel.getGroupId());
        model.setCompanyId(soapModel.getCompanyId());
        model.setUserId(soapModel.getUserId());
        model.setUserName(soapModel.getUserName());
        model.setCreateDate(soapModel.getCreateDate());
        model.setModifiedDate(soapModel.getModifiedDate());
        model.setField1(soapModel.getField1());
        model.setField2(soapModel.getField2());
        model.setField3(soapModel.getField3());
        model.setField4(soapModel.getField4());
        model.setField5(soapModel.getField5());

        return model;
    }

    /**
     * Converts the soap model instances into normal model instances.
     *
     * @param soapModels the soap model instances to convert
     * @return the normal model instances
     */
    public static List<Foo> toModels(FooSoap[] soapModels) {
        if (soapModels == null) {
            return null;
        }

        List<Foo> models = new ArrayList<Foo>(soapModels.length);

        for (FooSoap soapModel : soapModels) {
            models.add(toModel(soapModel));
        }

        return models;
    }

    public long getPrimaryKey() {
        return _fooId;
    }

    public void setPrimaryKey(long primaryKey) {
        setFooId(primaryKey);
    }

    public Serializable getPrimaryKeyObj() {
        return new Long(_fooId);
    }

    public void setPrimaryKeyObj(Serializable primaryKeyObj) {
        setPrimaryKey(((Long) primaryKeyObj).longValue());
    }

    public Class<?> getModelClass() {
        return Foo.class;
    }

    public String getModelClassName() {
        return Foo.class.getName();
    }

    @Override
    public Map<String, Object> getModelAttributes() {
        Map<String, Object> attributes = new HashMap<String, Object>();

        attributes.put("uuid", getUuid());
        attributes.put("fooId", getFooId());
        attributes.put("groupId", getGroupId());
        attributes.put("companyId", getCompanyId());
        attributes.put("userId", getUserId());
        attributes.put("userName", getUserName());
        attributes.put("createDate", getCreateDate());
        attributes.put("modifiedDate", getModifiedDate());
        attributes.put("field1", getField1());
        attributes.put("field2", getField2());
        attributes.put("field3", getField3());
        attributes.put("field4", getField4());
        attributes.put("field5", getField5());

        return attributes;
    }

    @Override
    public void setModelAttributes(Map<String, Object> attributes) {
        String uuid = (String) attributes.get("uuid");

        if (uuid != null) {
            setUuid(uuid);
        }

        Long fooId = (Long) attributes.get("fooId");

        if (fooId != null) {
            setFooId(fooId);
        }

        Long groupId = (Long) attributes.get("groupId");

        if (groupId != null) {
            setGroupId(groupId);
        }

        Long companyId = (Long) attributes.get("companyId");

        if (companyId != null) {
            setCompanyId(companyId);
        }

        Long userId = (Long) attributes.get("userId");

        if (userId != null) {
            setUserId(userId);
        }

        String userName = (String) attributes.get("userName");

        if (userName != null) {
            setUserName(userName);
        }

        Date createDate = (Date) attributes.get("createDate");

        if (createDate != null) {
            setCreateDate(createDate);
        }

        Date modifiedDate = (Date) attributes.get("modifiedDate");

        if (modifiedDate != null) {
            setModifiedDate(modifiedDate);
        }

        String field1 = (String) attributes.get("field1");

        if (field1 != null) {
            setField1(field1);
        }

        Boolean field2 = (Boolean) attributes.get("field2");

        if (field2 != null) {
            setField2(field2);
        }

        Integer field3 = (Integer) attributes.get("field3");

        if (field3 != null) {
            setField3(field3);
        }

        Date field4 = (Date) attributes.get("field4");

        if (field4 != null) {
            setField4(field4);
        }

        String field5 = (String) attributes.get("field5");

        if (field5 != null) {
            setField5(field5);
        }
    }

    @JSON
    public String getUuid() {
        if (_uuid == null) {
            return StringPool.BLANK;
        } else {
            return _uuid;
        }
    }

    public void setUuid(String uuid) {
        if (_originalUuid == null) {
            _originalUuid = _uuid;
        }

        _uuid = uuid;
    }

    public String getOriginalUuid() {
        return GetterUtil.getString(_originalUuid);
    }

    @JSON
    public long getFooId() {
        return _fooId;
    }

    public void setFooId(long fooId) {
        _fooId = fooId;
    }

    @JSON
    public long getGroupId() {
        return _groupId;
    }

    public void setGroupId(long groupId) {
        _columnBitmask |= GROUPID_COLUMN_BITMASK;

        if (!_setOriginalGroupId) {
            _setOriginalGroupId = true;

            _originalGroupId = _groupId;
        }

        _groupId = groupId;
    }

    public long getOriginalGroupId() {
        return _originalGroupId;
    }

    @JSON
    public long getCompanyId() {
        return _companyId;
    }

    public void setCompanyId(long companyId) {
        _companyId = companyId;
    }

    @JSON
    public long getUserId() {
        return _userId;
    }

    public void setUserId(long userId) {
        _userId = userId;
    }

    public String getUserUuid() throws SystemException {
        return PortalUtil.getUserValue(getUserId(), "uuid", _userUuid);
    }

    public void setUserUuid(String userUuid) {
        _userUuid = userUuid;
    }

    @JSON
    public String getUserName() {
        if (_userName == null) {
            return StringPool.BLANK;
        } else {
            return _userName;
        }
    }

    public void setUserName(String userName) {
        _userName = userName;
    }

    @JSON
    public Date getCreateDate() {
        return _createDate;
    }

    public void setCreateDate(Date createDate) {
        _createDate = createDate;
    }

    @JSON
    public Date getModifiedDate() {
        return _modifiedDate;
    }

    public void setModifiedDate(Date modifiedDate) {
        _modifiedDate = modifiedDate;
    }

    @JSON
    public String getField1() {
        if (_field1 == null) {
            return StringPool.BLANK;
        } else {
            return _field1;
        }
    }

    public void setField1(String field1) {
        _columnBitmask = -1L;

        _field1 = field1;
    }

    @JSON
    public boolean getField2() {
        return _field2;
    }

    public boolean isField2() {
        return _field2;
    }

    public void setField2(boolean field2) {
        _columnBitmask |= FIELD2_COLUMN_BITMASK;

        if (!_setOriginalField2) {
            _setOriginalField2 = true;

            _originalField2 = _field2;
        }

        _field2 = field2;
    }

    public boolean getOriginalField2() {
        return _originalField2;
    }

    @JSON
    public int getField3() {
        return _field3;
    }

    public void setField3(int field3) {
        _field3 = field3;
    }

    @JSON
    public Date getField4() {
        return _field4;
    }

    public void setField4(Date field4) {
        _field4 = field4;
    }

    @JSON
    public String getField5() {
        if (_field5 == null) {
            return StringPool.BLANK;
        } else {
            return _field5;
        }
    }

    public void setField5(String field5) {
        _field5 = field5;
    }

    public long getColumnBitmask() {
        return _columnBitmask;
    }

    @Override
    public ExpandoBridge getExpandoBridge() {
        return ExpandoBridgeFactoryUtil.getExpandoBridge(getCompanyId(),
            Foo.class.getName(), getPrimaryKey());
    }

    @Override
    public void setExpandoBridgeAttributes(ServiceContext serviceContext) {
        ExpandoBridge expandoBridge = getExpandoBridge();

        expandoBridge.setAttributes(serviceContext);
    }

    @Override
    public Foo toEscapedModel() {
        if (_escapedModelProxy == null) {
            _escapedModelProxy = (Foo) ProxyUtil.newProxyInstance(_classLoader,
                    _escapedModelProxyInterfaces,
                    new AutoEscapeBeanHandler(this));
        }

        return _escapedModelProxy;
    }

    @Override
    public Object clone() {
        FooImpl fooImpl = new FooImpl();

        fooImpl.setUuid(getUuid());
        fooImpl.setFooId(getFooId());
        fooImpl.setGroupId(getGroupId());
        fooImpl.setCompanyId(getCompanyId());
        fooImpl.setUserId(getUserId());
        fooImpl.setUserName(getUserName());
        fooImpl.setCreateDate(getCreateDate());
        fooImpl.setModifiedDate(getModifiedDate());
        fooImpl.setField1(getField1());
        fooImpl.setField2(getField2());
        fooImpl.setField3(getField3());
        fooImpl.setField4(getField4());
        fooImpl.setField5(getField5());

        fooImpl.resetOriginalValues();

        return fooImpl;
    }

    public int compareTo(Foo foo) {
        int value = 0;

        value = getField1().compareTo(foo.getField1());

        if (value != 0) {
            return value;
        }

        return 0;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }

        Foo foo = null;

        try {
            foo = (Foo) obj;
        } catch (ClassCastException cce) {
            return false;
        }

        long primaryKey = foo.getPrimaryKey();

        if (getPrimaryKey() == primaryKey) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return (int) getPrimaryKey();
    }

    @Override
    public void resetOriginalValues() {
        FooModelImpl fooModelImpl = this;

        fooModelImpl._originalUuid = fooModelImpl._uuid;

        fooModelImpl._originalGroupId = fooModelImpl._groupId;

        fooModelImpl._setOriginalGroupId = false;

        fooModelImpl._originalField2 = fooModelImpl._field2;

        fooModelImpl._setOriginalField2 = false;

        fooModelImpl._columnBitmask = 0;
    }

    @Override
    public CacheModel<Foo> toCacheModel() {
        FooCacheModel fooCacheModel = new FooCacheModel();

        fooCacheModel.uuid = getUuid();

        String uuid = fooCacheModel.uuid;

        if ((uuid != null) && (uuid.length() == 0)) {
            fooCacheModel.uuid = null;
        }

        fooCacheModel.fooId = getFooId();

        fooCacheModel.groupId = getGroupId();

        fooCacheModel.companyId = getCompanyId();

        fooCacheModel.userId = getUserId();

        fooCacheModel.userName = getUserName();

        String userName = fooCacheModel.userName;

        if ((userName != null) && (userName.length() == 0)) {
            fooCacheModel.userName = null;
        }

        Date createDate = getCreateDate();

        if (createDate != null) {
            fooCacheModel.createDate = createDate.getTime();
        } else {
            fooCacheModel.createDate = Long.MIN_VALUE;
        }

        Date modifiedDate = getModifiedDate();

        if (modifiedDate != null) {
            fooCacheModel.modifiedDate = modifiedDate.getTime();
        } else {
            fooCacheModel.modifiedDate = Long.MIN_VALUE;
        }

        fooCacheModel.field1 = getField1();

        String field1 = fooCacheModel.field1;

        if ((field1 != null) && (field1.length() == 0)) {
            fooCacheModel.field1 = null;
        }

        fooCacheModel.field2 = getField2();

        fooCacheModel.field3 = getField3();

        Date field4 = getField4();

        if (field4 != null) {
            fooCacheModel.field4 = field4.getTime();
        } else {
            fooCacheModel.field4 = Long.MIN_VALUE;
        }

        fooCacheModel.field5 = getField5();

        String field5 = fooCacheModel.field5;

        if ((field5 != null) && (field5.length() == 0)) {
            fooCacheModel.field5 = null;
        }

        return fooCacheModel;
    }

    @Override
    public String toString() {
        StringBundler sb = new StringBundler(27);

        sb.append("{uuid=");
        sb.append(getUuid());
        sb.append(", fooId=");
        sb.append(getFooId());
        sb.append(", groupId=");
        sb.append(getGroupId());
        sb.append(", companyId=");
        sb.append(getCompanyId());
        sb.append(", userId=");
        sb.append(getUserId());
        sb.append(", userName=");
        sb.append(getUserName());
        sb.append(", createDate=");
        sb.append(getCreateDate());
        sb.append(", modifiedDate=");
        sb.append(getModifiedDate());
        sb.append(", field1=");
        sb.append(getField1());
        sb.append(", field2=");
        sb.append(getField2());
        sb.append(", field3=");
        sb.append(getField3());
        sb.append(", field4=");
        sb.append(getField4());
        sb.append(", field5=");
        sb.append(getField5());
        sb.append("}");

        return sb.toString();
    }

    public String toXmlString() {
        StringBundler sb = new StringBundler(43);

        sb.append("<model><model-name>");
        sb.append("me.rkg.plugins.model.Foo");
        sb.append("</model-name>");

        sb.append(
            "<column><column-name>uuid</column-name><column-value><![CDATA[");
        sb.append(getUuid());
        sb.append("]]></column-value></column>");
        sb.append(
            "<column><column-name>fooId</column-name><column-value><![CDATA[");
        sb.append(getFooId());
        sb.append("]]></column-value></column>");
        sb.append(
            "<column><column-name>groupId</column-name><column-value><![CDATA[");
        sb.append(getGroupId());
        sb.append("]]></column-value></column>");
        sb.append(
            "<column><column-name>companyId</column-name><column-value><![CDATA[");
        sb.append(getCompanyId());
        sb.append("]]></column-value></column>");
        sb.append(
            "<column><column-name>userId</column-name><column-value><![CDATA[");
        sb.append(getUserId());
        sb.append("]]></column-value></column>");
        sb.append(
            "<column><column-name>userName</column-name><column-value><![CDATA[");
        sb.append(getUserName());
        sb.append("]]></column-value></column>");
        sb.append(
            "<column><column-name>createDate</column-name><column-value><![CDATA[");
        sb.append(getCreateDate());
        sb.append("]]></column-value></column>");
        sb.append(
            "<column><column-name>modifiedDate</column-name><column-value><![CDATA[");
        sb.append(getModifiedDate());
        sb.append("]]></column-value></column>");
        sb.append(
            "<column><column-name>field1</column-name><column-value><![CDATA[");
        sb.append(getField1());
        sb.append("]]></column-value></column>");
        sb.append(
            "<column><column-name>field2</column-name><column-value><![CDATA[");
        sb.append(getField2());
        sb.append("]]></column-value></column>");
        sb.append(
            "<column><column-name>field3</column-name><column-value><![CDATA[");
        sb.append(getField3());
        sb.append("]]></column-value></column>");
        sb.append(
            "<column><column-name>field4</column-name><column-value><![CDATA[");
        sb.append(getField4());
        sb.append("]]></column-value></column>");
        sb.append(
            "<column><column-name>field5</column-name><column-value><![CDATA[");
        sb.append(getField5());
        sb.append("]]></column-value></column>");

        sb.append("</model>");

        return sb.toString();
    }
}


text:
'''Module to parse an affiliation string using grobid.'''

import requests
import xml.etree.ElementTree as et
import csv
from pkg_resources import resource_filename
import re
from urllib.parse import quote_plus

# generate two dictionaries mapping the ISO 3166-1 alpha-2 country codes to
# the corresponding country names and to the corresponding population sizes
countryDict, populationDict = {}, {}
countryInfo = resource_filename(__name__, 'data/countryInfo.txt')
with open(countryInfo) as csvfile:
	data = filter(lambda row: not row[0].startswith('#'), csvfile)
	reader = csv.reader(data, delimiter='\t', quoting=csv.QUOTE_NONE)
	for row in reader:
		countryDict[row[0]] = row[4]
		populationDict[row[0]] = int(row[7])

# create a list of country code and country tuples
countryList = list(countryDict.items())
# add alternative country names
altCountries = resource_filename(__name__, 'data/alternativeCountryNames.csv')
with open(altCountries) as csvfile:
	reader = csv.reader(csvfile)
	for row in reader:
		countryList.append((row[0], row[1]))
# sort the list by the population size
countryList.sort(key=lambda item: populationDict[item[0]], reverse=True)
# move country names which contain a part of another country name before these
# countries in order to avoid false assignments when extracting them
for i in range(len(countryList)):
	for j in range(i + 1, len(countryList)):
		if countryList[i][1] in countryList[j][1]:
			countryList.insert(i, countryList.pop(j))

def parseAddress(affiliation, root, patternHK=re.compile(r'\b(?i)Hong Kong\b'),
		patternMO=re.compile(r'\b(?i)Macao\b')):
	'''
	Parse every address tag inside the retrieved grobid xml string and
	try to improve the country information searching for a valid country
	at the end of the affiliation string.

	:param affiliation: the affiliation string
	:param root: the root node of the grobid xml string
	:param patternHK: the pattern to search for Hong Kong
	:param patternMO: the pattern to search for Macao
	'''
	result = {}

	# extract the country code
	for alpha2, country in countryList:
		try:
			match = re.search(r'(?i)\b{}$'.format(country), affiliation)
		except TypeError:
			return result
		if match:
			countrySource = 'regex'
			break
	else:
		for country in root.findall('./affiliation/address/country'):
			alpha2 = country.get('key')
			countrySource = 'grobid'
			break
		else:
			alpha2 = None

	# fix the country codes of Hong Kong and Macao
	if alpha2 == 'CN' and re.search(patternHK, affiliation):
		alpha2 = 'HK'
	if alpha2 == 'CN' and re.search(patternMO, affiliation):
		alpha2 = 'MO'

	# retrieve the country information corresponding to the country code
	try:
		result['country'] = countryDict[alpha2]
		result['alpha2'] = alpha2
		result['countrySource'] = countrySource
	except KeyError:
		pass

	# retrieve region and postCode
	for tag in ['region', 'postCode',]:
		for addressTag in root.findall('./affiliation/address/' + tag):
			result[tag] = addressTag.text
			break

	return result

def parseSettlement(affiliation, root,
		pattern=re.compile(r'\b(?<!\-)[A-Za-z][a-z]*\b(?!\-)')):
	'''
	Extract every possible settlement starting with the words betweeen
	the second and third last commas, followed by the words between the
	last and second last comma and finally with the settlement extracted
	by grobid.

	:param affiliation: the affiliation string
	:param root: the root node of the grobid xml string
	:param pattern: the pattern for a country name
	'''
	result = {'settlement':[]}
	try:
		splitAffi = affiliation.split(',')
	except AttributeError:
		return result
	try:
		leftmost = ' '.join(re.findall(pattern, splitAffi[-3]))
		if leftmost != '':
			result['settlement'].append(leftmost)
	except IndexError:
		leftmost = None
	try:
		rightmost = ' '.join(re.findall(pattern, splitAffi[-2]))
		if rightmost != '' and leftmost != rightmost:
			result['settlement'].append(rightmost)
	except IndexError:
		rightmost = None
	for addressTag in root.findall('./affiliation/address/settlement'):
		grobid = addressTag.text
		if grobid != leftmost and grobid != rightmost:
			result['settlement'].append(grobid)
		break
	return result

def parseOrganisations(affiliation, root, pattern=re.compile(r'^[^,]+(?=,)')):
	'''
	Retrieve groups of organisations consisting of institutions,
	departments and/or laboratories based on the retrieved grobid xml
	string. Additionally, try to improve the first institution using the
	part of the affiliation string before the first comma.

	Note that if multiple institutions, departments or laboratories are
	in the same group they are considered identical. Only one of them is
	taken for the returned data structure.

	:param affiliation: the affiliation string
	:param root: the root node of the grobid xml string
	:param pattern: the pattern for the string before the first comma
	'''
	result = []
	for org in root.findall('./affiliation/orgName'):
		# determine index
		orgKey = org.get('key')
		try:
			index = int(re.search(r'\d+', orgKey).group()) - 1
		except TypeError:
			index = 0
		# update or insert item at index
		item = {org.get('type'): org.text}
		try:
			result[index].update(item)
		except IndexError:
			result.insert(index, item)

	for item in result:
		item.update({'institutionSource': 'grobid'})

	try:
		match = re.search(pattern, affiliation)
	except TypeError:
		return result
	try:
		extracted = match.group(0)
	except AttributeError:
		return result

	if not result or not 'institution' in result[0]:
		result.insert(0, {
			'institution': extracted,
			'institutionSource':'regexInsert',
		})
	elif result[0]['institution'] in extracted:
		result[0]['institution'] = extracted
		result[0]['institutionSource'] = 'regexReplace'
	elif extracted in result[0]['institution']:
		result.insert(1, {
			'institution': extracted,
			'institutionSource':'regexInsertAfter',
		})
	else:
		result.insert(0, {
			'institution': extracted,
			'institutionSource':'regexInsertBefore',
		})

	return result

def queryGrobid(affiliation, url):
	'''
	Try to retrieve a structured xml representation of the the
	affiliation string using grobid.

	:param affiliation: the affiliation string to be sent to grobid
	:param url: the URL to the grobid service
	'''
	try:
		cmd = 'affiliations=' + quote_plus(affiliation)
	except TypeError:
		return '<results></results>'
	headers = {'Content-type': 'application/x-www-form-urlencoded'}
	r = requests.post(url + '/processAffiliations', data=cmd, headers=headers)
	return '<results>' + r.content.decode('UTF-8') + '</results>'

def parseAll(affiliation, url):
	'''
	Yield all possible institutions along with their corresponding
	departments, laboratories and address information using grobid and
	regular expressions to parse the given affiliation string.

	:param affiliation: the affiliation string to be parsed
	:param url: the URL to the grobid service
	'''
	try:
		root = et.fromstring(queryGrobid(affiliation, url))
	except et.ParseError:
		return
	organisations = parseOrganisations(affiliation, root)
	address = parseAddress(affiliation, root)
	settlement = parseSettlement(affiliation, root)
	for organisation in organisations:
		result = {}
		result.update(organisation)
		result.update(address)
		result.update(settlement)
		yield result

def parse(affiliation, url):
	'''
	Get the first institution along with the corresponding
	department, laboratory and address information using grobid and
	regular expressions to parse the given affiliation string.

	:param affiliation: the affiliation string to be parsed
	:param url: the URL to the grobid service
	'''
	try:
		return next(parseAll(affiliation, url))
	except StopIteration:
		return

redpajama_set_name: RedPajamaGithub


text:
1.  `npm install -g jspm live-server`
2.  Clone this repo
3.  `jspm install`
4.  Run `live-server` and observe the results

### Bundle project
`npm run build`

MIT License


text:
/* global CodeMirror:false */

var codeEditorAutoComplete = require('./codeEditorAutoComplete');
var codeEditorAutoDocument = require('./codeEditorAutoDocument');
var PluginItem = require('../pluginItem');
var MessageBox = require('../../widgets/messageBox');

/**
 * @constructor
 * @struct
 * @param {!jQuery} parent
 * @param {!ViewContext} context
 * @param {!PluginViewModel} viewModel
 */
function PluginView(parent, context, viewModel) {
    'use strict';

    /**
     * @type {!PluginView}
     */
    var self = this;

    /**
    * @type {CodeMirror}
    */
    var codeEditor = null;

    /**
     * @type {!Template}
     */
    var template = context.template.load('pluginEdit');

    /**
     * @type {MessageBox}
     */
    var messageBox;

    function constructor() {
        console.log('InstanceView.constructor', self);

        initializeView();

        viewModel.onPluginItemChanged = handlePluginItemChanged;
        viewModel.onErrorResponse = messageBox.showWarning;
    }

    function initializeCodeEditor() {
        CodeMirror.commands.autocomplete = codeEditorAutoComplete;
        CodeMirror.commands.autodocument = codeEditorAutoDocument;
        CodeMirror.commands.quicksave = save;

        codeEditor = new CodeMirror(parent.find('[data-element=codeEditor]')[0], {
            value:  '',
            mode:  'javascript',
            lineNumbers: false,
            indentUnit: 4,
            extraKeys: { 'Ctrl-Space': 'autocomplete', 'Ctrl-D': 'autodocument', 'Ctrl-S': 'quicksave' }
        });

        codeEditor.on('cursorActivity', handleCodeCursorActivity);

        minimizeCodeEditor();
    }

    function initializeView() {
        parent.html(template.build(viewModel));

        parent.find('[data-element=save]').click(save);
        parent.find('[data-element=delete]').click(handleDeleteCommand);
        parent.find('[data-element=cancel]').click(handleCancelCommand);

        parent.find('[data-element=maximize-editor]').click(maximizeCodeEditor);
        parent.find('[data-element=minimize-editor]').click(minimizeCodeEditor);

        messageBox = new MessageBox(parent.find('[data-element=errorMessageBox]'));

        initializeCodeEditor();

        if (viewModel.pluginItem) {
            codeEditor.setValue(viewModel.pluginItem.code);
        }
    }

    /**
     * Maximizes the code editor and hides the config section.
     */
    function maximizeCodeEditor() {
        parent.find('[data-element=maximize-editor]').hide();
        parent.find('[data-element=minimize-editor]').show();

        parent.find('[data-section=config]').hide();
    }

    /**
     * Minimizes the code editor to available space.
     */
    function minimizeCodeEditor() {
        parent.find('[data-element=maximize-editor]').show();
        parent.find('[data-element=minimize-editor]').hide();

        parent.find('[data-section=config]').show();
    }

    /**
     * Display the current cursor position in the editor status bar.
     * @param {?} instance
     */
    function handleCodeCursorActivity(instance) {
        var cursorPosition = instance.getCursor();
        parent.find('[data-bind=editorCursorLine]').html(cursorPosition.line);
        parent.find('[data-bind=editorCursorColumn]').html(cursorPosition.ch);
    }

    /**
     * Updates the editor syntax error component.
     * @param {string} error
     * @param {string} title
     */
    function updateEditorSyntaxError(error, title) {
        parent.find('[data-editor-error]')
            .attr('data-editor-error', error)
            .attr('title', title);
    }

    /**
     * Activate view
     * @param {string|object} [data]
     */
    this.activate = function activate(data) {
        parent.find('.error-line').hide();
        viewModel.activate(data);
    };

    function handlePluginItemChanged() {
        initializeView();
    }

    /**
     * Handle Save Button Click
     */
    function save() {
        var pluginItem = new PluginItem();
        pluginItem.id = parent.find('[name=id]').val();
        pluginItem.code = codeEditor.getValue();

        if (pluginItem.id) {
            viewModel.createOrUpdate(pluginItem);
        } else {
            messageBox.showWarning('Please use a plugin name.');
        }
    }

    /**
     * Handle cancel button click
     */
    function handleCancelCommand() {
        viewModel.cancel();
    }

    /**
     * Handle delete click
     */
    function handleDeleteCommand() {
        viewModel.deletePlugin();
    }

    constructor();
}

module.exports = PluginView;


text:
<?php

namespace tests\codeception;

use Codeception\Specify;
use inblank\activeuser\models\User;
use inblank\activeuser\Module;
use tests\codeception\_fixtures\ProfileFixture;
use tests\codeception\_fixtures\UserFixture;
use yii;
use yii\db\Query;

/**
 * @property \UnitTester $tester
 */
class UserQueryTest extends \Codeception\Test\Unit
{
    use Specify;

    /** @var  Module */
    protected $module;

    public function testFind()
    {
        expect("we can find user", User::findOne(1))->notNull();
        expect("we can't find wrong user", User::findOne(9999))->null();

        foreach ([User::STATUS_ACTIVE, User::STATUS_BLOCKED, User::STATUS_CONFIRM, User::STATUS_RESTORE] as $status) {
            $realCount = (new Query)->from(User::tableName())
                ->where('[[status]]=:s', [':s' => $status])
                ->count('*', User::getDb());
            $query = User::find();
            switch ($status) {
                case User::STATUS_ACTIVE:
                    $query->active();
                    break;
                case User::STATUS_BLOCKED:
                    $query->blocked();
                    break;
                case User::STATUS_CONFIRM:
                    $query->notConfirmed();
                    break;
                case User::STATUS_RESTORE:
                    $query->restoring();
                    break;
            }
            $users = $query->all();
            expect("result must be as array", is_array($users))->true();
            expect("count of active user must equals", count($users))->equals($realCount);
            if (!empty($users)) {
                expect("result must contain User objects", $users[0])->isInstanceOf(User::className());
            }
        }
    }

    protected function tearDown()
    {
        parent::tearDown();
    }

    protected function setUp()
    {
        parent::setUp();
        $this->module = Yii::$app->getModule('activeuser');
    }

    protected function _before()
    {
        parent::_before();
        $this->tester->haveFixtures([
            'users' => UserFixture::className(),
            'profiles' => ProfileFixture::className(),
        ]);
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>quarkus-tck-microprofile-metrics-parent</artifactId>
        <groupId>io.quarkus</groupId>
        <version>999-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>quarkus-tck-microprofile-metrics-rest</artifactId>
    <name>Quarkus - TCK - MicroProfile Metrics REST</name>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <systemPropertyVariables>
                        <!-- Disable quarkus optimization -->
                        <quarkus.arc.remove-unused-beans>false</quarkus.arc.remove-unused-beans>
                        <!-- Change metrics endpoint to be /metrics -->
                        <quarkus.http.non-application-root-path>/</quarkus.http.non-application-root-path>
                    </systemPropertyVariables>
                    <!-- This workaround allows us to run a single test using
                        the "test" system property -->
                    <!-- https://issues.apache.org/jira/browse/SUREFIRE-569 -->
                    <dependenciesToScan>
                        <dependency>org.eclipse.microprofile.metrics:microprofile-metrics-rest-tck</dependency>
                    </dependenciesToScan>
                    <environmentVariables>
                        <MP_METRICS_TAGS>tier=integration</MP_METRICS_TAGS>
                    </environmentVariables>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>io.quarkus</groupId>
            <artifactId>quarkus-arquillian</artifactId>
        </dependency>
        <dependency>
            <groupId>io.quarkus</groupId>
            <artifactId>quarkus-smallrye-metrics</artifactId>
        </dependency>
        <dependency>
            <groupId>org.eclipse.microprofile.metrics</groupId>
            <artifactId>microprofile-metrics-rest-tck</artifactId>
            <version>${microprofile-metrics-tck.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.jboss.shrinkwrap.resolver</groupId>
                    <artifactId>shrinkwrap-resolver-impl-maven</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>jakarta.xml.bind</groupId>
                    <artifactId>jakarta.xml.bind-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.jboss.spec.javax.xml.bind</groupId>
            <artifactId>jboss-jaxb-api_2.3_spec</artifactId>
        </dependency>

        <!-- Minimal test dependencies to *-deployment artifacts for consistent build order -->
        <dependency>
            <groupId>io.quarkus</groupId>
            <artifactId>quarkus-smallrye-metrics-deployment</artifactId>
            <version>${project.version}</version>
            <type>pom</type>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>*</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <profiles>
        <profile>
            <id>jakarta-rewrite</id>
            <activation>
                <property>
                    <name>jakarta-rewrite</name>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.openrewrite.maven</groupId>
                        <artifactId>rewrite-maven-plugin</artifactId>
                        <configuration>
                            <activeRecipes>
                                <recipe>io.quarkus.microprofile-tck-versions</recipe>
                                <recipe>io.quarkus.jakarta-jaxb-switch</recipe>
                            </activeRecipes>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>


text:
package org.smartpony.common.error

trait ErrorCode {

  val identifier: String
  lazy val code: String = identifier.split(": ")(0)
  lazy val message: String = identifier.split(": ")(1)

}


text:
import { __read, __spreadArray } from '../../tslib/tslib.js';
import { MDCFoundation } from './foundation.js';
var MDCComponent = /** @class */ (function () {
    function MDCComponent(root, foundation) {
        var args = [];
        for (var _i = 2; _i < arguments.length; _i++) {
            args[_i - 2] = arguments[_i];
        }
        this.root = root;
        this.initialize.apply(this, __spreadArray([], __read(args)));
        // Note that we initialize foundation here and not within the constructor's
        // default param so that this.root is defined and can be used within the
        // foundation class.
        this.foundation =
            foundation === undefined ? this.getDefaultFoundation() : foundation;
        this.foundation.init();
        this.initialSyncWithDOM();
    }
    MDCComponent.attachTo = function (root) {
        // Subclasses which extend MDCBase should provide an attachTo() method that takes a root element and
        // returns an instantiated component with its root set to that element. Also note that in the cases of
        // subclasses, an explicit foundation class will not have to be passed in; it will simply be initialized
        // from getDefaultFoundation().
        return new MDCComponent(root, new MDCFoundation({}));
    };
    /* istanbul ignore next: method param only exists for typing purposes; it does not need to be unit tested */
    MDCComponent.prototype.initialize = function () {
        var _args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            _args[_i] = arguments[_i];
        }
        // Subclasses can override this to do any additional setup work that would be considered part of a
        // "constructor". Essentially, it is a hook into the parent constructor before the foundation is
        // initialized. Any additional arguments besides root and foundation will be passed in here.
    };
    MDCComponent.prototype.getDefaultFoundation = function () {
        // Subclasses must override this method to return a properly configured foundation class for the
        // component.
        throw new Error('Subclasses must override getDefaultFoundation to return a properly configured ' +
            'foundation class');
    };
    MDCComponent.prototype.initialSyncWithDOM = function () {
        // Subclasses should override this method if they need to perform work to synchronize with a host DOM
        // object. An example of this would be a form control wrapper that needs to synchronize its internal state
        // to some property or attribute of the host DOM. Please note: this is *not* the place to perform DOM
        // reads/writes that would cause layout / paint, as this is called synchronously from within the constructor.
    };
    MDCComponent.prototype.destroy = function () {
        // Subclasses may implement this method to release any resources / deregister any listeners they have
        // attached. An example of this might be deregistering a resize event from the window object.
        this.foundation.destroy();
    };
    MDCComponent.prototype.listen = function (evtType, handler, options) {
        this.root.addEventListener(evtType, handler, options);
    };
    MDCComponent.prototype.unlisten = function (evtType, handler, options) {
        this.root.removeEventListener(evtType, handler, options);
    };
    /**
     * Fires a cross-browser-compatible custom event from the component root of the given type, with the given data.
     */
    MDCComponent.prototype.emit = function (evtType, evtData, shouldBubble) {
        if (shouldBubble === void 0) { shouldBubble = false; }
        var evt;
        if (typeof CustomEvent === 'function') {
            evt = new CustomEvent(evtType, {
                bubbles: shouldBubble,
                detail: evtData,
            });
        }
        else {
            evt = document.createEvent('CustomEvent');
            evt.initCustomEvent(evtType, shouldBubble, false, evtData);
        }
        this.root.dispatchEvent(evt);
    };
    return MDCComponent;
}());
export { MDCComponent };
// tslint:disable-next-line:no-default-export Needed for backward compatibility with MDC Web v0.44.0 and earlier.
export default MDCComponent;
//# sourceMappingURL=component.js.map


text:
namespace network {

namespace cors {

namespace {

const auto kAllowSubdomains = mojom::CorsDomainMatchMode::kAllowSubdomains;
const auto kDisallowSubdomains =
    mojom::CorsDomainMatchMode::kDisallowSubdomains;
const auto kAllowAnyPort = mojom::CorsPortMatchMode::kAllowAnyPort;
const auto kAllowOnlySpecifiedPort =
    mojom::CorsPortMatchMode::kAllowOnlySpecifiedPort;
constexpr uint16_t kHttpsPort = 443;
constexpr uint16_t kAnyPort = 0;

// OriginAccessListTest is a out of blink version of blink::SecurityPolicyTest,
// but it contains only tests for the allow/block lists management.
class OriginAccessListTest : public testing::Test {
 public:
  OriginAccessListTest()
      : https_example_origin_(url::Origin::Create(GURL("https://example.com"))),
        https_another_port_example_origin_(
            url::Origin::Create(GURL("https://example.com:10443"))),
        https_sub_example_origin_(
            url::Origin::Create(GURL("https://sub.example.com"))),
        http_example_origin_(url::Origin::Create(GURL("http://example.com"))),
        https_google_origin_(url::Origin::Create(GURL("https://google.com"))),
        source_origin_(url::Origin::Create(GURL("https://chromium.org"))) {}

  ~OriginAccessListTest() override = default;

 protected:
  const url::Origin& https_example_origin() const {
    return https_example_origin_;
  }
  const url::Origin& https_another_port_example_origin() const {
    return https_another_port_example_origin_;
  }
  const url::Origin& https_sub_example_origin() const {
    return https_sub_example_origin_;
  }
  const url::Origin& http_example_origin() const {
    return http_example_origin_;
  }
  const url::Origin& https_google_origin() const {
    return https_google_origin_;
  }
  const url::Origin& source_origin() const { return source_origin_; }
  OriginAccessList::AccessState CheckAccess(
      const url::Origin& request_initiator,
      const base::Optional<url::Origin>& isolated_world_origin,
      const GURL& url) {
    ResourceRequest request;
    request.url = url;
    request.request_initiator = request_initiator;
    request.isolated_world_origin = isolated_world_origin;
    return list_.CheckAccessState(request);
  }
  bool IsAllowed(const url::Origin& destination_origin) const {
    return list_.CheckAccessState(source_origin_,
                                  destination_origin.GetURL()) ==
           OriginAccessList::AccessState::kAllowed;
  }
  void SetAllowListEntry(const std::string& protocol,
                         const std::string& host,
                         const uint16_t port,
                         const mojom::CorsDomainMatchMode domain_match_mode,
                         const mojom::CorsPortMatchMode port_match_mode) {
    std::vector<mojom::CorsOriginPatternPtr> patterns;
    patterns.push_back(mojom::CorsOriginPattern::New(
        protocol, host, port, domain_match_mode, port_match_mode,
        mojom::CorsOriginAccessMatchPriority::kDefaultPriority));
    list_.SetAllowListForOrigin(source_origin_, patterns);
  }
  void AddAllowListEntry(const std::string& protocol,
                         const std::string& host,
                         const uint16_t port,
                         const mojom::CorsDomainMatchMode domain_match_mode,
                         const mojom::CorsPortMatchMode port_match_mode,
                         const mojom::CorsOriginAccessMatchPriority priority) {
    list_.AddAllowListEntryForOrigin(source_origin_, protocol, host, port,
                                     domain_match_mode, port_match_mode,
                                     priority);
  }
  void SetBlockListEntry(const std::string& protocol,
                         const std::string& host,
                         const int16_t port,
                         const mojom::CorsDomainMatchMode domain_match_mode,
                         const mojom::CorsPortMatchMode port_match_mode) {
    std::vector<mojom::CorsOriginPatternPtr> patterns;
    patterns.push_back(mojom::CorsOriginPattern::New(
        protocol, host, port, domain_match_mode, port_match_mode,
        mojom::CorsOriginAccessMatchPriority::kDefaultPriority));
    list_.SetBlockListForOrigin(source_origin_, patterns);
  }
  void AddBlockListEntry(const std::string& protocol,
                         const std::string& host,
                         const uint16_t port,
                         const mojom::CorsDomainMatchMode domain_match_mode,
                         const mojom::CorsPortMatchMode port_match_mode,
                         const mojom::CorsOriginAccessMatchPriority priority) {
    list_.AddBlockListEntryForOrigin(source_origin_, protocol, host, port,
                                     domain_match_mode, port_match_mode,
                                     priority);
  }
  void ResetLists() { list_.Clear(); }

 private:
  url::Origin https_example_origin_;
  url::Origin https_another_port_example_origin_;
  url::Origin https_sub_example_origin_;
  url::Origin http_example_origin_;
  url::Origin https_google_origin_;

  url::Origin source_origin_;

  OriginAccessList list_;

  DISALLOW_COPY_AND_ASSIGN(OriginAccessListTest);
};

TEST_F(OriginAccessListTest, IsAccessAllowedWithPort) {
  // By default, no access should be allowed.
  EXPECT_FALSE(IsAllowed(https_example_origin()));

  // Adding access for https://example.com should work, but should not grant
  // access to different ports for the same scheme:host pair.
  SetAllowListEntry("https", "example.com", kHttpsPort, kDisallowSubdomains,
                    kAllowOnlySpecifiedPort);
  EXPECT_TRUE(IsAllowed(https_example_origin()));
  EXPECT_FALSE(IsAllowed(https_another_port_example_origin()));

  // Another entry can overwrite to allow any port.
  SetAllowListEntry("https", "example.com", kAnyPort, kDisallowSubdomains,
                    kAllowAnyPort);
  EXPECT_TRUE(IsAllowed(https_example_origin()));
  EXPECT_TRUE(IsAllowed(https_another_port_example_origin()));
}

TEST_F(OriginAccessListTest, IsAccessAllowedForIsolatedWorldOrigin) {
  // By default, no access should be allowed.
  EXPECT_FALSE(IsAllowed(https_example_origin()));

  // Adding access for https://example.com should work, but should not grant
  // access to different ports for the same scheme:host pair.
  GURL target("https://example.com");
  SetAllowListEntry(target.scheme(), target.host(), kHttpsPort,
                    kDisallowSubdomains, kAllowOnlySpecifiedPort);

  // When request is made by a Chrome Extension background page,
  // request_initiator is the origin that should be used as a key for
  // OriginAccessList.
  EXPECT_EQ(OriginAccessList::AccessState::kAllowed,
            CheckAccess(source_origin(), base::nullopt, target));

  // When request is made by a Chrome Extension content script,
  // isolated_world_origin is the origin that should be used as a key for
  // OriginAccessList.
  EXPECT_EQ(OriginAccessList::AccessState::kAllowed,
            CheckAccess(https_another_port_example_origin(), source_origin(),
                        target));

  // Impossible situation with Chrome Extensions - the isolated_world_origin is
  // non-empty, but request_intiator is the key in the OriginAccessList.  In
  // this impossible situation it is okay to indicate that no entry is listed
  // in the OriginAccessList.
  EXPECT_EQ(OriginAccessList::AccessState::kNotListed,
            CheckAccess(source_origin(), https_another_port_example_origin(),
                        target));
}

TEST_F(OriginAccessListTest, IsAccessAllowed) {
  // By default, no access should be allowed.
  EXPECT_FALSE(IsAllowed(https_example_origin()));
  EXPECT_FALSE(IsAllowed(https_sub_example_origin()));
  EXPECT_FALSE(IsAllowed(http_example_origin()));

  // Adding access for https://example.com should work, but should not grant
  // access to subdomains or other schemes.
  SetAllowListEntry("https", "example.com", kAnyPort, kDisallowSubdomains,
                    kAllowAnyPort);
  EXPECT_TRUE(IsAllowed(https_example_origin()));
  EXPECT_FALSE(IsAllowed(https_sub_example_origin()));
  EXPECT_FALSE(IsAllowed(http_example_origin()));

  // Clearing the map should revoke all special access.
  ResetLists();
  EXPECT_FALSE(IsAllowed(https_example_origin()));
  EXPECT_FALSE(IsAllowed(https_sub_example_origin()));
  EXPECT_FALSE(IsAllowed(http_example_origin()));

  // Adding an entry that matches subdomains should grant access to any
  // subdomains.
  AddAllowListEntry("https", "example.com", kAnyPort, kAllowSubdomains,
                    kAllowAnyPort,
                    mojom::CorsOriginAccessMatchPriority::kDefaultPriority);
  EXPECT_TRUE(IsAllowed(https_example_origin()));
  EXPECT_TRUE(IsAllowed(https_sub_example_origin()));
  EXPECT_FALSE(IsAllowed(http_example_origin()));
}

TEST_F(OriginAccessListTest, IsAccessAllowedWildCard) {
  // An empty domain that matches subdomains results in matching every domain.
  SetAllowListEntry("https", "", kAnyPort, kAllowSubdomains, kAllowAnyPort);
  EXPECT_TRUE(IsAllowed(https_example_origin()));
  EXPECT_TRUE(IsAllowed(https_google_origin()));
  EXPECT_FALSE(IsAllowed(http_example_origin()));
}

TEST_F(OriginAccessListTest, IsAccessAllowedWithBlockListEntry) {
  // The block list takes priority over the allow list.
  SetAllowListEntry("https", "example.com", kAnyPort, kAllowSubdomains,
                    kAllowAnyPort);
  SetBlockListEntry("https", "example.com", kAnyPort, kDisallowSubdomains,
                    kAllowAnyPort);

  EXPECT_FALSE(IsAllowed(https_example_origin()));
  EXPECT_TRUE(IsAllowed(https_sub_example_origin()));
}

TEST_F(OriginAccessListTest, IsAccessAllowedWildcardWithBlockListEntry) {
  SetAllowListEntry("https", "", kAnyPort, kAllowSubdomains, kAllowAnyPort);
  AddBlockListEntry("https", "google.com", kAnyPort, kDisallowSubdomains,
                    kAllowAnyPort,
                    mojom::CorsOriginAccessMatchPriority::kDefaultPriority);

  EXPECT_TRUE(IsAllowed(https_example_origin()));
  EXPECT_FALSE(IsAllowed(https_google_origin()));
}

TEST_F(OriginAccessListTest, IsPriorityRespected) {
  SetAllowListEntry("https", "example.com", kAnyPort, kAllowSubdomains,
                    kAllowAnyPort);
  EXPECT_TRUE(IsAllowed(https_example_origin()));
  EXPECT_TRUE(IsAllowed(https_sub_example_origin()));

  // Higher priority blocklist overrides lower priority allowlist.
  AddBlockListEntry("https", "example.com", kAnyPort, kAllowSubdomains,
                    kAllowAnyPort,
                    mojom::CorsOriginAccessMatchPriority::kLowPriority);
  EXPECT_FALSE(IsAllowed(https_example_origin()));
  EXPECT_FALSE(IsAllowed(https_sub_example_origin()));

  // Higher priority allowlist overrides lower priority blocklist.
  AddAllowListEntry("https", "example.com", kAnyPort, kDisallowSubdomains,
                    kAllowAnyPort,
                    mojom::CorsOriginAccessMatchPriority::kMediumPriority);
  EXPECT_TRUE(IsAllowed(https_example_origin()));
  EXPECT_FALSE(IsAllowed(https_sub_example_origin()));
}

TEST_F(OriginAccessListTest, IsPriorityRespectedReverse) {
  AddAllowListEntry("https", "example.com", kAnyPort, kDisallowSubdomains,
                    kAllowAnyPort,
                    mojom::CorsOriginAccessMatchPriority::kMediumPriority);
  EXPECT_TRUE(IsAllowed(https_example_origin()));
  EXPECT_FALSE(IsAllowed(https_sub_example_origin()));

  AddBlockListEntry("https", "example.com", kAnyPort, kAllowSubdomains,
                    kAllowAnyPort,
                    mojom::CorsOriginAccessMatchPriority::kLowPriority);
  EXPECT_TRUE(IsAllowed(https_example_origin()));
  EXPECT_FALSE(IsAllowed(https_sub_example_origin()));

  AddAllowListEntry("https", "example.com", kAnyPort, kAllowSubdomains,
                    kAllowAnyPort,
                    mojom::CorsOriginAccessMatchPriority::kDefaultPriority);
  EXPECT_TRUE(IsAllowed(https_example_origin()));
  EXPECT_FALSE(IsAllowed(https_sub_example_origin()));
}

TEST_F(OriginAccessListTest, CreateCorsOriginAccessPatternsList) {
  const url::Origin kOrigin1 =
      url::Origin::Create(GURL("https://foo.google.com"));
  const url::Origin kOrigin2 =
      url::Origin::Create(GURL("https://bar.google.com"));
  const std::string kProtocol = "https";
  const std::string kDomain1 = "foo.example.com";
  const std::string kDomain2 = "bar.example.com";
  const uint16_t kPort1 = kAnyPort;
  const uint16_t kPort2 = kHttpsPort;

  OriginAccessList list;
  list.AddAllowListEntryForOrigin(
      kOrigin1, kProtocol, kDomain1, kPort1, kAllowSubdomains, kAllowAnyPort,
      mojom::CorsOriginAccessMatchPriority::kMediumPriority);
  list.AddBlockListEntryForOrigin(
      kOrigin2, kProtocol, kDomain2, kPort2, kDisallowSubdomains,
      kAllowOnlySpecifiedPort,
      mojom::CorsOriginAccessMatchPriority::kDefaultPriority);

  std::vector<mojom::CorsOriginAccessPatternsPtr> patterns =
      list.CreateCorsOriginAccessPatternsList();
  bool found_origin1 = false;
  bool found_origin2 = false;
  for (const auto& pattern : patterns) {
    if (pattern->source_origin == kOrigin1) {
      EXPECT_FALSE(found_origin1);
      found_origin1 = true;

      EXPECT_EQ(0u, pattern->block_patterns.size());
      ASSERT_EQ(1u, pattern->allow_patterns.size());
      EXPECT_EQ(kProtocol, pattern->allow_patterns[0]->protocol);
      EXPECT_EQ(kDomain1, pattern->allow_patterns[0]->domain);
      EXPECT_EQ(kPort1, pattern->allow_patterns[0]->port);
      EXPECT_EQ(kAllowSubdomains,
                pattern->allow_patterns[0]->domain_match_mode);
      EXPECT_EQ(kAllowAnyPort, pattern->allow_patterns[0]->port_match_mode);
      EXPECT_EQ(mojom::CorsOriginAccessMatchPriority::kMediumPriority,
                pattern->allow_patterns[0]->priority);
    } else if (pattern->source_origin == kOrigin2) {
      EXPECT_FALSE(found_origin2);
      found_origin2 = true;

      EXPECT_EQ(0u, pattern->allow_patterns.size());
      ASSERT_EQ(1u, pattern->block_patterns.size());
      EXPECT_EQ(kProtocol, pattern->block_patterns[0]->protocol);
      EXPECT_EQ(kDomain2, pattern->block_patterns[0]->domain);
      EXPECT_EQ(kPort2, pattern->block_patterns[0]->port);
      EXPECT_EQ(kDisallowSubdomains,
                pattern->block_patterns[0]->domain_match_mode);
      EXPECT_EQ(kAllowOnlySpecifiedPort,
                pattern->block_patterns[0]->port_match_mode);
      EXPECT_EQ(mojom::CorsOriginAccessMatchPriority::kDefaultPriority,
                pattern->block_patterns[0]->priority);
    } else {
      FAIL();
    }
  }
  EXPECT_TRUE(found_origin1);
  EXPECT_TRUE(found_origin2);
}

}  // namespace

}  // namespace cors

}  // namespace network


text:
import web
from datetime import datetime

def current_time_as_string(format='iso'):
    assert(format in ['iso', 'web'])

    if format == 'iso':
        return datetime.now().isoformat(' ')
    else:
        web.net.httpdate(datetime.now())


text:
easy_quiz = """For 2016 Presidential Election race, the leading female Democratic candidate's
first name is ____1____ and her last name is ____2____. The other leading male Democratic
candidate's first name is ____3____ and his last name is ____4____."""

medium_quiz = """For 2016 Presidential Election race, there are 4 remaining republican
candidates. Donald Trump is Chairman of The ____1____ Organization, Marco Rubio is
a Senator from ____2____, John Kasich is a Governor from ____3____, and Ted Cruz is
a Senator from ____4____."""

hard_quiz = """While they withdrew pretty quickly, there were 4 other dem candidates
for 2016 US Presidential Election. They are Martin ____1____, Lawrence ____2____,
Lincoln ____3____, and Jim ____4____."""

blank  = ["____1____", "____2____", "____3____", "____4____"]
level = ["Easy", "Medium", "Hard"]
quiz_sentence = [easy_quiz, medium_quiz, hard_quiz]
answer_list = [["Hillary", "Clinton", "Bernie", "Sanders"], ["Trump", "Florida", "Ohio", "Texas"], ["O'Malley", "Lessig", "Chafee", "Webb"]]
quiz_title = "2016 Election Quiz"

def word_in_pos(word, parts_of_speech):
	""" Takes a string and a list of strings. Return the string with the first letter capitalized if word is
	in fact in the list (parts_of_speech). If not, it will return None"""
	parts_of_speech = [x.lower() for x in parts_of_speech] # lowercasing the comparison list
	word = word.lower() # lowercasing the word to compare
	for e in parts_of_speech:
		if e in word:
			e = e.title() # Capitalizing the found word
			return e
	return None

def header_format(word):
	"""Takes a string, and format it as a header for easy readability like ==== example ===="""
	title_length = len(word)
	word = word.title()	# Makig the first letter of every word to be capitalized automatically
	full_length = 60
	symbol_needed = full_length - title_length
	if symbol_needed % 2 == 0:	# Fixing one character being off sometimes
		header_left = symbol_needed / 2
		header_right = header_left
	else:
		header_left = symbol_needed / 2
		header_right = header_left + 1
	header = "=" * header_left + " " + word + " " + "=" * header_right +  "\n"
	print header
	return

def level_selection():
	"""Prompt user to select the game level. If invalid input, re-prompt.
	If valid, return the index number of the level list"""
	index = 0
	while index == 0:
		header_format("Level Selection")
		print "Welcome to " + quiz_title + "!"
		user_input = raw_input("Select your level: Easy, Medium, Hard: ")
		level_selected = word_in_pos(user_input, level)
		if level_selected == None:
			print "Not a valid level. Choose again"
		else:
			print "You chose " + level_selected + "! Good Luck!" +  "\n"
			index += 1
			level_index = level.index(level_selected)
	return level_index

def replace_with_answer2(quiz, blank, answer): # holy cow, this is so much simpler
	"""takes a quiz sentence, blank to be filled, an answer, and retry limit. Prompt user to provide and answer and
	check if the provided answer matches the correct answer. if the user hits the retry limit, it breaks
	out from the function"""
	print quiz
	index = 0
	while index == 0:
		user_input = raw_input("What should go in " + blank + "?: ").lower()
		if user_input == answer.lower():
			print "Correct! \n"
			quiz = quiz.replace(blank, answer)
			index += 1
		else:
			print "Incorrect! Try again! \n"
	return quiz

def play_game():
	"""when ran, it asks for a difficulty level, and spit out a pre-defined quiz for the given level.
	User is prompted to fill in the blanks until they successfully finish the quiz"""
	level_index = level_selection()
	selected_quiz = quiz_sentence[level_index]
	header_format("Quiz: " + level[level_index])
	index = 0
	while index < len(blank):
		corresponding_answer = answer_list[level_index][index]
		corresponding_blank = blank[index]
		selected_quiz = replace_with_answer2(selected_quiz, corresponding_blank, corresponding_answer)
		index += 1
	header_format("You successfully answered all questions!")
	print selected_quiz +  "\n"
	return

play_game()


text:
using System;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace ComicBook
{
    [Activity(Label = "ComicBook", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            global::Xamarin.Forms.Forms.Init(this, bundle);

            //-----------------------------------------------------------------------------------------------
            // Xamarin.Auth initialization

            // Presenters Initialization
            global::Xamarin.Auth.Presenters.XamarinAndroid.AuthenticationConfiguration.Init(this, bundle);

            // User-Agent tweaks for Embedded WebViews
            global::Xamarin.Auth.WebViewConfiguration.Android.UserAgent = "moljac++";

            // Xamarin.Auth CustomTabs Initialization/Customisation
            global::Xamarin.Auth.CustomTabsConfiguration.ActionLabel = null;
            global::Xamarin.Auth.CustomTabsConfiguration.MenuItemTitle = null;
            global::Xamarin.Auth.CustomTabsConfiguration.AreAnimationsUsed = true;
            global::Xamarin.Auth.CustomTabsConfiguration.IsShowTitleUsed = false;
            global::Xamarin.Auth.CustomTabsConfiguration.IsUrlBarHidingUsed = false;
            global::Xamarin.Auth.CustomTabsConfiguration.IsCloseButtonIconUsed = false;
            global::Xamarin.Auth.CustomTabsConfiguration.IsActionButtonUsed = false;
            global::Xamarin.Auth.CustomTabsConfiguration.IsActionBarToolbarIconUsed = false;
            global::Xamarin.Auth.CustomTabsConfiguration.IsDefaultShareMenuItemUsed = false;

            global::Android.Graphics.Color color_xamarin_blue;
            color_xamarin_blue = new global::Android.Graphics.Color(0x34, 0x98, 0xdb);
            global::Xamarin.Auth.CustomTabsConfiguration.ToolbarColor = color_xamarin_blue;

            // ActivityFlags for tweaking closing of CustomTabs
            // please report findings!
            global::Xamarin.Auth.CustomTabsConfiguration.
               ActivityFlags =
                    global::Android.Content.ActivityFlags.NoHistory
                    |
                    global::Android.Content.ActivityFlags.SingleTop
                    |
                    global::Android.Content.ActivityFlags.NewTask
                    ;

            global::Xamarin.Auth.CustomTabsConfiguration.IsWarmUpUsed = true;
            global::Xamarin.Auth.CustomTabsConfiguration.IsPrefetchUsed = true;

            //-----------------------------------------------------------------------------------------------

            LoadApplication(new App());
        }
    }
}


text:
import { Manager } from './shell';
import { Builder } from './builder';
import { http } from '@ennube/runtime';
export declare class Server implements Manager {
    serve(builder: Builder): Promise<void>;
    matchers: ((httpEvent: http.RequestData) => boolean)[];
    private buildMatchers();
    private buildMatcher(gateway, resource);
    requestHandler(request: any, response: any): void;
}


text:
//
//  CMWalletFlowLayout.m
//  CMCollectionFlowLayouts
//
//  Created by CrabMan on 2018/4/30.
//  Copyright © 2018年 CrabMan. All rights reserved.
//

#import "CMWalletFlowLayout.h"

@interface CMWalletFlowLayout ()

/**保存layoutattribute的数组*/
@property (nonatomic,strong) NSArray *layoutAttrs;

@property (nonatomic,strong) NSIndexPath *currentIndexPath;

@property (nonatomic,assign) BOOL isExtend;

@end

@implementation CMWalletFlowLayout

- (void)prepareLayout {

    [super prepareLayout];

    UIEdgeInsets inset = self.collectionView.contentInset;
    self.itemSize = CGSizeMake(CMCollectionW - inset.right - inset.left, CMCellH);
    self.minimumLineSpacing = CMFoldCellMinSpace - CMCellH;

}

- (NSArray *)resolveCellAttributesInRect:(CGRect)rect {

    NSMutableArray *mutableArr = [NSMutableArray array];

    NSInteger itemCount = [self.collectionView numberOfItemsInSection:0];

    CGFloat offsetY = self.collectionView.contentOffset.y;

    UIEdgeInsets contentInset = self.collectionView.contentInset;

    //展开后底部多余的index
    NSInteger shrinkCellIndex = 0;

    for (NSInteger row = 0; row < itemCount; row++) {

        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:row inSection:0];
        UICollectionViewLayoutAttributes *att = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
        //吸顶效果
        CGRect cellRect = CGRectMake(0, MAX(offsetY, row * CMFoldCellMinSpace), CMCollectionW - contentInset.right - contentInset.left, CMCellH);

        CGFloat top = shrinkCellIndex * CMExtendCellMinSpace + 20;
        CGFloat left = (4 - shrinkCellIndex) * 5;

        //如果点击展开后的布局
        if (self.isExtend && self.currentIndexPath.item == indexPath.item) {
            cellRect = CGRectMake(0, offsetY, CMCollectionW - contentInset.right - contentInset.left, CMCollectionH - CMExtendedCellFooter);
        } else if (self.isExtend && self.currentIndexPath.item != indexPath.item) {

            cellRect = CGRectMake(left,offsetY + CMCollectionH - CMExtendedCellFooter + top, CMCollectionW -contentInset.left - contentInset.right - left * 2, CMCellH);
            shrinkCellIndex ++;
            shrinkCellIndex = MIN(row, 3);
        }

        att.frame = cellRect;
       // att.zIndex = row * 2;
        att.transform3D = CATransform3DMakeTranslation(0, 0, row * 2);

        if (CGRectIntersectsRect(cellRect, rect) || CGRectContainsRect(cellRect, rect)) {
            [mutableArr addObject:att];
        }

    }
    self.layoutAttrs = [mutableArr copy];

    return self.layoutAttrs;
}

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    return YES;
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {

    return [self resolveCellAttributesInRect:rect];

}

- (CGSize)collectionViewContentSize {
    UIEdgeInsets contentInset = self.collectionView.contentInset;
    NSInteger itemCount = [self.collectionView numberOfItemsInSection:0];
    CGSize contentSize = CGSizeMake(CMCollectionW - contentInset.left - contentInset.right, (itemCount - 1) * CMFoldCellMinSpace + CMCellH);

    return contentSize;

}

- (void)extendCell {

    self.isExtend = YES;
    [self.collectionView performBatchUpdates:^{

        [self invalidateLayout];

    } completion:^(BOOL finished) {
        self.collectionView.scrollEnabled = NO;
    }];

}

- (void)foldCell {

    self.isExtend = NO;

    [self.collectionView performBatchUpdates:^{

        [self invalidateLayout];

    } completion:^(BOOL finished) {
        self.collectionView.scrollEnabled = YES;
    }];

}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    if (self.isExtend) {
        [self foldCell];
    } else {

        self.currentIndexPath = indexPath;
        [self extendCell];
    }
}

@end


text:
namespace GSMTaskMain
{
    using System;
    using System.Text;

    public class Owner
    {
        private string firstName;
        private string lastName;
        private int age;

        public Owner(string firstName, string lastName, int age)
            : this(firstName, lastName)
        {
            this.Age = age;
        }

        public Owner(string firstName, string lastName)
            : this(firstName)
        {
            this.LastName = lastName;
        }

        public Owner(string firstName)
        {
            this.firstName = firstName;
        }

        public string FirstName
        {
            get
            {
                return this.firstName;
            }

            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    throw new ArgumentNullException("Owner first name cannot be null or empty!");
                }

                this.firstName = value;
            }
        }

        public string LastName
        {
            get
            {
                return this.lastName;
            }

            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    throw new ArgumentNullException("Owner last name cannot be null or empty!");
                }

                this.lastName = value;
            }
        }

        public int Age
        {
            get
            {
                return this.age;
            }

            set
            {
                if (value < 3)
                {
                    throw new ArgumentException("Owner age cannot be smaller than 3!");
                }

                this.age = value;
            }
        }

        public override string ToString()
        {
            var result = new StringBuilder();

            result.AppendLine(string.Format("- Owner first name: {0}", this.FirstName));

            if (this.LastName != null)
            {
                result.AppendLine(string.Format("- Owner last name: {0}", this.LastName));
            }

            if (this.Age != null)
            {
                result.AppendLine(string.Format("- Owner age: {0}", this.Age));
            }

            return result.ToString().Trim();
        }
    }
}


text:
namespace arc {
// Calculate the window content bounds (excluding caption if it exists) in the
// root window.
gfx::RectF input_overlay::CalculateWindowContentBounds(aura::Window* window) {
  DCHECK(window);
  auto* widget = views::Widget::GetWidgetForNativeView(window);
  DCHECK(widget->non_client_view());
  auto* frame_view = widget->non_client_view()->frame_view();
  DCHECK(frame_view);
  int height = frame_view->GetBoundsForClientView().y();
  auto bounds = gfx::RectF(window->bounds());
  bounds.Inset(0, height, 0, 0);
  return bounds;
}

TouchInjector::TouchInjector(aura::Window* top_level_window)
    : target_window_(top_level_window) {}

TouchInjector::~TouchInjector() {
  UnRegisterEventRewriter();
}

void TouchInjector::ParseActions(const base::Value& root) {
  auto parsed_actions = ParseJsonToActions(target_window_, root);
  if (!parsed_actions)
    return;
  std::move(parsed_actions->begin(), parsed_actions->end(),
            std::back_inserter(actions_));
}

void TouchInjector::NotifyTextInputState(bool active) {
  if (text_input_active_ != active && active)
    DispatchTouchCancelEvent();
  text_input_active_ = active;
}

void TouchInjector::RegisterEventRewriter() {
  if (observation_.IsObserving())
    return;
  observation_.Observe(target_window_->GetHost()->GetEventSource());
}

void TouchInjector::UnRegisterEventRewriter() {
  if (!observation_.IsObserving())
    return;
  DispatchTouchCancelEvent();
  observation_.Reset();
}

void TouchInjector::DispatchTouchCancelEvent() {
  for (auto& action : actions_) {
    auto cancel = action->GetTouchCancelEvent();
    if (!cancel)
      continue;
    if (SendEventFinally(continuation_, &*cancel).dispatcher_destroyed) {
      VLOG(0) << "Undispatched event due to destroyed dispatcher for canceling "
                 "touch event.";
    }
  }
}

void TouchInjector::SendTouchMoveEvent(
    const ui::EventRewriter::Continuation continuation,
    const ui::TouchEvent& event) {
  if (SendEventFinally(continuation, &event).dispatcher_destroyed) {
    VLOG(0) << "Undispatched event due to destroyed dispatcher for "
               "touch move event.";
  }
}

////////////////////////////////////////////////////////////////////////////////
// ui::EventRewriter
ui::EventDispatchDetails TouchInjector::RewriteEvent(
    const ui::Event& event,
    const ui::EventRewriter::Continuation continuation) {
  continuation_ = continuation;
  if (text_input_active_)
    return SendEvent(continuation, &event);

  auto bounds = input_overlay::CalculateWindowContentBounds(target_window_);

  std::list<ui::TouchEvent> touch_events;
  for (auto& action : actions_) {
    bool rewritten = action->RewriteEvent(event, touch_events, bounds);
    if (!rewritten)
      continue;
    if (touch_events.empty())
      return DiscardEvent(continuation);
    if (touch_events.size() == 1)
      return SendEventFinally(continuation, &touch_events.front());
    if (touch_events.size() == 2) {
      // Some apps can't process correctly on the touch move event which follows
      // touch press event immediately, so send the touch move event delayed
      // here.
      base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
          FROM_HERE,
          base::BindOnce(&TouchInjector::SendTouchMoveEvent,
                         weak_ptr_factory_.GetWeakPtr(), continuation,
                         touch_events.back()),
          input_overlay::kSendTouchMoveDelay);
      return SendEventFinally(continuation, &touch_events.front());
    }
  }
  return SendEvent(continuation, &event);
}

}  // namespace arc


text:
#ifndef __domInputLocal_h__
#define __domInputLocal_h__

#include <dae/daeDocument.h>
#include <dom/domTypes.h>
#include <dom/domElements.h>

class DAE;

/**
 * The InputLocal type is used to represent inputs that can only reference
 * resources declared in the same document.
 */
class domInputLocal_complexType
{
protected:  // Attributes
/**
 *  The semantic attribute is the user-defined meaning of the input connection.
 * Required attribute.
 */
	xsNMTOKEN attrSemantic;
/**
 *  The source attribute indicates the location of the data source. Required
 * attribute.
 */
	domURIFragmentType attrSource;

public:	//Accessors and Mutators
	/**
	 * Gets the semantic attribute.
	 * @return Returns a xsNMTOKEN of the semantic attribute.
	 */
	xsNMTOKEN getSemantic() const { return attrSemantic; }
	/**
	 * Sets the semantic attribute.
	 * @param atSemantic The new value for the semantic attribute.
	 */
	void setSemantic( xsNMTOKEN atSemantic ) { *(daeStringRef*)&attrSemantic = atSemantic;}

	/**
	 * Gets the source attribute.
	 * @return Returns a domURIFragmentType reference of the source attribute.
	 */
	domURIFragmentType &getSource() { return attrSource; }
	/**
	 * Gets the source attribute.
	 * @return Returns a constant domURIFragmentType reference of the source attribute.
	 */
	const domURIFragmentType &getSource() const { return attrSource; }
	/**
	 * Sets the source attribute.
	 * @param atSource The new value for the source attribute.
	 */
	void setSource( const domURIFragmentType &atSource ) { attrSource = atSource; }
	/**
	 * Sets the source attribute.
	 * @param atSource The new value for the source attribute.
	 */
	void setSource( xsString atSource ) { attrSource = atSource; }

protected:
	/**
	 * Constructor
	 */
	domInputLocal_complexType(DAE& dae, daeElement* elt) : attrSemantic(), attrSource(dae, *elt) {}
	/**
	 * Destructor
	 */
	virtual ~domInputLocal_complexType() {}
	/**
	 * Overloaded assignment operator
	 */
	domInputLocal_complexType &operator=(const domInputLocal_complexType&) { return *this; }
};

/**
 * An element of type domInputLocal_complexType.
 */
class domInputLocal : public daeElement, public domInputLocal_complexType
{
public:
	virtual COLLADA_TYPE::TypeEnum getElementType() const { return COLLADA_TYPE::INPUTLOCAL; }
	static daeInt ID() { return 1; }
	virtual daeInt typeID() const { return ID(); }

public:	//Accessors and Mutators
	/**
	 * Gets the semantic attribute.
	 * @return Returns a xsNMTOKEN of the semantic attribute.
	 */
	xsNMTOKEN getSemantic() const { return attrSemantic; }
	/**
	 * Sets the semantic attribute.
	 * @param atSemantic The new value for the semantic attribute.
	 */
	void setSemantic( xsNMTOKEN atSemantic ) { *(daeStringRef*)&attrSemantic = atSemantic; _validAttributeArray[0] = true; }

	/**
	 * Gets the source attribute.
	 * @return Returns a domURIFragmentType reference of the source attribute.
	 */
	domURIFragmentType &getSource() { return attrSource; }
	/**
	 * Gets the source attribute.
	 * @return Returns a constant domURIFragmentType reference of the source attribute.
	 */
	const domURIFragmentType &getSource() const { return attrSource; }
	/**
	 * Sets the source attribute.
	 * @param atSource The new value for the source attribute.
	 */
	void setSource( const domURIFragmentType &atSource ) { attrSource = atSource; _validAttributeArray[1] = true; }
	/**
	 * Sets the source attribute.
	 * @param atSource The new value for the source attribute.
	 */
	void setSource( xsString atSource ) { attrSource = atSource; _validAttributeArray[1] = true; }

protected:
	/**
	 * Constructor
	 */
	domInputLocal(DAE& dae) : daeElement(dae), domInputLocal_complexType(dae, this) {}
	/**
	 * Destructor
	 */
	virtual ~domInputLocal() {}
	/**
	 * Overloaded assignment operator
	 */
	domInputLocal &operator=(const domInputLocal&) { return *this; }

public: // STATIC METHODS
	/**
	 * Creates an instance of this class and returns a daeElementRef referencing it.
	 * @return a daeElementRef referencing an instance of this object.
	 */
	static DLLSPEC daeElementRef create(DAE& dae);
	/**
	 * Creates a daeMetaElement object that describes this element in the meta object reflection framework.
	 * If a daeMetaElement already exists it will return that instead of creating a new one.
	 * @return A daeMetaElement describing this COLLADA element.
	 */
	static DLLSPEC daeMetaElement* registerElement(DAE& dae);
};

#endif


text:
(function(angular, $, _) {

  // Controller for the in-place msg-template management
  angular.module('crmMailing').controller('MsgTemplateCtrl', function MsgTemplateCtrl($scope, crmMsgTemplates, dialogService) {
    var ts = $scope.ts = CRM.ts(null);
    $scope.crmMsgTemplates = crmMsgTemplates;
    $scope.checkPerm = CRM.checkPerm;
    // @return Promise MessageTemplate (per APIv3)
    $scope.saveTemplate = function saveTemplate(mailing) {
      var model = {
        selected_id: mailing.msg_template_id,
        tpl: {
          msg_title: '',
          msg_subject: mailing.subject,
          msg_text: mailing.body_text,
          msg_html: mailing.body_html
        }
      };
      var options = CRM.utils.adjustDialogDefaults({
        autoOpen: false,
        height: 'auto',
        width: '40%',
        title: ts('Save Template')
      });
      return dialogService.open('saveTemplateDialog', '~/crmMailing/SaveMsgTemplateDialogCtrl.html', model, options)
        .then(function(item) {
          mailing.msg_template_id = item.id;
          return item;
        });
    };

    // @param int id
    // @return Promise
    $scope.loadTemplate = function loadTemplate(mailing, id) {
      return crmMsgTemplates.get(id).then(function(tpl) {
        mailing.subject = tpl.msg_subject;
        mailing.body_text = tpl.msg_text;
        mailing.body_html = tpl.msg_html;
      });
    };
  });

})(angular, CRM.$, CRM._);


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "dictionary".
 *
 * @property integer $id
 * @property string $word
 */
class Dictionary extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'dictionary';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['word'], 'required'],
            [['word'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'word' => 'Word',
        ];
    }
}


text:
namespace blink {
class PageState;
}

namespace IPC {

template <>
struct CONTENT_EXPORT ParamTraits<blink::PageState> {
  typedef blink::PageState param_type;
  static void Write(base::Pickle* m, const param_type& p);
  static bool Read(const base::Pickle* m,
                   base::PickleIterator* iter,
                   param_type* p);
  static void Log(const param_type& p, std::string* l);
};

template <>
struct ParamTraits<gfx::NativeWindow> {
  typedef gfx::NativeWindow param_type;
  static void Write(base::Pickle* m, const param_type& p) {
#if BUILDFLAG(IS_WIN)
    m->WriteUInt32(base::win::HandleToUint32(p));
#else
    m->WriteData(reinterpret_cast<const char*>(&p), sizeof(p));
#endif
  }
  static bool Read(const base::Pickle* m,
                   base::PickleIterator* iter,
                   param_type* r) {
#if BUILDFLAG(IS_WIN)
    return iter->ReadUInt32(reinterpret_cast<uint32_t*>(r));
#else
    const char *data;
    size_t data_size = 0;
    bool result = iter->ReadData(&data, &data_size);
    if (result && data_size == sizeof(gfx::NativeWindow)) {
      memcpy(r, data, sizeof(gfx::NativeWindow));
    } else {
      result = false;
      NOTREACHED();
    }
    return result;
#endif
  }
  static void Log(const param_type& p, std::string* l) {
    l->append("<gfx::NativeWindow>");
  }
};

}  // namespace IPC

#endif  // CONTENT_PUBLIC_COMMON_COMMON_PARAM_TRAITS_H_