text:
<?xml version="1.0"?>
<Document>

	<Sentence>
		<value>Medullary carcinoma of the thyroid is cancer of the thyroid gland that starts in cells that release a hormone called calcitonin.</value>
		<pattern_crowdsource> [[Medullary carcinoma|C0206693]] of the thyroid is [[cancer|C0006826]] of the [[thyroid gland|C0040132]] that starts in [[cells|C0007634]] that release a [[hormone|C0019932]] called calcitonin.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Medullary carcinoma</surface-form>
				<RDF-ID>C0206693</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>cancer</surface-form>
				<RDF-ID>C0006826</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>thyroid gland</surface-form>
				<RDF-ID>C0040132</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>cells</surface-form>
				<RDF-ID>C0007634</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>hormone</surface-form>
				<RDF-ID>C0019932</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>calcitonin</surface-form>
				<RDF-ID>C0006668</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0206693 ISA C0006826</triple>
			<triple>C0006826 PART_OF C0040132</triple>
			<triple>C0007634 LOCATION_OF C0206693</triple>
			<triple>C0007634 PRODUCES C0019932</triple>
			<triple>C0206693 PART_OF C0040132</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Unlike other types of thyroid cancer, MTC is less likely to be caused by radiation therapy to the neck given to treat other cancers during childhood.</value>
		<pattern_crowdsource> Unlike other types of thyroid cancer, MTC is less likely to be caused by [[radiation therapy|C0034618]] to the neck given to treat other [[cancers|C0006826]] during childhood.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>types</surface-form>
				<RDF-ID>C0332307</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>thyroid cancer</surface-form>
				<RDF-ID>C0007115</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>MTC</surface-form>
				<RDF-ID>C0238462</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>likely</surface-form>
				<RDF-ID>C0332148</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>radiation therapy</surface-form>
				<RDF-ID>C0034618</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>neck</surface-form>
				<RDF-ID>C0027530</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>cancers</surface-form>
				<RDF-ID>C0006826</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>childhood</surface-form>
				<RDF-ID>C0231335</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0034618 TREATS C0006826</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>There are two forms of MTC:  -  Sporadic MTC, which does not run in families.</value>
		<pattern_crowdsource> There are two forms of MTC:  -  Sporadic [[MTC|C0238462]], which does not run in [[families|C0015576]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>two</surface-form>
				<RDF-ID>C0205448</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>forms</surface-form>
				<RDF-ID>C0376315</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>MTC</surface-form>
				<RDF-ID>C0238462</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Sporadic</surface-form>
				<RDF-ID>C0205422</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>MTC</surface-form>
				<RDF-ID>C0238462</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>not</surface-form>
				<RDF-ID>C1518422</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>families</surface-form>
				<RDF-ID>C0015576</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0238462 NEG_PROCESS_OF C0015576</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>-  Inherited MTC, which runs in families.</value>
		<pattern_crowdsource> -  Inherited [[MTC|C0238462]], which runs in [[families|C0015576]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Inherited</surface-form>
				<RDF-ID>C0439660</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>MTC</surface-form>
				<RDF-ID>C0238462</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>families</surface-form>
				<RDF-ID>C0015576</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0238462 PROCESS_OF C0015576</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>You have an increased risk of this type of cancer if you have:  -  A family history of MTC   -  A family history of multiple endocrine neoplasia (MEN)   -  A prior history of pheochromocytoma, mucosal neuromas, or hyperparathyroidism   Other types of thyroid cancer include:  - Anaplastic carcinoma of the thyroid  - Follicular tumor of the thyroid  - Papillary carcinoma of the thyroid  -  Thyroid lymphoma</value>
		<pattern_crowdsource> You have an increased risk of this type of [[cancer|C0006826]] if you have:  -  A family history of MTC   -  A family history of multiple endocrine neoplasia (MEN)   -  A prior history of pheochromocytoma, [[mucosal neuromas|C0878627]], or [[hyperparathyroidism|C0020502]]   Other types of thyroid cancer include:  - Anaplastic carcinoma of the thyroid  - Follicular tumor of the thyroid  - Papillary carcinoma of the thyroid  -  Thyroid lymphoma		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>increased</surface-form>
				<RDF-ID>C0205217</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>risk</surface-form>
				<RDF-ID>C0035647</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>type</surface-form>
				<RDF-ID>C1547052</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>cancer</surface-form>
				<RDF-ID>C0006826</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>family</surface-form>
				<RDF-ID>C0015576</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>history</surface-form>
				<RDF-ID>C0019665</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>MTC</surface-form>
				<RDF-ID>C0238462</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>family</surface-form>
				<RDF-ID>C0015576</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>history</surface-form>
				<RDF-ID>C0019665</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>multiple endocrine neoplasia</surface-form>
				<RDF-ID>C0027662</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>prior</surface-form>
				<RDF-ID>C0332152</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>history</surface-form>
				<RDF-ID>C0019665</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>pheochromocytoma</surface-form>
				<RDF-ID>C0031511</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>mucosal neuromas</surface-form>
				<RDF-ID>C0878627</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>hyperparathyroidism</surface-form>
				<RDF-ID>C0020502</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>types</surface-form>
				<RDF-ID>C0332307</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>thyroid cancer</surface-form>
				<RDF-ID>C0007115</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Anaplastic carcinoma</surface-form>
				<RDF-ID>C0205696</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Follicular tumor</surface-form>
				<RDF-ID>C0474808</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>thyroid  - Papillary carcinoma</surface-form>
				<RDF-ID>C0238463</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>thyroid  -  Thyroid lymphoma</surface-form>
				<RDF-ID>C1336753</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0878627 PREDISPOSES C0006826</triple>
			<triple>C0020502 PREDISPOSES C0006826</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Your health care provider will perform a physical exam.</value>
		<pattern_crowdsource> Your [[health care provider|C0018724]] will perform a [[physical exam|C0031809]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>health care provider</surface-form>
				<RDF-ID>C0018724</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>physical exam</surface-form>
				<RDF-ID>C0031809</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0031809 ADMINISTERED_TO C0018724</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Lymph nodes in the neck may be swollen.</value>
		<pattern_crowdsource> [[Lymph nodes|C0024204]] in the [[neck|C0027530]] may be swollen.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Lymph nodes</surface-form>
				<RDF-ID>C0024204</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>neck</surface-form>
				<RDF-ID>C0027530</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>swollen</surface-form>
				<RDF-ID>C0038999</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0027530 LOCATION_OF C0024204</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Examination of the thyroid may reveal single or multiple nodules (lumps).</value>
		<pattern_crowdsource> Examination of the thyroid may reveal single or multiple [[nodules|C0028259]] ([[lumps|C0577559]]).		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>single</surface-form>
				<RDF-ID>C0205171</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>multiple</surface-form>
				<RDF-ID>C0439064</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>nodules</surface-form>
				<RDF-ID>C0028259</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>lumps</surface-form>
				<RDF-ID>C0577559</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0028259 ISA C0577559</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Because this is an uncommon tumor, surgery should be performed by a surgeon who is familiar with this type of cancer and experienced with the operation required.</value>
		<pattern_crowdsource> Because this is an uncommon tumor, [[surgery|C0543467]] should be performed by a [[surgeon|C0582175]] who is familiar with this type of cancer and experienced with the operation required.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>uncommon</surface-form>
				<RDF-ID>C0522498</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>tumor</surface-form>
				<RDF-ID>C0027651</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>surgery</surface-form>
				<RDF-ID>C0543467</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>surgeon</surface-form>
				<RDF-ID>C0582175</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>type</surface-form>
				<RDF-ID>C1547052</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>cancer</surface-form>
				<RDF-ID>C0006826</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>operation</surface-form>
				<RDF-ID>C0543467</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0543467 ADMINISTERED_TO C0582175</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Call your health care provider if you have symptoms of medullary carcinoma of the thyroid.</value>
		<pattern_crowdsource> Call your [[health care provider|C0018724]] if you have [[symptoms|C1457887]] of medullary carcinoma of the thyroid.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>health care provider</surface-form>
				<RDF-ID>C0018724</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>symptoms</surface-form>
				<RDF-ID>C1457887</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>medullary carcinoma</surface-form>
				<RDF-ID>C0206693</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C1457887 PROCESS_OF C0018724</triple>
		</triples>
	</Sentence>

</Document>


text:
CREATE TABLE country (id VARCHAR(2) NOT NULL, name VARCHAR(64) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE = InnoDB;

INSERT INTO `country` (`id`, `name`) VALUES ('AD', 'Andorra');
INSERT INTO `country` (`id`, `name`) VALUES ('AE', 'Vereenigte Araabsche Emiraten');
INSERT INTO `country` (`id`, `name`) VALUES ('AF', 'Afghanistan');
INSERT INTO `country` (`id`, `name`) VALUES ('AG', 'Antigua un Barbuda');
INSERT INTO `country` (`id`, `name`) VALUES ('AI', 'Anguilla');
INSERT INTO `country` (`id`, `name`) VALUES ('AL', 'Albanien');
INSERT INTO `country` (`id`, `name`) VALUES ('AM', 'Armenien');
INSERT INTO `country` (`id`, `name`) VALUES ('AN', 'Nedderlandsche Antillen');
INSERT INTO `country` (`id`, `name`) VALUES ('AO', 'Angola');
INSERT INTO `country` (`id`, `name`) VALUES ('AQ', 'Antarktis');
INSERT INTO `country` (`id`, `name`) VALUES ('AR', 'Argentinien');
INSERT INTO `country` (`id`, `name`) VALUES ('AS', 'Amerikaansch-Samoa');
INSERT INTO `country` (`id`, `name`) VALUES ('AT', 'Öösterriek');
INSERT INTO `country` (`id`, `name`) VALUES ('AU', 'Australien');
INSERT INTO `country` (`id`, `name`) VALUES ('AW', 'Aruba');
INSERT INTO `country` (`id`, `name`) VALUES ('AX', 'Ålandeilannen');
INSERT INTO `country` (`id`, `name`) VALUES ('AZ', 'Aserbaidschan');
INSERT INTO `country` (`id`, `name`) VALUES ('BA', 'Bosnien un Herzegowina');
INSERT INTO `country` (`id`, `name`) VALUES ('BB', 'Barbados');
INSERT INTO `country` (`id`, `name`) VALUES ('BD', 'Bangladesch');
INSERT INTO `country` (`id`, `name`) VALUES ('BE', 'Belgien');
INSERT INTO `country` (`id`, `name`) VALUES ('BF', 'Burkina Faso');
INSERT INTO `country` (`id`, `name`) VALUES ('BG', 'Bulgarien');
INSERT INTO `country` (`id`, `name`) VALUES ('BH', 'Bahrain');
INSERT INTO `country` (`id`, `name`) VALUES ('BI', 'Burundi');
INSERT INTO `country` (`id`, `name`) VALUES ('BJ', 'Benin');
INSERT INTO `country` (`id`, `name`) VALUES ('BL', 'Saint Barthélemy');
INSERT INTO `country` (`id`, `name`) VALUES ('BM', 'Bermuda');
INSERT INTO `country` (`id`, `name`) VALUES ('BN', 'Brunei Darussalam');
INSERT INTO `country` (`id`, `name`) VALUES ('BO', 'Bolivien');
INSERT INTO `country` (`id`, `name`) VALUES ('BR', 'Brasilien');
INSERT INTO `country` (`id`, `name`) VALUES ('BS', 'Bahamas');
INSERT INTO `country` (`id`, `name`) VALUES ('BT', 'Bhutan');
INSERT INTO `country` (`id`, `name`) VALUES ('BV', 'Bouvet-Eiland');
INSERT INTO `country` (`id`, `name`) VALUES ('BW', 'Botswana');
INSERT INTO `country` (`id`, `name`) VALUES ('BY', 'Wittrussland');
INSERT INTO `country` (`id`, `name`) VALUES ('BZ', 'Belize');
INSERT INTO `country` (`id`, `name`) VALUES ('CA', 'Kanada');
INSERT INTO `country` (`id`, `name`) VALUES ('CC', 'Kokos-Eilannen');
INSERT INTO `country` (`id`, `name`) VALUES ('CD', 'Demokraatsche Republik Kongo');
INSERT INTO `country` (`id`, `name`) VALUES ('CF', 'Zentralafrikaansche Republik');
INSERT INTO `country` (`id`, `name`) VALUES ('CG', 'Republik Kongo');
INSERT INTO `country` (`id`, `name`) VALUES ('CH', 'Swiez');
INSERT INTO `country` (`id`, `name`) VALUES ('CI', 'Elfenbeenküst');
INSERT INTO `country` (`id`, `name`) VALUES ('CK', 'Cook-Eilannen');
INSERT INTO `country` (`id`, `name`) VALUES ('CL', 'Chile');
INSERT INTO `country` (`id`, `name`) VALUES ('CM', 'Kamerun');
INSERT INTO `country` (`id`, `name`) VALUES ('CN', 'China');
INSERT INTO `country` (`id`, `name`) VALUES ('CO', 'Kolumbien');
INSERT INTO `country` (`id`, `name`) VALUES ('CR', 'Costa Rica');
INSERT INTO `country` (`id`, `name`) VALUES ('CU', 'Kuba');
INSERT INTO `country` (`id`, `name`) VALUES ('CV', 'Kap Verde');
INSERT INTO `country` (`id`, `name`) VALUES ('CX', 'Wiehnachtseiland');
INSERT INTO `country` (`id`, `name`) VALUES ('CY', 'Zypern');
INSERT INTO `country` (`id`, `name`) VALUES ('CZ', 'Tschechien');
INSERT INTO `country` (`id`, `name`) VALUES ('DE', 'Düütschland');
INSERT INTO `country` (`id`, `name`) VALUES ('DJ', 'Dschibuti');
INSERT INTO `country` (`id`, `name`) VALUES ('DK', 'Däänmark');
INSERT INTO `country` (`id`, `name`) VALUES ('DM', 'Dominica');
INSERT INTO `country` (`id`, `name`) VALUES ('DO', 'Dominikaansche Republik');
INSERT INTO `country` (`id`, `name`) VALUES ('DZ', 'Algerien');
INSERT INTO `country` (`id`, `name`) VALUES ('EC', 'Ecuador');
INSERT INTO `country` (`id`, `name`) VALUES ('EE', 'Eestland');
INSERT INTO `country` (`id`, `name`) VALUES ('EG', 'Ägypten');
INSERT INTO `country` (`id`, `name`) VALUES ('EH', 'Westsahara');
INSERT INTO `country` (`id`, `name`) VALUES ('ER', 'Eritrea');
INSERT INTO `country` (`id`, `name`) VALUES ('ES', 'Spanien');
INSERT INTO `country` (`id`, `name`) VALUES ('ET', 'Äthiopien');
INSERT INTO `country` (`id`, `name`) VALUES ('FI', 'Finnland');
INSERT INTO `country` (`id`, `name`) VALUES ('FJ', 'Fidschi');
INSERT INTO `country` (`id`, `name`) VALUES ('FK', 'Falkland-Eilannen');
INSERT INTO `country` (`id`, `name`) VALUES ('FM', 'Mikronesien');
INSERT INTO `country` (`id`, `name`) VALUES ('FO', 'Färöer');
INSERT INTO `country` (`id`, `name`) VALUES ('FR', 'Frankriek');
INSERT INTO `country` (`id`, `name`) VALUES ('GA', 'Gabun');
INSERT INTO `country` (`id`, `name`) VALUES ('GB', 'Vereenigt Königriek');
INSERT INTO `country` (`id`, `name`) VALUES ('GD', 'Grenada');
INSERT INTO `country` (`id`, `name`) VALUES ('GE', 'Georgien');
INSERT INTO `country` (`id`, `name`) VALUES ('GF', 'Franzöösch-Guayana');
INSERT INTO `country` (`id`, `name`) VALUES ('GG', 'Guernsey');
INSERT INTO `country` (`id`, `name`) VALUES ('GH', 'Ghana');
INSERT INTO `country` (`id`, `name`) VALUES ('GI', 'Gibraltar');
INSERT INTO `country` (`id`, `name`) VALUES ('GL', 'Gröönland');
INSERT INTO `country` (`id`, `name`) VALUES ('GM', 'Gambia');
INSERT INTO `country` (`id`, `name`) VALUES ('GN', 'Guinea');
INSERT INTO `country` (`id`, `name`) VALUES ('GP', 'Guadeloupe');
INSERT INTO `country` (`id`, `name`) VALUES ('GQ', 'Äquatorialguinea');
INSERT INTO `country` (`id`, `name`) VALUES ('GR', 'Grekenland');
INSERT INTO `country` (`id`, `name`) VALUES ('GS', 'Süüdgeorgien un de Südlichen Sandwich-Eilannen');
INSERT INTO `country` (`id`, `name`) VALUES ('GT', 'Guatemala');
INSERT INTO `country` (`id`, `name`) VALUES ('GU', 'Guam');
INSERT INTO `country` (`id`, `name`) VALUES ('GW', 'Guinea-Bissau');
INSERT INTO `country` (`id`, `name`) VALUES ('GY', 'Guyana');
INSERT INTO `country` (`id`, `name`) VALUES ('HK', 'Sünnerverwaltensrebeed Hongkong');
INSERT INTO `country` (`id`, `name`) VALUES ('HM', 'Heard- un McDonald-Eilannen');
INSERT INTO `country` (`id`, `name`) VALUES ('HN', 'Honduras');
INSERT INTO `country` (`id`, `name`) VALUES ('HR', 'Kroatien');
INSERT INTO `country` (`id`, `name`) VALUES ('HT', 'Haiti');
INSERT INTO `country` (`id`, `name`) VALUES ('HU', 'Ungarn');
INSERT INTO `country` (`id`, `name`) VALUES ('ID', 'Indonesien');
INSERT INTO `country` (`id`, `name`) VALUES ('IE', 'Irland');
INSERT INTO `country` (`id`, `name`) VALUES ('IL', 'Israel');
INSERT INTO `country` (`id`, `name`) VALUES ('IM', 'Insel Man');
INSERT INTO `country` (`id`, `name`) VALUES ('IN', 'Indien');
INSERT INTO `country` (`id`, `name`) VALUES ('IO', 'Britisch Rebeed in'n Indischen Ozean');
INSERT INTO `country` (`id`, `name`) VALUES ('IQ', 'Irak');
INSERT INTO `country` (`id`, `name`) VALUES ('IR', 'Iran');
INSERT INTO `country` (`id`, `name`) VALUES ('IS', 'Iesland');
INSERT INTO `country` (`id`, `name`) VALUES ('IT', 'Italien');
INSERT INTO `country` (`id`, `name`) VALUES ('JE', 'Jersey');
INSERT INTO `country` (`id`, `name`) VALUES ('JM', 'Jamaika');
INSERT INTO `country` (`id`, `name`) VALUES ('JO', 'Jordanien');
INSERT INTO `country` (`id`, `name`) VALUES ('JP', 'Japan');
INSERT INTO `country` (`id`, `name`) VALUES ('KE', 'Kenia');
INSERT INTO `country` (`id`, `name`) VALUES ('KG', 'Kirgisistan');
INSERT INTO `country` (`id`, `name`) VALUES ('KH', 'Kambodscha');
INSERT INTO `country` (`id`, `name`) VALUES ('KI', 'Kiribati');
INSERT INTO `country` (`id`, `name`) VALUES ('KM', 'Komoren');
INSERT INTO `country` (`id`, `name`) VALUES ('KN', 'St. Kitts un Nevis');
INSERT INTO `country` (`id`, `name`) VALUES ('KP', 'Noordkorea');
INSERT INTO `country` (`id`, `name`) VALUES ('KR', 'Süüdkorea');
INSERT INTO `country` (`id`, `name`) VALUES ('KW', 'Kuwait');
INSERT INTO `country` (`id`, `name`) VALUES ('KY', 'Kaiman-Eilannen');
INSERT INTO `country` (`id`, `name`) VALUES ('KZ', 'Kasachstan');
INSERT INTO `country` (`id`, `name`) VALUES ('LA', 'Laos');
INSERT INTO `country` (`id`, `name`) VALUES ('LB', 'Libanon');
INSERT INTO `country` (`id`, `name`) VALUES ('LC', 'St. Lucia');
INSERT INTO `country` (`id`, `name`) VALUES ('LI', 'Liechtensteen');
INSERT INTO `country` (`id`, `name`) VALUES ('LK', 'Sri Lanka');
INSERT INTO `country` (`id`, `name`) VALUES ('LR', 'Liberia');
INSERT INTO `country` (`id`, `name`) VALUES ('LS', 'Lesotho');
INSERT INTO `country` (`id`, `name`) VALUES ('LT', 'Litauen');
INSERT INTO `country` (`id`, `name`) VALUES ('LU', 'Luxemborg');
INSERT INTO `country` (`id`, `name`) VALUES ('LV', 'Lettland');
INSERT INTO `country` (`id`, `name`) VALUES ('LY', 'Libyen');
INSERT INTO `country` (`id`, `name`) VALUES ('MA', 'Marokko');
INSERT INTO `country` (`id`, `name`) VALUES ('MC', 'Monaco');
INSERT INTO `country` (`id`, `name`) VALUES ('MD', 'Moldawien');
INSERT INTO `country` (`id`, `name`) VALUES ('ME', 'Montenegro');
INSERT INTO `country` (`id`, `name`) VALUES ('MF', 'Saint Martin');
INSERT INTO `country` (`id`, `name`) VALUES ('MG', 'Madagaskar');
INSERT INTO `country` (`id`, `name`) VALUES ('MH', 'Marshall-Eilannen');
INSERT INTO `country` (`id`, `name`) VALUES ('MK', 'Makedonien');
INSERT INTO `country` (`id`, `name`) VALUES ('ML', 'Mali');
INSERT INTO `country` (`id`, `name`) VALUES ('MM', 'Birma');
INSERT INTO `country` (`id`, `name`) VALUES ('MN', 'Mongolei');
INSERT INTO `country` (`id`, `name`) VALUES ('MO', 'Sünnerverwaltensrebeed Macao');
INSERT INTO `country` (`id`, `name`) VALUES ('MP', 'Nöördliche Marianen');
INSERT INTO `country` (`id`, `name`) VALUES ('MQ', 'Martinique');
INSERT INTO `country` (`id`, `name`) VALUES ('MR', 'Mauretanien');
INSERT INTO `country` (`id`, `name`) VALUES ('MS', 'Montserrat');
INSERT INTO `country` (`id`, `name`) VALUES ('MT', 'Malta');
INSERT INTO `country` (`id`, `name`) VALUES ('MU', 'Mauritius');
INSERT INTO `country` (`id`, `name`) VALUES ('MV', 'Malediven');
INSERT INTO `country` (`id`, `name`) VALUES ('MW', 'Malawi');
INSERT INTO `country` (`id`, `name`) VALUES ('MX', 'Mexiko');
INSERT INTO `country` (`id`, `name`) VALUES ('MY', 'Malaysia');
INSERT INTO `country` (`id`, `name`) VALUES ('MZ', 'Mosambik');
INSERT INTO `country` (`id`, `name`) VALUES ('NA', 'Namibia');
INSERT INTO `country` (`id`, `name`) VALUES ('NC', 'Neekaledonien');
INSERT INTO `country` (`id`, `name`) VALUES ('NE', 'Niger');
INSERT INTO `country` (`id`, `name`) VALUES ('NF', 'Norfolk');
INSERT INTO `country` (`id`, `name`) VALUES ('NG', 'Nigeria');
INSERT INTO `country` (`id`, `name`) VALUES ('NI', 'Nikaragua');
INSERT INTO `country` (`id`, `name`) VALUES ('NL', 'Nedderlannen');
INSERT INTO `country` (`id`, `name`) VALUES ('NO', 'Norwegen');
INSERT INTO `country` (`id`, `name`) VALUES ('NP', 'Nepal');
INSERT INTO `country` (`id`, `name`) VALUES ('NR', 'Nauru');
INSERT INTO `country` (`id`, `name`) VALUES ('NU', 'Niue');
INSERT INTO `country` (`id`, `name`) VALUES ('NZ', 'Neeseeland');
INSERT INTO `country` (`id`, `name`) VALUES ('OM', 'Oman');
INSERT INTO `country` (`id`, `name`) VALUES ('PA', 'Panama');
INSERT INTO `country` (`id`, `name`) VALUES ('PE', 'Peru');
INSERT INTO `country` (`id`, `name`) VALUES ('PF', 'Franzöösch-Polynesien');
INSERT INTO `country` (`id`, `name`) VALUES ('PG', 'Papua-Neeguinea');
INSERT INTO `country` (`id`, `name`) VALUES ('PH', 'Philippinen');
INSERT INTO `country` (`id`, `name`) VALUES ('PK', 'Pakistan');
INSERT INTO `country` (`id`, `name`) VALUES ('PL', 'Polen');
INSERT INTO `country` (`id`, `name`) VALUES ('PM', 'St. Pierre un Miquelon');
INSERT INTO `country` (`id`, `name`) VALUES ('PN', 'Pitcairn');
INSERT INTO `country` (`id`, `name`) VALUES ('PR', 'Puerto Rico');
INSERT INTO `country` (`id`, `name`) VALUES ('PS', 'Palästinensische Rebeden');
INSERT INTO `country` (`id`, `name`) VALUES ('PT', 'Portugal');
INSERT INTO `country` (`id`, `name`) VALUES ('PW', 'Palau');
INSERT INTO `country` (`id`, `name`) VALUES ('PY', 'Paraguay');
INSERT INTO `country` (`id`, `name`) VALUES ('QA', 'Katar');
INSERT INTO `country` (`id`, `name`) VALUES ('RE', 'Reunion');
INSERT INTO `country` (`id`, `name`) VALUES ('RO', 'Rumänien');
INSERT INTO `country` (`id`, `name`) VALUES ('RS', 'Serbien');
INSERT INTO `country` (`id`, `name`) VALUES ('RU', 'Russland');
INSERT INTO `country` (`id`, `name`) VALUES ('RW', 'Ruanda');
INSERT INTO `country` (`id`, `name`) VALUES ('SA', 'Saudi-Arabien');
INSERT INTO `country` (`id`, `name`) VALUES ('SB', 'Salomonen');
INSERT INTO `country` (`id`, `name`) VALUES ('SC', 'Seychellen');
INSERT INTO `country` (`id`, `name`) VALUES ('SD', 'Sudan');
INSERT INTO `country` (`id`, `name`) VALUES ('SE', 'Sweden');
INSERT INTO `country` (`id`, `name`) VALUES ('SG', 'Singapur');
INSERT INTO `country` (`id`, `name`) VALUES ('SH', 'St. Helena');
INSERT INTO `country` (`id`, `name`) VALUES ('SI', 'Slowenien');
INSERT INTO `country` (`id`, `name`) VALUES ('SJ', 'Svalbard un Jan Mayen');
INSERT INTO `country` (`id`, `name`) VALUES ('SK', 'Slowakei');
INSERT INTO `country` (`id`, `name`) VALUES ('SL', 'Sierra Leone');
INSERT INTO `country` (`id`, `name`) VALUES ('SM', 'San Marino');
INSERT INTO `country` (`id`, `name`) VALUES ('SN', 'Senegal');
INSERT INTO `country` (`id`, `name`) VALUES ('SO', 'Somalia');
INSERT INTO `country` (`id`, `name`) VALUES ('SR', 'Surinam');
INSERT INTO `country` (`id`, `name`) VALUES ('ST', 'São Tomé un Príncipe');
INSERT INTO `country` (`id`, `name`) VALUES ('SV', 'El Salvador');
INSERT INTO `country` (`id`, `name`) VALUES ('SY', 'Syrien');
INSERT INTO `country` (`id`, `name`) VALUES ('SZ', 'Swasiland');
INSERT INTO `country` (`id`, `name`) VALUES ('TC', 'Turks- un Caicosinseln');
INSERT INTO `country` (`id`, `name`) VALUES ('TD', 'Tschad');
INSERT INTO `country` (`id`, `name`) VALUES ('TF', 'Franzöösche Süüd- un Antarktisrebeden');
INSERT INTO `country` (`id`, `name`) VALUES ('TG', 'Togo');
INSERT INTO `country` (`id`, `name`) VALUES ('TH', 'Thailand');
INSERT INTO `country` (`id`, `name`) VALUES ('TJ', 'Tadschikistan');
INSERT INTO `country` (`id`, `name`) VALUES ('TK', 'Tokelau');
INSERT INTO `country` (`id`, `name`) VALUES ('TL', 'Oosttimor');
INSERT INTO `country` (`id`, `name`) VALUES ('TM', 'Turkmenistan');
INSERT INTO `country` (`id`, `name`) VALUES ('TN', 'Tunesien');
INSERT INTO `country` (`id`, `name`) VALUES ('TO', 'Tonga');
INSERT INTO `country` (`id`, `name`) VALUES ('TR', 'Törkie');
INSERT INTO `country` (`id`, `name`) VALUES ('TT', 'Trinidad un Tobago');
INSERT INTO `country` (`id`, `name`) VALUES ('TV', 'Tuvalu');
INSERT INTO `country` (`id`, `name`) VALUES ('TW', 'Taiwan');
INSERT INTO `country` (`id`, `name`) VALUES ('TZ', 'Tansania');
INSERT INTO `country` (`id`, `name`) VALUES ('UA', 'Ukraine');
INSERT INTO `country` (`id`, `name`) VALUES ('UG', 'Uganda');
INSERT INTO `country` (`id`, `name`) VALUES ('UM', 'Amerikaansch-Ozeanien');
INSERT INTO `country` (`id`, `name`) VALUES ('US', 'USA');
INSERT INTO `country` (`id`, `name`) VALUES ('UY', 'Uruguay');
INSERT INTO `country` (`id`, `name`) VALUES ('UZ', 'Usbekistan');
INSERT INTO `country` (`id`, `name`) VALUES ('VA', 'Vatikan');
INSERT INTO `country` (`id`, `name`) VALUES ('VC', 'St. Vincent un de Grenadinen');
INSERT INTO `country` (`id`, `name`) VALUES ('VE', 'Venezuela');
INSERT INTO `country` (`id`, `name`) VALUES ('VG', 'Brietsche Jumfern-Eilannen');
INSERT INTO `country` (`id`, `name`) VALUES ('VI', 'Amerikaansche Jumfern-Eilannen');
INSERT INTO `country` (`id`, `name`) VALUES ('VN', 'Vietnam');
INSERT INTO `country` (`id`, `name`) VALUES ('VU', 'Vanuatu');
INSERT INTO `country` (`id`, `name`) VALUES ('WF', 'Wallis un Futuna');
INSERT INTO `country` (`id`, `name`) VALUES ('WS', 'Samoa');
INSERT INTO `country` (`id`, `name`) VALUES ('YE', 'Jemen');
INSERT INTO `country` (`id`, `name`) VALUES ('YT', 'Mayotte');
INSERT INTO `country` (`id`, `name`) VALUES ('ZA', 'Süüdafrika');
INSERT INTO `country` (`id`, `name`) VALUES ('ZM', 'Sambia');
INSERT INTO `country` (`id`, `name`) VALUES ('ZW', 'Simbabwe');
INSERT INTO `country` (`id`, `name`) VALUES ('ZZ', 'Unbekannte oder ungüllige Region');

redpajama_set_name: RedPajamaGithub


text: Modeling channel coding and source coding.


text:
* {
    padding:0;
    margin:0;
}

.blocks_js_editor {
    width:100%;
    height:100%;
    position:relative;
}

.blocks_js_editor .blocks {
    overflow:hidden;
}

.blocks_js_editor svg {
    position:absolute;
    z-index:1;
}

.blocks_js_editor .blocks {
    overflow:hidden;
    position:absolute;
    z-index:3;
    width:100%;
    height:100%;
}

/**
 * Menu bar
 */

.blocks_js_editor .menubar {
    width:100%;
    height:30px;
    z-index:1;
}

.blocks_js_editor .contextmenu,
.blocks_js_editor .childs {
    width:120px;
    padding:0px;
    position:absolute;
    display:none;
    float:left;
    z-index:99;
}

.blocks_js_editor .contextmenu,
.blocks_js_editor .childs
{
    box-shadow:0px 0px 5px #666;
    border:1px solid #aaa;
    background-color:#fff;
}

.blocks_js_editor .menubar .add span {
    color:green;
}

.blocks_js_editor .contextmenu .types {
}

.blocks_js_editor .contextmenu .type,
.blocks_js_editor .contextmenu .menuentry,
.blocks_js_editor .contextmenu .family {
    font-size:14px;
    padding:1px;
    cursor:pointer;
    background-color:#fff;
    height:18px;
    background-image:url('gfx/menufade.png');
    color:#666;
    border-left:1px solid #aaa;
    border-right:1px solid #aaa;
    border-top:none;
    border-bottom:none;
    margin-left:-1px;
    margin-right:-1px;
    background-repeat:repeat-x;
    padding:3px;
}

.blocks_js_editor .contextmenu .menu_icon
{
    width:16px;
    height:16px;
    float:left;
    background-repeat:no-repeat;
    margin-right:3px;
}

.blocks_js_editor .contextmenu .menu_icon_compact
{
    background-image:url('gfx/compact.png');
}

.blocks_js_editor .contextmenu .menu_icon_scale
{
    background-image:url('gfx/scale.png');
}

.blocks_js_editor .contextmenu .family:hover,
.blocks_js_editor .contextmenu .menuentry:hover,
.blocks_js_editor .contextmenu .type:hover {
    background-image:url('gfx/menufadeOver.png');
    color:black;
}

.blocks_js_editor .contextmenu .family .childs {
    margin-left:121px;
    margin-top:-20px;
}

.blocks_js_editor .contextmenu .family .familyName span {
    float:right;
}

.blocks_js_editor .contextmenu .family h3 {
    font-size:100%;
    font-weight:bold;
    cursor:pointer;
}

/**
 * Blocks
 */

.blocks_js_editor .block {
    position:absolute;
    background-image:url('gfx/blockFade.png');
    background-repeat:repeat-x;
    border:2px solid #fafafa;
    box-shadow:5px 5px 10px #aaa;
    padding:1px;
    margin-left:0px;
    margin-top:0px;
    background-color:#fafafa;
    opacity:0.8;
    font-size:14px;
    -moz-user-select:none;
    -khtml-user-select:none;
    -webkit-user-select:none;
    -o-user-select:none;
}

.blocks_js_editor .block .description {
    display:none;
    width:200px;
    padding:3px;
    border:1px solid #083776;
    border-radius:5px;
    color:#001531;
    background-color:#91bcf6;
    margin-top:15px;
    position:absolute;
    font-weight:normal;
}

.blocks_js_editor .blockTitle {
    font-weight:bold;
    background-color:#ddd;
    background-image:url('gfx/titleFade.png');
    background-repeat:repeat-x;
    padding:1px;
    margin:-1px;
    margin-bottom:2px;
    cursor:move;
    font-size:80%;
}

.blocks_js_editor .blockTitle .blockId {
    opacity:0.4;
}

.blocks_js_editor .block .blockicon
{
    margin:0;
    padding:0;
    width:14px;
    height:14px;
    float:right;
    cursor:pointer;
    opacity:0.5;
    margin-right:2px;
}

.blocks_js_editor .block .blockicon:hover {
    opacity:1.0;
}

.blocks_js_editor .block .settings {
    background-image:url('gfx/settings.png');
}

.blocks_js_editor .block .delete {
    background-image:url('gfx/delete.png');
}

.blocks_js_editor .block .info {
    background-image:url('gfx/info.png');
}

.blocks_js_editor .block_selected {
    border:2px solid #0a0;
}

.blocks_js_editor .block_selected .blockTitle {
    background-color:#0c0;
}

.blocks_js_editor .inputs,
.blocks_js_editor .outputs {
    width:80px;
}

.blocks_js_editor .outputs {
    float:right;
}

.blocks_js_editor .inputs {
    float:left;
}

.blocks_js_editor .inputs.loopable {
    float:right;
}

.blocks_js_editor .outputs.loopable {
    float:left;
}

.blocks_js_editor .connector {
    font-size:80%;
    padding-top:2px;
    background-repeat:no-repeat;
    cursor:pointer;
    clear:both;
    width:130px;
}

.blocks_js_editor .connector.disabled {
    opacity:0.4;
}

.blocks_js_editor .output {
    text-align:right;
}

.blocks_js_editor .circle {
    width:12px;
    height:12px;
    background-image:url('gfx/circle.png');
    background-size:12px 12px;
}

.blocks_js_editor .circle.io_active {
    background-image:url('gfx/circle_full.png');
}

.blocks_js_editor .circle.io_selected {
    background-image:url('gfx/circle_selected.png') !important;
}

.blocks_js_editor input,
.blocks_js_editor textarea
{
    font-family:Courier;
}

.blocks_js_editor .input,
.blocks_js_editor .loopable .output
{
    float:left;
}

.blocks_js_editor .input .circle,
.blocks_js_editor .loopable .output .circle,
.blocks_js_editor .parameter .circle {
    float:left;
    margin:1px;
}

.blocks_js_editor .input .circle.io_active,
.blocks_js_editor .loopable .output .circle.io_active
{
    float:left;
    margin:1px;
}

.blocks_js_editor .output,
.blocks_js_editor .loopable .input {
    float:right;
}

.blocks_js_editor .output .circle,
.blocks_js_editor .loopable .input .circle
{
    float:right;
    margin:1px;
}

.blocks_js_editor .block .parameters {
    display:none;
    position:absolute;
    border:2px solid #aaa;
    padding:3px;
    z-index:50;
    width:250px;
    margin-left:-5px;
    margin-top:-5px;
    background-color:white;
}

/**
 * Messages
 */
.blocks_js_editor .messages {
    display:none;
    width:350px;
    position:absolute;
    z-index:100;
}

.blocks_js_editor .message {
    padding:5px;
    font-size:14px;
    cursor:pointer;
    border:3px solid;
    border-radius:5px;
}

.blocks_js_editor .messages ul {
    list-style:circle;
    margin-left:20px;
}

.blocks_js_editor .message.error {
    color:red;
    border-color:red;
    background-color:#ffe3e3;
}

.blocks_js_editor .message.valid {
    color:green;
    border-color:green;
    background-color:#eeffee;
}

.blocks_js_modal button {
    margin:5px;
    padding:2px;
    cursor:pointer;
    border:0;
    color:#222;
    font-size:18px;
}

.blocks_js_modal button.close {
    color:white;
    background-color:#ff4646;
}

.blocks_js_modal button.save {
    color:white;
    background-color:#21c40c;
    float:right;
}

.blocks_js_modal input,
.blocks_js_modal select,
.blocks_js_modal textarea {
    width:250px;
    padding:2px;
    border:1px solid #aaa;
    border-radius:2px;
    background-color:#fafafa;
    margin:2px;
}

.blocks_js_modal textarea {
    width:400px;
    height:110px;
}

.blocks_js_modal .fieldsArray .pattern {
    display:none;
}


text:
#define LOG_TAG "VelocityTracker-JNI"

#include "JNIHelp.h"

#include <android_runtime/AndroidRuntime.h>
#include <utils/Log.h>
#include <input/Input.h>
#include <input/VelocityTracker.h>
#include "android_view_MotionEvent.h"

#include <ScopedUtfChars.h>

namespace android {

// Special constant to request the velocity of the active pointer.
static const int ACTIVE_POINTER_ID = -1;

static struct {
    jfieldID xCoeff;
    jfieldID yCoeff;
    jfieldID degree;
    jfieldID confidence;
} gEstimatorClassInfo;

// --- VelocityTrackerState ---

class VelocityTrackerState {
public:
    VelocityTrackerState(const char* strategy);

    void clear();
    void addMovement(const MotionEvent* event);
    void computeCurrentVelocity(int32_t units, float maxVelocity);
    void getVelocity(int32_t id, float* outVx, float* outVy);
    bool getEstimator(int32_t id, VelocityTracker::Estimator* outEstimator);

private:
    struct Velocity {
        float vx, vy;
    };

    VelocityTracker mVelocityTracker;
    int32_t mActivePointerId;
    BitSet32 mCalculatedIdBits;
    Velocity mCalculatedVelocity[MAX_POINTERS];
};

VelocityTrackerState::VelocityTrackerState(const char* strategy) :
        mVelocityTracker(strategy), mActivePointerId(-1) {
}

void VelocityTrackerState::clear() {
    mVelocityTracker.clear();
    mActivePointerId = -1;
    mCalculatedIdBits.clear();
}

void VelocityTrackerState::addMovement(const MotionEvent* event) {
    mVelocityTracker.addMovement(event);
}

void VelocityTrackerState::computeCurrentVelocity(int32_t units, float maxVelocity) {
    BitSet32 idBits(mVelocityTracker.getCurrentPointerIdBits());
    mCalculatedIdBits = idBits;

    for (uint32_t index = 0; !idBits.isEmpty(); index++) {
        uint32_t id = idBits.clearFirstMarkedBit();

        float vx, vy;
        mVelocityTracker.getVelocity(id, &vx, &vy);

        vx = vx * units / 1000;
        vy = vy * units / 1000;

        if (vx > maxVelocity) {
            vx = maxVelocity;
        } else if (vx < -maxVelocity) {
            vx = -maxVelocity;
        }
        if (vy > maxVelocity) {
            vy = maxVelocity;
        } else if (vy < -maxVelocity) {
            vy = -maxVelocity;
        }

        Velocity& velocity = mCalculatedVelocity[index];
        velocity.vx = vx;
        velocity.vy = vy;
    }
}

void VelocityTrackerState::getVelocity(int32_t id, float* outVx, float* outVy) {
    if (id == ACTIVE_POINTER_ID) {
        id = mVelocityTracker.getActivePointerId();
    }

    float vx, vy;
    if (id >= 0 && id <= MAX_POINTER_ID && mCalculatedIdBits.hasBit(id)) {
        uint32_t index = mCalculatedIdBits.getIndexOfBit(id);
        const Velocity& velocity = mCalculatedVelocity[index];
        vx = velocity.vx;
        vy = velocity.vy;
    } else {
        vx = 0;
        vy = 0;
    }

    if (outVx) {
        *outVx = vx;
    }
    if (outVy) {
        *outVy = vy;
    }
}

bool VelocityTrackerState::getEstimator(int32_t id, VelocityTracker::Estimator* outEstimator) {
    return mVelocityTracker.getEstimator(id, outEstimator);
}

// --- JNI Methods ---

static jlong android_view_VelocityTracker_nativeInitialize(JNIEnv* env, jclass clazz,
        jstring strategyStr) {
    if (strategyStr) {
        ScopedUtfChars strategy(env, strategyStr);
        return reinterpret_cast<jlong>(new VelocityTrackerState(strategy.c_str()));
    }
    return reinterpret_cast<jlong>(new VelocityTrackerState(NULL));
}

static void android_view_VelocityTracker_nativeDispose(JNIEnv* env, jclass clazz, jlong ptr) {
    VelocityTrackerState* state = reinterpret_cast<VelocityTrackerState*>(ptr);
    delete state;
}

static void android_view_VelocityTracker_nativeClear(JNIEnv* env, jclass clazz, jlong ptr) {
    VelocityTrackerState* state = reinterpret_cast<VelocityTrackerState*>(ptr);
    state->clear();
}

static void android_view_VelocityTracker_nativeAddMovement(JNIEnv* env, jclass clazz, jlong ptr,
        jobject eventObj) {
    const MotionEvent* event = android_view_MotionEvent_getNativePtr(env, eventObj);
    if (!event) {
        ALOGW("nativeAddMovement failed because MotionEvent was finalized.");
        return;
    }

    VelocityTrackerState* state = reinterpret_cast<VelocityTrackerState*>(ptr);
    state->addMovement(event);
}

static void android_view_VelocityTracker_nativeComputeCurrentVelocity(JNIEnv* env, jclass clazz,
        jlong ptr, jint units, jfloat maxVelocity) {
    VelocityTrackerState* state = reinterpret_cast<VelocityTrackerState*>(ptr);
    state->computeCurrentVelocity(units, maxVelocity);
}

static jfloat android_view_VelocityTracker_nativeGetXVelocity(JNIEnv* env, jclass clazz,
        jlong ptr, jint id) {
    VelocityTrackerState* state = reinterpret_cast<VelocityTrackerState*>(ptr);
    float vx;
    state->getVelocity(id, &vx, NULL);
    return vx;
}

static jfloat android_view_VelocityTracker_nativeGetYVelocity(JNIEnv* env, jclass clazz,
        jlong ptr, jint id) {
    VelocityTrackerState* state = reinterpret_cast<VelocityTrackerState*>(ptr);
    float vy;
    state->getVelocity(id, NULL, &vy);
    return vy;
}

static jboolean android_view_VelocityTracker_nativeGetEstimator(JNIEnv* env, jclass clazz,
        jlong ptr, jint id, jobject outEstimatorObj) {
    VelocityTrackerState* state = reinterpret_cast<VelocityTrackerState*>(ptr);
    VelocityTracker::Estimator estimator;
    bool result = state->getEstimator(id, &estimator);

    jfloatArray xCoeffObj = jfloatArray(env->GetObjectField(outEstimatorObj,
            gEstimatorClassInfo.xCoeff));
    jfloatArray yCoeffObj = jfloatArray(env->GetObjectField(outEstimatorObj,
            gEstimatorClassInfo.yCoeff));

    env->SetFloatArrayRegion(xCoeffObj, 0, VelocityTracker::Estimator::MAX_DEGREE + 1,
            estimator.xCoeff);
    env->SetFloatArrayRegion(yCoeffObj, 0, VelocityTracker::Estimator::MAX_DEGREE + 1,
            estimator.yCoeff);
    env->SetIntField(outEstimatorObj, gEstimatorClassInfo.degree, estimator.degree);
    env->SetFloatField(outEstimatorObj, gEstimatorClassInfo.confidence, estimator.confidence);
    return result;
}

// --- JNI Registration ---

static JNINativeMethod gVelocityTrackerMethods[] = {
    /* name, signature, funcPtr */
    { "nativeInitialize",
            "(Ljava/lang/String;)J",
            (void*)android_view_VelocityTracker_nativeInitialize },
    { "nativeDispose",
            "(J)V",
            (void*)android_view_VelocityTracker_nativeDispose },
    { "nativeClear",
            "(J)V",
            (void*)android_view_VelocityTracker_nativeClear },
    { "nativeAddMovement",
            "(JLandroid/view/MotionEvent;)V",
            (void*)android_view_VelocityTracker_nativeAddMovement },
    { "nativeComputeCurrentVelocity",
            "(JIF)V",
            (void*)android_view_VelocityTracker_nativeComputeCurrentVelocity },
    { "nativeGetXVelocity",
            "(JI)F",
            (void*)android_view_VelocityTracker_nativeGetXVelocity },
    { "nativeGetYVelocity",
            "(JI)F",
            (void*)android_view_VelocityTracker_nativeGetYVelocity },
    { "nativeGetEstimator",
            "(JILandroid/view/VelocityTracker$Estimator;)Z",
            (void*)android_view_VelocityTracker_nativeGetEstimator },
};

#define FIND_CLASS(var, className) \
        var = env->FindClass(className); \
        LOG_FATAL_IF(! var, "Unable to find class " className);

#define GET_FIELD_ID(var, clazz, fieldName, fieldDescriptor) \
        var = env->GetFieldID(clazz, fieldName, fieldDescriptor); \
        LOG_FATAL_IF(! var, "Unable to find field " fieldName);

int register_android_view_VelocityTracker(JNIEnv* env) {
    int res = jniRegisterNativeMethods(env, "android/view/VelocityTracker",
            gVelocityTrackerMethods, NELEM(gVelocityTrackerMethods));
    LOG_FATAL_IF(res < 0, "Unable to register native methods.");

    jclass clazz;
    FIND_CLASS(clazz, "android/view/VelocityTracker$Estimator");

    GET_FIELD_ID(gEstimatorClassInfo.xCoeff, clazz,
            "xCoeff", "[F");
    GET_FIELD_ID(gEstimatorClassInfo.yCoeff, clazz,
            "yCoeff", "[F");
    GET_FIELD_ID(gEstimatorClassInfo.degree, clazz,
            "degree", "I");
    GET_FIELD_ID(gEstimatorClassInfo.confidence, clazz,
            "confidence", "F");
    return 0;
}

} // namespace android


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

    <item android:state_checked="true" android:drawable="@drawable/rb_zone_press"></item>
    <item android:state_checked="false" android:drawable="@drawable/rb_zone_normal"></item>

</selector>


text:
using System;
using System.Collections.Generic;
using Hl7.Fhir.Introspection;
using Hl7.Fhir.Validation;
using System.Linq;
using System.Runtime.Serialization;

//
// Generated on Wed, Dec 24, 2014 16:02+0100 for FHIR v0.4.0
//
namespace Hl7.Fhir.Model
{
    public abstract partial class Element : IExtendable
    {
    }

}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>MovieAPP-ImranMH</title>
	<link rel="stylesheet" href="css/bootstrap.min.css">
	<link rel="stylesheet" href="css/main.css">

IMDB Movie search

							<input type="text" id="movie-title" class="form-control" placeholder="Inception">
							<button id="search-movie" class="btn btn-primary btn-block">Search Movie</button>

Movie :

Genres

Rated

Directors:

Writters:

Plot:Chronicles the experiences of a formerly successful banker as a prisoner in the gloomy jailhouse of Shawshank after being found guilty of a crime he claims he did not commit. The film portrays the man's unique way of dealing with his new, torturous life; along the way he befriends a number of fellow prisoners, most notably a wise long-term inmate named Red

Rankings:

Release Year

Rating

Runtimes:

Countries:

Vote:

Filming Locations:


text:
Multiple Choice Question {{vm.multipleChoiceQuestion.id}}

    <jhi-alert-error></jhi-alert-error>

    <button type="submit"
            ui-sref="{{ vm.previousState }}"
            class="btn btn-info">
          Back
    </button>

    <button type="button" ui-sref="multiple-choice-question-detail.edit({id:vm.multipleChoiceQuestion.id})" class="btn btn-primary">

         Edit
    </button>


text:
package org.apache.jena.reasoner.rulesys;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

import org.apache.jena.datatypes.RDFDatatype ;
import org.apache.jena.datatypes.TypeMapper ;
import org.apache.jena.datatypes.xsd.XSDDatatype ;
import org.apache.jena.graph.Node ;
import org.apache.jena.graph.NodeFactory ;
import org.apache.jena.rdf.model.AnonId ;
import org.apache.jena.reasoner.ReasonerException ;
import org.apache.jena.reasoner.TriplePattern ;
import org.apache.jena.shared.JenaException ;
import org.apache.jena.shared.PrefixMapping ;
import org.apache.jena.shared.RulesetNotFoundException ;
import org.apache.jena.shared.WrappedIOException ;
import org.apache.jena.util.FileManager ;
import org.apache.jena.util.FileUtils ;
import org.apache.jena.util.PrintUtil ;
import org.apache.jena.util.Tokenizer ;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**Representation of a generic inference rule.
 *

 * This represents the rule specification but most engines will
 * compile this specification into an abstract machine or processing
 * graph.

 *

 * The rule specification comprises a list of antecendents (body) and a list
 * of consequents (head). If there is more than one consequent then a backchainer
 * should regard this as a shorthand for several rules, all with the
 * same body but with a singleton head.

 *

 * Each element in the head or body can be a TriplePattern, a Functor or a Rule.
 * A TriplePattern is just a triple of Nodes but the Nodes can represent
 * variables, wildcards and embedded functors - as well as constant uri or
 * literal graph nodes. A functor comprises a functor name and a list of
 * arguments. The arguments are Nodes of any type except functor nodes
 * (there is no functor nesting). The functor name can be mapped into a registered
 * java class that implements its semantics. Functors play three roles -
 * in heads they represent actions (procedural attachement); in bodies they
 * represent builtin predicates; in TriplePatterns they represent embedded
 * structured literals that are used to cache matched subgraphs such as
 * restriction specifications.

 *

 * The equality contract for rules is that two rules are equal if each of terms
 * (ClauseEntry objects) are equals and they have the same name, if any.
 *

 * We include a trivial, recursive descent parser but this is just there
 * to allow rules to be embedded in code. External rule syntax based on N3
 * and RDF could be developed. The embedded syntax supports rules such as:
 * <blockindent>
 * [ (?C rdf:type *), guard(?C, ?P)  -> (?c rb:restriction some(?P, ?D)) ].

 * [ (?s owl:foo ?p) -> [ (?s owl:bar ?a) -> (?s ?p ?a) ] ].

 * [name: (?s owl:foo ?p) -> (?s ?p ?a)].

 * </blockindent>
 * only built in namespaces are recognized as such, * is a wildcard node, ?c is a variable,
 * name(node ... node) is a functor, (node node node) is a triple pattern, [..] is an
 * embedded rule, commas are ignore and can be freely used as separators. Functor names
 * may not end in ':'.
 *

 */
public class Rule implements ClauseEntry {

//=======================================================================
// variables

    /** Rule body */
    protected ClauseEntry[] body;

    /** Rule head or set of heads */
    protected ClauseEntry[] head;

    /** Optional name for the rule */
    protected String name;

    /** The number of distinct variables used in the rule */
    protected int numVars = -1;

    /** Flags whether the rule was written as a forward or backward rule */
    protected boolean isBackward = false;

    /** Flags whether the rule is monotonic */
    protected boolean isMonotonic = true;

    static Logger logger = LoggerFactory.getLogger(Rule.class);

    /**
     * Constructor
     * @param body a list of TriplePatterns or Functors.
     * @param head a list of TriplePatterns, Functors or rules
     */
    public Rule(List<ClauseEntry> head, List<ClauseEntry> body) {
        this(null, head, body);
    }

    /**
     * Constructor
     * @param name a label for rule
     * @param body a list of TriplePatterns or Functors.
     * @param head a list of TriplePatterns, Functors or rules
     */
    public Rule(String name, List<ClauseEntry> head, List<ClauseEntry> body) {
        this(name,
                head.toArray(new ClauseEntry[head.size()]),
                body.toArray(new ClauseEntry[body.size()]) );
    }

    /**
     * Constructor
     * @param name a label for rule
     * @param body an array of TriplePatterns or Functors.
     * @param head an array of TriplePatterns, Functors or rules
     */
    public Rule(String name, ClauseEntry[] head, ClauseEntry[] body) {
        this.name = name;
        this.head = head;
        this.body = body;
        this.isMonotonic = allMonotonic(head);
    }

    // Compute the monotonicity flag
    // Future support for negation would affect this
    private boolean allMonotonic(ClauseEntry[] elts) {
        for ( ClauseEntry elt : elts )
        {
            if ( elt instanceof Functor )
            {
                Builtin b = ( (Functor) elt ).getImplementor();
                if ( b != null )
                {
                    if ( !b.isMonotonic() )
                    {
                        return false;
                    }
                }
                else
                {
                    throw new ReasonerException(
                        "Undefined Functor " + ( (Functor) elt ).getName() + " in " + toShortString() );
                }
            }
        }
        return true;
    }

//=======================================================================
// accessors

    /**
     * Return the number of body elements
     */
    public int bodyLength() {
        return body.length;
    }

    /**
     * Return the n'th body element
     */
    public ClauseEntry getBodyElement(int n) {
        return body[n];
    }

    /**
     * return the entire rule body as an array of objects
     */
    public ClauseEntry[] getBody() {
        return body;
    }

    /**
     * Return the number of head elements
     */
    public int headLength() {
        return head.length;
    }

    /**
     * Return the n'th head element
     */
    public ClauseEntry getHeadElement(int n) {
        return head[n];
    }

    /**
     * return the entire rule head as an array of objects
     */
    public ClauseEntry[] getHead() {
        return head;
    }

    /**
     * Return true if the rule was written as a backward (as opposed to forward) rule.
     */
    public boolean isBackward() {
        return isBackward;
    }

    /**
     * Set the rule to be run backwards.
     * @param flag if true the rule should run backwards.
     */
    public void setBackward(boolean flag) {
        isBackward = flag;
    }

    /**
     * Get the name for the rule - can be null.
     */
    public String getName() {
        return name;
    }

    /**
     * Set the number of distinct variables for this rule.
     * Used internally when cloing rules, not normally required.
     */
    public void setNumVars(int n) {
        numVars = n;
    }

    /**
     * Return the number of distinct variables in the rule. Or more precisely, the
     * size of a binding environment needed to represent the rule.
     */
    public int getNumVars() {
        if (numVars == -1) {
            // only have to do this if the rule was generated programatically
            // the parser will have prefilled this in for normal rules
            int max = findVars(body, -1);
            max = findVars(head, max);
            numVars = max + 1;
        }
        return numVars;
    }

    /**
     * Find all the variables in a clause array.
     */
    private int findVars(Object[] nodes, int maxIn) {
        int max = maxIn;
        for ( Object node : nodes )
        {
            if ( node instanceof TriplePattern )
            {
                max = findVars( (TriplePattern) node, max );
            }
            else
            {
                max = findVars( (Functor) node, max );
            }
        }
        return max;
    }

    /**
     * Find all the variables in a TriplePattern.
     */
    private int findVars(TriplePattern t, int maxIn) {
        int max = maxIn;
        max = maxVarIndex(t.getSubject(), max);
        max = maxVarIndex(t.getPredicate(), max);
        Node obj = t.getObject();
        if (obj instanceof Node_RuleVariable) {
            max = maxVarIndex(obj, max);
        } else if (Functor.isFunctor(obj)) {
            max = findVars((Functor)obj.getLiteralValue(), max);
        }
        return max;
    }

    /**
     * Find all the variables in a Functor.
     */
    private int findVars(Functor f, int maxIn) {
        int max = maxIn;
        Node[] args = f.getArgs();
        for ( Node arg : args )
        {
            if ( arg.isVariable() )
            {
                max = maxVarIndex( arg, max );
            }
        }
        return max;
    }

    /**
     * Return the maximum node index of the variable and the max so far.
     */
    private int maxVarIndex(Node var, int max) {
        if (var instanceof Node_RuleVariable) {
            int index = ((Node_RuleVariable)var).index;
            if (index > max) return index;
        }
        return max;
    }

    /**
     * Instantiate a rule given a variable binding environment.
     * This will clone any non-bound variables though that is only needed
     * for trail implementations.
     */
    public Rule instantiate(BindingEnvironment env) {
        HashMap<Node_RuleVariable, Node> vmap = new HashMap<>();
        return new Rule(name, cloneClauseArray(head, vmap, env), cloneClauseArray(body, vmap, env));
    }

    /**
     * Clone a rule, cloning any embedded variables.
     */
    public Rule cloneRule() {
        if (getNumVars() > 0) {
            HashMap<Node_RuleVariable, Node> vmap = new HashMap<>();
            return new Rule(name, cloneClauseArray(head, vmap, null), cloneClauseArray(body, vmap, null));
        } else {
            return this;
        }
    }

    /**
     * Clone a clause array.
     */
    private ClauseEntry[] cloneClauseArray(ClauseEntry[] clauses, Map<Node_RuleVariable, Node> vmap, BindingEnvironment env) {
        ClauseEntry[] cClauses = new ClauseEntry[clauses.length];
        for (int i = 0; i < clauses.length; i++ ) {
            cClauses[i] = cloneClause(clauses[i], vmap, env);
        }
        return cClauses;
    }

    /**
     * Clone a clause, cloning any embedded variables.
     */
    private ClauseEntry cloneClause(ClauseEntry clause, Map<Node_RuleVariable, Node> vmap, BindingEnvironment env) {
        if (clause instanceof TriplePattern) {
            TriplePattern tp = (TriplePattern)clause;
            return new TriplePattern (
                            cloneNode(tp.getSubject(), vmap, env),
                            cloneNode(tp.getPredicate(), vmap, env),
                            cloneNode(tp.getObject(), vmap, env)
                        );
        } else {
            return cloneFunctor((Functor)clause, vmap, env);
        }
    }

    /**
     * Clone a functor, cloning any embedded variables.
     */
    private Functor cloneFunctor(Functor f, Map<Node_RuleVariable, Node> vmap, BindingEnvironment env) {
        Node[] args = f.getArgs();
        Node[] cargs = new Node[args.length];
        for (int i = 0; i < args.length; i++) {
            cargs[i] = cloneNode(args[i], vmap, env);
        }
        Functor fn = new Functor(f.getName(), cargs);
        fn.setImplementor(f.getImplementor());
        return fn;
    }

    /**
     * Close a single node.
     */
    private Node cloneNode(Node nIn, Map<Node_RuleVariable, Node> vmap, BindingEnvironment env) {
        Node n = (env == null) ? nIn : env.getGroundVersion(nIn);
        if (n instanceof Node_RuleVariable) {
            Node_RuleVariable nv = (Node_RuleVariable)n;
            Node c = vmap.get(nv);
            if (c == null) {
                c = ((Node_RuleVariable)n).cloneNode();
                vmap.put(nv, c);
            }
            return c;
        } else if (Functor.isFunctor(n)) {
            Functor f = (Functor)n.getLiteralValue();
            return Functor.makeFunctorNode(cloneFunctor(f, vmap, env));
        } else {
            return n;
        }
    }

    /**
     * Returns false for rules which can affect other rules non-monotonically (remove builtin
     * or similar) or are affected non-monotonically (involve negation-as-failure).
     */
    public boolean isMonotonic() {
        return isMonotonic;
    }

    /**
     * Returns true if the rule does not depend on any data, and so should
     * be treated as an axiom.
     */
    public boolean isAxiom() {
        if (isBackward() && body.length > 0) return false;
        for ( ClauseEntry aBody : body )
        {
            if ( aBody instanceof TriplePattern )
            {
                return false;
            }
        }
        return true;
    }

    /**
     * Printable string describing the rule
     */
    @Override
    public String toString() {
        StringBuilder buff = new StringBuilder();
        buff.append("[ ");
        if (name != null) {
            buff.append(name);
            buff.append(": ");
        }
        if (isBackward) {
            for ( ClauseEntry aHead : head )
            {
                buff.append( PrintUtil.print( aHead ) );
                buff.append( " " );
            }
            buff.append("<- ");
            for ( ClauseEntry aBody : body )
            {
                buff.append( PrintUtil.print( aBody ) );
                buff.append( " " );
            }
        } else {
            for ( ClauseEntry aBody : body )
            {
                buff.append( PrintUtil.print( aBody ) );
                buff.append( " " );
            }
            buff.append("-> ");
            for ( ClauseEntry aHead : head )
            {
                buff.append( PrintUtil.print( aHead ) );
                buff.append( " " );
            }
        }
        buff.append("]");
        return buff.toString();
    }

    /**
     * Print a short description of the rule, just its name if it
     * has one, otherwise the whole rule description.
     */
    public String toShortString() {
        if (name != null) {
            return name;
        } else {
            return toString();
        }
    }

//=======================================================================
// parser access

    /**
     * Parse a string as a rule.
     * @throws ParserException if there is a problem
     */
    public static Rule parseRule(String source) throws ParserException {
        Parser parser = new Parser(source);
        return parser.parseRule();
    }

    /**
     * Answer the list of rules parsed from the given URL.
     * @throws RulesetNotFoundException
     */
    public static List<Rule> rulesFromURL( String uri ) {
        BufferedReader br = null;
        try {
            InputStream in = FileManager.get().open(uri);
            if (in == null) throw new RulesetNotFoundException( uri );
            br = FileUtils.asBufferedUTF8( in );
            return parseRules( Rule.rulesParserFromReader( br ) );
        } finally {
            if (br != null) try { br.close(); } catch (IOException e2) {}
        }
    }

    /**
     * Processes the source reader stripping off comment lines and noting prefix
     * definitions (@prefix) and rule inclusion commands (@include).
     * Returns a parser which is bound to the stripped source text with
     * associated prefix and rule inclusion definitions.
    */
    public static Parser rulesParserFromReader( BufferedReader src ) {
       try {
           StringBuilder result = new StringBuilder();
           String line;
           Map<String, String> prefixes = new HashMap<>();
           List<Rule> preloadedRules = new ArrayList<>();
           while ((line = src.readLine()) != null) {
               if (line.startsWith("#")) continue;     // Skip comment lines
               line = line.trim();
               if (line.startsWith("//")) continue;    // Skip comment lines
               if (line.startsWith("@prefix")) {
                   line = line.substring("@prefix".length());
                   String prefix = nextArg(line);
                   String rest = nextAfterArg(line);
                   if (prefix.endsWith(":")) prefix = prefix.substring(0, prefix.length() - 1);
                   String url = extractURI(rest);
                   prefixes.put(prefix, url);

               } else if (line.startsWith("@include")) {
                   // Include referenced rule file, either URL or local special case
                   line = line.substring("@include".length());
                   String url = extractURI(line);
                   // Check for predefined cases
                   if (url.equalsIgnoreCase("rdfs")) {
                       preloadedRules.addAll( RDFSFBRuleReasoner.loadRules() );

                   } else if (url.equalsIgnoreCase("owl")) {
                       preloadedRules.addAll( OWLFBRuleReasoner.loadRules() ) ;

                   } else if (url.equalsIgnoreCase("owlmicro")) {
                       preloadedRules.addAll( OWLMicroReasoner.loadRules() ) ;

                   } else if (url.equalsIgnoreCase("owlmini")) {
                       preloadedRules.addAll( OWLMiniReasoner.loadRules() ) ;

                   } else {
                       // Just try loading as a URL
                       preloadedRules.addAll( rulesFromURL(url) );
                   }

               } else {
                   result.append(line);
                   result.append("\n");
               }
           }
           Parser parser = new Parser(result.toString());
           parser.registerPrefixMap(prefixes);
           parser.addRulesPreload(preloadedRules);
           return parser;
       }
       catch (IOException e)
           { throw new WrappedIOException( e ); }
   }

    /**
     * Helper function find a URI argument in the current string,
     * optionally surrounded by matching <>.
     */
    private static String extractURI(String lineSoFar) {
        String token = lineSoFar.trim();
        if (token.startsWith("<")) {
            int split = token.indexOf('>');
            token = token.substring(1, split);
        }
        return token;
    }

    /**
     * Helper function to return the next whitespace delimited argument
     * from the string
     */
    private static String nextArg(String token) {
        int start = nextSplit(0, false, token);
        int stop = nextSplit(start, true, token);
        return token.substring(start, stop);
    }

    /**
     * Helper function to return the remainder of the line after
     * stripping off the next whitespace delimited argument
     * from the string
     */
    private static String nextAfterArg(String token) {
        int start = nextSplit(0, false, token);
        int stop = nextSplit(start, true, token);
        int rest = nextSplit(stop, false, token);
        return token.substring(rest);
    }

    /**
     * Helper function - find index of next whitespace or non white
     * after the start index.
     */
    private static int nextSplit(int start, boolean white, String line) {
        int i = start;
        while (i < line.length()) {
            boolean isWhite = Character.isWhitespace(line.charAt(i));
            if ((white & isWhite) || (!white & !isWhite)) {
                return i;
            }
            i++;
        }
        return i;
    }

    /**
     * Run a pre-bound rule parser to extract it's rules
     * @return a list of rules
     * @throws ParserException if there is a problem
     */
    public static List<Rule> parseRules(Parser parser) throws ParserException {
        boolean finished = false;
        List<Rule> ruleset = new ArrayList<>();
        ruleset.addAll(parser.getRulesPreload());
        while (!finished) {
            try {
                parser.peekToken();
            } catch (NoSuchElementException e) {
                finished = true;
                break;
            }
            Rule rule = parser.parseRule();
            ruleset.add(rule);
        }
        return ruleset;
    }

    /**
     * Parse a string as a list a rules.
     * @return a list of rules
     * @throws ParserException if there is a problem
     */
    public static List<Rule> parseRules(String source) throws ParserException {
        return parseRules(new Parser(source));
    }

//=======================================================================
// parser support

    /**
     * Inner class which provides minimalist parsing support based on
     * tokenisation with depth 1 lookahead. No sensible error reporting on offer.
     * No embedded spaces supported.
     */
    public static class Parser {

        /** Tokenizer */
        private Tokenizer stream;

        /** Look ahead, null if none */
        private String lookahead;

        // Literal parse state flags
        private static final int NORMAL = 0;
        private static final int STARTED_LITERAL = 1;

        /** Literal parse state */
        private int literalState = NORMAL;

        /** Trace back of recent tokens for error reporting */
        protected List<String> priorTokens = new ArrayList<>();

        /** Maximum number of recent tokens to remember */
        private static final int maxPriors = 20;

        /** Variable table */
        private Map<String, Node_RuleVariable> varMap;

        /** Local prefix map */
        private PrefixMapping prefixMapping = PrefixMapping.Factory.create();

        /** Pre-included rules */
        private List<Rule> preloadedRules = new ArrayList<>();

        /**
         * Constructor
         * @param source the string to be parsed
         */
        Parser(String source) {
            stream = new Tokenizer(source, "()[], \t\n\r", "'\"", true);
            lookahead = null;
        }

        /**
         * Register a new namespace prefix with the parser
         */
        public void registerPrefix(String prefix, String namespace ) {
            prefixMapping.setNsPrefix(prefix, namespace);
        }

        /**
         * Register a set of prefix to namespace mappings with the parser
         */
        public void registerPrefixMap(Map<String, String> map) {
            prefixMapping.setNsPrefixes(map);
        }

        /**
         * Return a map of all the discovered prefixes
         */
        public Map<String, String> getPrefixMap() {
            return prefixMapping.getNsPrefixMap();
        }

        /**
         * Add a new set of preloaded rules.
         */
        void addRulesPreload(List<Rule> rules) {
            preloadedRules.addAll(rules);
        }

        /**
         * Return the complete set of preloaded rules;
         */
        public List<Rule> getRulesPreload() {
            return preloadedRules;
        }

        /**
         * Return the next token
         */
        String nextToken() {
            if (lookahead != null) {
                String temp = lookahead;
                lookahead = null;
                return temp;
            } else {
                String token = stream.nextToken();
                if (literalState == NORMAL) {
                    // Skip separators unless within a literal
                    while (isSeparator(token)) {
                        token = stream.nextToken();
                    }
                }
                if (token.equals("'")) {
                    if (literalState == NORMAL) {
                        literalState = STARTED_LITERAL;
                    } else {
                        literalState = NORMAL;
                    }
                }
                priorTokens.add(0, token);
                if (priorTokens.size() > maxPriors) {
                    priorTokens.remove(priorTokens.size()-1);
                }
                return token;
            }
        }

        /**
         * Return a trace of the recently seen tokens, for use
         * in error reporting
         */
        public String recentTokens() {
            StringBuilder trace = new StringBuilder();
            for (int i = priorTokens.size()-1; i >= 0; i--) {
                trace.append(priorTokens.get(i));
                trace.append(" ");
            }
            return trace.toString();
        }

        /**
         * Peek ahead one token.
         */
        String peekToken() {
            if (lookahead == null) {
                lookahead = nextToken();
            }
            return lookahead;
        }

        /**
         * Push back a previously fetched token. Only depth 1 supported.
         */
        void pushback(String token) {
            lookahead = token;
        }

        /**
         * Returns true if token is an skippable separator
         */
        boolean isSeparator(String token) {
            if (token.length() == 1) {
                char c = token.charAt(0);
                return (c == ',' || Character.isWhitespace(c));
            }
            return false;
        }

        /**
         * Returns true if token is a syntax element ()[]
         */
        boolean isSyntax(String token) {
            if (token.length() == 1) {
                char c = token.charAt(0);
                return (c == '(' || c == ')' || c == '[' || c == ']');
            }
            return false;
        }

        /**
         * Find the variable index for the given variable name
         * and return a Node_RuleVariable with that index.
         */
        Node_RuleVariable getNodeVar(String name) {
            Node_RuleVariable node = varMap.get(name);
            if (node == null) {
                node = new Node_RuleVariable(name, varMap.size());
                varMap.put(name, node);
            }
            return node;
        }

        /**
         * Translate a token to a node.
         */
        Node parseNode(String token) {
            if (token.startsWith("?")) {
                return getNodeVar(token);
                // Dropped support for anon wildcards until the implementation is better resolved
            } else if (token.equals("*") || token.equals("_")) {
                throw new ParserException("Wildcard variables no longer supported", this);
////                return Node_RuleVariable.ANY;
//                return Node_RuleVariable.WILD;
            } else if (token.startsWith("<") && token.endsWith(">")) {
                String uri = token.substring(1, token.length()-1);
                return NodeFactory.createURI(uri);
            } else if (token.startsWith( "_" )) { // TODO rationalise [this is for the RIF code]
                return NodeFactory.createAnon( new AnonId( token.substring( 1 ) ) );
            } else if (token.indexOf(':') != -1) {
                String exp = prefixMapping.expandPrefix(token); // Local map first
                exp = PrintUtil.expandQname(exp);  // Retain global map for backward compatibility
                if (exp == token) {
                    // No expansion was possible
                    String prefix = token.substring(0, token.indexOf(':'));
                    if (prefix.equals("http") || prefix.equals("urn") || prefix.equals("file")
                     || prefix.equals("ftp") || prefix.equals("mailto")) {
                        // assume it is all OK and fall through
                    } else {
                        // Likely to be a typo in a qname or failure to register
                        throw new ParserException("Unrecognized qname prefix (" + prefix + ") in rule", this);
                    }
                }
                return NodeFactory.createURI(exp);
            } else if (peekToken().equals("(")) {
                Functor f = new Functor(token, parseNodeList(), BuiltinRegistry.theRegistry);
                return Functor.makeFunctorNode( f );
            } else if (token.equals("'") || token.equals("\"")) {
                // A plain literal
                String lit = nextToken();
                // Skip the trailing quote
                nextToken();
                // Check for an explicit datatype
                if (peekToken().startsWith("^^")) {
                    String dtURI = nextToken().substring(2);
                    if (dtURI.indexOf(':') != -1) {
                        // Thanks to Steve Cranefield for pointing out the need for prefix expansion here
                        String exp = prefixMapping.expandPrefix(dtURI); // Local map first
                        exp = PrintUtil.expandQname(exp);  // Retain global map for backward compatibility
                        if (exp == dtURI) {
                            // No expansion was possible
                            String prefix = dtURI.substring(0, dtURI.indexOf(':'));
                            if (prefix.equals("http") || prefix.equals("urn")
                             || prefix.equals("ftp") || prefix.equals("mailto")) {
                                // assume it is all OK and fall through
                            } else {
                                // Likely to be a typo in a qname or failure to register
                                throw new ParserException("Unrecognized qname prefix (" + prefix + ") in rule", this);
                            }
                        } else {
                            dtURI = exp;
                        }
                    }
                    RDFDatatype dt = TypeMapper.getInstance().getSafeTypeByName(dtURI);
                    return NodeFactory.createLiteral(lit, dt);
                } else {
                    return NodeFactory.createLiteral(lit, "");
                }
            } else  if ( Character.isDigit(token.charAt(0)) ||
                         (token.charAt(0) == '-' && token.length() > 1 && Character.isDigit(token.charAt(1))) ) {
                // A number literal
               return parseNumber(token);
            } else {
                // A  uri
                return NodeFactory.createURI(token);
            }
        }

        /**
         * Turn a possible numeric token into typed literal else a plain literal
         * @return the constructed literal node
         */
        Node parseNumber(String lit) {
            if ( Character.isDigit(lit.charAt(0)) ||
                (lit.charAt(0) == '-' && lit.length() > 1 && Character.isDigit(lit.charAt(1))) ) {
                if ( lit.contains( "." ) ) {
                    // Float?
                    if (XSDDatatype.XSDfloat.isValid(lit)) {
                        return NodeFactory.createLiteral(lit, XSDDatatype.XSDfloat);
                    }
                } else {
                    // Int?
                    if (XSDDatatype.XSDint.isValid(lit)) {
                        return NodeFactory.createLiteral(lit, XSDDatatype.XSDint);
                    }
                }
            }
            // Default is a plain literal
            return NodeFactory.createLiteral(lit, "");
        }

        /**
         * Parse a list of nodes delimited by parentheses
         */
        List<Node> parseNodeList() {
            String token = nextToken();
            if (!token.equals("(")) {
                throw new ParserException("Expected '(' at start of clause, found " + token, this);
            }
            token = nextToken();
            List<Node> nodeList = new ArrayList<>();
            while (!isSyntax(token)) {
                nodeList.add(parseNode(token));
                token = nextToken();
            }
            if (!token.equals(")")) {
                throw new ParserException("Expected ')' at end of clause, found " + token, this);
            }
            return nodeList;
        }

        /**
         * Parse a clause, could be a triple pattern, a rule or a functor
         */
        ClauseEntry parseClause() {
            String token = peekToken();
            if (token.equals("(")) {
                List<Node> nodes = parseNodeList();
                if (nodes.size() != 3) {
                    throw new ParserException("Triple with " + nodes.size() + " nodes!", this);
                }
                if (Functor.isFunctor(nodes.get(0))) {
                    throw new ParserException("Functors not allowed in subject position of pattern", this);
                }
                if (Functor.isFunctor(nodes.get(1))) {
                    throw new ParserException("Functors not allowed in predicate position of pattern", this);
                }
                return new TriplePattern(nodes.get(0), nodes.get(1), nodes.get(2));
            } else if (token.equals("[")) {
                nextToken();
                return doParseRule(true);
            } else {
                String name = nextToken();
                List<Node> args = parseNodeList();
                Functor clause = new Functor(name, args, BuiltinRegistry.theRegistry);
                if (clause.getImplementor() == null) {
                    // Not a.error error becase later processing can add this
                    // implementation to the registry
                    logger.warn("Rule references unimplemented functor: " + name);
                }
                return clause;
            }
        }

        /**
         * Parse a rule, terminated by a "]" or "." character.
         */
        public Rule parseRule() {
            return doParseRule(false);
        }

        /**
         * Parse a rule, terminated by a "]" or "." character.
         * @param retainVarMap set to true to ccause the existing varMap to be left in place, which
         * is required for nested rules.
         */
        private Rule doParseRule(boolean retainVarMap) {
            try {
                // Skip initial '[' if present
                if (peekToken().equals("[")) {
                    nextToken();
                }
                // Check for optional name
                String name = null;
                String token = peekToken();
                if (token.endsWith(":")) {
                    name = token.substring(0, token.length()-1);
                    nextToken();
                }
                // Start rule parsing with empty variable table
                if (!retainVarMap) varMap = new HashMap<>();
                // Body
                List<ClauseEntry> body = new ArrayList<>();
                token = peekToken();
                while ( !(token.equals("->") || token.equals("<-")) ) {
                    body.add(parseClause());
                    token = peekToken();
                }
                boolean backwardRule = token.equals("<-");
                List<ClauseEntry> head = new ArrayList<>();
                token = nextToken();   // skip -> token
                token = peekToken();
                while ( !(token.equals(".") || token.equals("]")) ) {
                    head.add(parseClause());
                    token = peekToken();
                }
                nextToken();        // consume the terminating token
                Rule r = null;
                if (backwardRule) {
                    r =  new Rule(name, body, head);
                } else {
                    r = new Rule(name, head, body);
                }
                r.numVars = varMap.keySet().size();
                r.isBackward = backwardRule;
                return r;
            } catch (NoSuchElementException e) {
                throw new ParserException("Malformed rule", this);
            }
        }

    }

    /** Equality override */
    @Override
    public boolean equals(Object o) {
        // Pass 1 - just check basic shape
        if (! (o instanceof Rule) ) return false;
        Rule other = (Rule) o;
        if (other.head.length != head.length) return false;
        if (other.body.length != body.length) return false;
        // Pass 2 - check clause by clause matching
        for (int i = 0; i < body.length; i++) {
            if (! (body[i]).sameAs(other.body[i]) ) return false;
        }
        for (int i = 0; i < head.length; i++) {
            if (! (head[i]).sameAs(other.head[i]) ) return false;
        }
        // Also include the rule name in the equality contract
        if (name != null) {
            if ( !name.equals(other.name) ) return false;
        } else {
            if (other.name != null) return false;
        }
        return true;
    }

    /** hash function override */
    @Override
    public int hashCode() {
        int hash = 0;
        for ( ClauseEntry aBody : body )
        {
            hash = ( hash << 1 ) ^ aBody.hashCode();
        }
        for ( ClauseEntry aHead : head )
        {
            hash = ( hash << 1 ) ^ aHead.hashCode();
        }
        return hash;
    }

    /**
     * Compare clause entries, taking into account variable indices.
     * The equality function ignores differences between variables.
     */
    @Override
    public boolean sameAs(Object o) {
        return equals(o);
    }

//=======================================================================
// Other supporting inner classes

    /**
     * Inner class. Exception raised if there is a problem
     * during rule parsing.
     */
    public static class ParserException extends JenaException {

        /** constructor */
        public ParserException(String message, Parser parser) {
            super(constructMessage(message, parser));
        }

        /**
         * Extract context trace from prior tokens stack
         */
        private static String constructMessage(String baseMessage, Parser parser) {
            StringBuilder message = new StringBuilder();
            message.append(baseMessage);
            message.append("\nAt '");
            message.append(parser.recentTokens());
            message.append("'");
            return message.toString();
        }

    }

}


text:
/**
 * Bean Validation TCK
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */
package org.hibernate.beanvalidation.tck.common;

import java.io.InputStream;

import javax.validation.BootstrapConfiguration;
import javax.validation.ClockProvider;
import javax.validation.Configuration;
import javax.validation.ConstraintValidatorFactory;
import javax.validation.MessageInterpolator;
import javax.validation.ParameterNameProvider;
import javax.validation.TraversableResolver;
import javax.validation.ValidatorFactory;
import javax.validation.spi.ValidationProvider;
import javax.validation.valueextraction.ValueExtractor;

/**
 * @author Hardy Ferentschik
 */
public class TCKValidatorConfiguration implements Configuration<TCKValidatorConfiguration> {
	private final ValidationProvider<?> provider;

	public TCKValidatorConfiguration() {
		provider = null;
	}

	public TCKValidatorConfiguration(ValidationProvider<?> provider) {
		this.provider = provider;
	}

	@Override
	public TCKValidatorConfiguration ignoreXmlConfiguration() {
		throw new UnsupportedOperationException();
	}

	@Override
	public TCKValidatorConfiguration messageInterpolator(MessageInterpolator interpolator) {
		throw new UnsupportedOperationException();
	}

	@Override
	public TCKValidatorConfiguration traversableResolver(TraversableResolver resolver) {
		throw new UnsupportedOperationException();
	}

	@Override
	public TCKValidatorConfiguration constraintValidatorFactory(ConstraintValidatorFactory constraintValidatorFactory) {
		throw new UnsupportedOperationException();
	}

	@Override
	public TCKValidatorConfiguration parameterNameProvider(ParameterNameProvider parameterNameProvider) {
		throw new UnsupportedOperationException();
	}

	@Override
	public TCKValidatorConfiguration clockProvider(ClockProvider clockProvider) {
		throw new UnsupportedOperationException();
	}

	@Override
	public TCKValidatorConfiguration addMapping(InputStream stream) {
		throw new UnsupportedOperationException();
	}

	@Override
	public TCKValidatorConfiguration addProperty(String name, String value) {
		throw new UnsupportedOperationException();
	}

	@Override
	public TCKValidatorConfiguration addValueExtractor(ValueExtractor<?> extractor) {
		throw new UnsupportedOperationException();
	}

	@Override
	public MessageInterpolator getDefaultMessageInterpolator() {
		throw new UnsupportedOperationException();
	}

	@Override
	public TraversableResolver getDefaultTraversableResolver() {
		throw new UnsupportedOperationException();
	}

	@Override
	public ConstraintValidatorFactory getDefaultConstraintValidatorFactory() {
		throw new UnsupportedOperationException();
	}

	@Override
	public ParameterNameProvider getDefaultParameterNameProvider() {
		throw new UnsupportedOperationException();
	}

	@Override
	public ClockProvider getDefaultClockProvider() {
		throw new UnsupportedOperationException();
	}

	@Override
	public BootstrapConfiguration getBootstrapConfiguration() {
		throw new UnsupportedOperationException();
	}

	@Override
	public ValidatorFactory buildValidatorFactory() {
		return provider.buildValidatorFactory( null );
	}

}


text:
module EbayTrading # :nodoc:
  module Types # :nodoc:
    class FeedbackTypeCode
      extend Enumerable
      extend Enumeration
      FeedbackReceivedAsSeller = 'FeedbackReceivedAsSeller'
      FeedbackReceivedAsBuyer = 'FeedbackReceivedAsBuyer'
      FeedbackReceived = 'FeedbackReceived'
      FeedbackLeft = 'FeedbackLeft'
    end
  end
end


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.util;

import com.google.common.collect.ImmutableList;

import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;

import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.util.Objects.requireNonNull;

public class MoreLists
{
    public static <T> List<List<T>> listOfListsCopy(List<List<T>> lists)
    {
        return requireNonNull(lists, "lists is null").stream()
                .map(ImmutableList::copyOf)
                .collect(toImmutableList());
    }

    public static <T> List<T> filteredCopy(List<T> elements, Predicate<T> predicate)
    {
        requireNonNull(elements, "elements is null");
        requireNonNull(predicate, "predicate is null");
        return elements.stream()
                .filter(predicate)
                .collect(toImmutableList());
    }

    public static <T, R> List<R> mappedCopy(List<T> elements, Function<T, R> mapper)
    {
        requireNonNull(elements, "elements is null");
        requireNonNull(mapper, "mapper is null");
        return elements.stream()
                .map(mapper)
                .collect(toImmutableList());
    }

    private MoreLists() {}
}


text:
Registuojami pacientai pas gydytojus
#Gydytoju registracija
Gydytojai gali peržiūrėti laukiančius pacientus, savo darbo laikus
#Ligonių registracia
Ligonis gali pasirinkti sau gydytojo laiką, redaguoti jį


text:
describe("luga.validator.SelectValidator", function(){

	"use strict";

	it("Implements the luga.validator.BaseFieldValidator abstract class", function(){
		const validator = luga.validator.fieldValidatorFactory.getInstance({
			fieldNode: document.createElement("select")
		});
		const MockValidator = function(options){
			luga.extend(luga.validator.BaseFieldValidator, this, [options]);
		};
		const node = document.createElement("input");
		node.setAttribute("type", "text");
		expect(validator).toMatchDuckType(new MockValidator({
			fieldNode: node
		}));
	});

	it("Handle select-multiple", function(){
		const selectNode = document.createElement("select");
		selectNode.setAttribute("multiple", "multiple");
		const validator = luga.validator.fieldValidatorFactory.getInstance({
			fieldNode: selectNode
		});
		const MockValidator = function(options){
			luga.extend(luga.validator.BaseFieldValidator, this, [options]);
		};
		const node = document.createElement("input");
		node.setAttribute("type", "text");
		expect(validator).toMatchDuckType(new MockValidator({
			fieldNode: node
		}));
	});

	it("Throws an exception if the associated field node does not exists", function(){
		expect(function(){
			new luga.validator.SelectValidator({
				fieldNode: document.getElementById("missing")
			});
		}).toThrow();
	});

	describe("Accepts an Options object as single argument", function(){

		let basicSelectValidator, attributeSelectValidator, configSelectValidator;
		beforeEach(function(){

			basicSelectValidator = luga.validator.fieldValidatorFactory.getInstance({
				fieldNode: document.createElement("select")
			});

			const selectNode = document.createElement("select");
			selectNode.setAttribute("name", "dish");
			selectNode.setAttribute("data-lugavalidator-errorclass", "invalid-select");
			selectNode.setAttribute("data-lugavalidator-message", "Invalid select!");
			selectNode.setAttribute("data-lugavalidator-invalidindex", "1");
			selectNode.setAttribute("data-lugavalidator-invalidvalue", "Crepes");

			attributeSelectValidator = luga.validator.fieldValidatorFactory.getInstance({
				fieldNode: selectNode
			});

			configSelectValidator = new luga.validator.SelectValidator({
				fieldNode: document.createElement("select"),
				errorclass: "invalid-select",
				message: "Invalid select!",
				invalidindex: 1,
				invalidvalue: "Crepes"
			});

		});

		describe("options.invalidindex either:", function(){

			it("Default to 'null'", function(){
				expect(basicSelectValidator.config.invalidindex).toEqual(null);
			});

			it("Retrieves the value from the field's data-lugavalidator-invalidindex custom attribute", function(){
				expect(attributeSelectValidator.config.invalidindex).toEqual("1");
			});

			it("Uses the value specified inside the option argument", function(){
				expect(configSelectValidator.config.invalidindex).toEqual(1);
			});
		});

		describe("options.invalidvalue either:", function(){

			it("Default to 'null'", function(){
				expect(basicSelectValidator.config.invalidvalue).toEqual(null);
			});

			it("Retrieves the value from the field's data-lugavalidator-invalidvalue custom attribute", function(){
				expect(attributeSelectValidator.config.invalidvalue).toEqual("Crepes");
			});

			it("Uses the value specified inside the option argument", function(){
				expect(configSelectValidator.config.invalidvalue).toEqual("Crepes");
			});
		});

		describe("options.errorclass either:", function(){

			it("Default to an empty string", function(){
				expect(basicSelectValidator.config.errorclass).toEqual("");
			});

			it("Retrieves the value from the field's data-lugavalidator-errorclass custom attribute", function(){
				expect(attributeSelectValidator.config.errorclass).toEqual("invalid-select");
			});

			it("Uses the value specified inside the option argument", function(){
				expect(configSelectValidator.config.errorclass).toEqual("invalid-select");
			});
		});

		describe("options.message either:", function(){

			it("Default to an empty string", function(){
				basicSelectValidator.flagInvalid();
				expect(basicSelectValidator.config.message).toEqual("");
				// We have neither message or error class
				expect(basicSelectValidator.node.title).toEqual("");
				expect(basicSelectValidator.node.classList.length).toEqual(0);
			});

			it("Retrieves the value from the field's data-lugavalidator-message custom attribute", function(){
				expect(attributeSelectValidator.config.message).toEqual("Invalid select!");
			});

			it("Uses the value specified inside the option argument", function(){
				expect(configSelectValidator.config.message).toEqual("Invalid select!");
			});
		});

	});

	describe("data-lugavalidator-invalidindex", function(){

		it("Accepts only numbers", function(){
			const selectNode = document.createElement("select");
			selectNode.setAttribute("data-lugavalidator-invalidindex", "test");
			expect(function(){
				luga.validator.fieldValidatorFactory.getInstance({
					fieldNode: selectNode
				});
			}).toThrow();
		});

		it("Prevents selection of an entry on a given position", function(){
			jasmineFixtures.loadHTML("validator/SelectValidator/invalidindex.htm");
			let selectValidator = null;

			selectValidator = luga.validator.fieldValidatorFactory.getInstance({
				fieldNode: document.getElementById("notSelected")
			});
			expect(selectValidator.isValid()).toEqual(false);

			selectValidator = luga.validator.fieldValidatorFactory.getInstance({
				fieldNode: document.getElementById("kateSelected")
			});
			expect(selectValidator.isValid()).toEqual(true);
		});

		it("Works around a weird brower bug when the size attribute is specified", function(){
			jasmineFixtures.loadHTML("validator/SelectValidator/invalidindex.htm");
			let selectValidator = null;

			selectValidator = luga.validator.fieldValidatorFactory.getInstance({
				fieldNode: document.getElementById("selectWithSize")
			});
			expect(selectValidator.isValid()).toEqual(false);

		});

	});

	describe("data-lugavalidator-invalidvalue", function(){

		it("Prevents selection of an entry with a given value", function(){
			jasmineFixtures.loadHTML("validator/SelectValidator/invalidvalue.htm");
			let selectValidator = null;

			selectValidator = luga.validator.fieldValidatorFactory.getInstance({
				fieldNode: document.getElementById("pizza")
			});
			expect(selectValidator.isValid()).toEqual(false);

			selectValidator = luga.validator.fieldValidatorFactory.getInstance({
				fieldNode: document.getElementById("spaghetti")
			});
			expect(selectValidator.isValid()).toEqual(true);
		});

	});

});


text:
import { module, test } from 'qunit';
import mobileDetection from "ember-mobiletouch/utils/is-mobile";

var currentModuleLabel = null;
var currentModuleHooks = null;
var currentTests = [];

// Save the label and hooks so we can use them with each pair of tests.
var pairModule = function(label, hooks) {
  if (currentModuleLabel || currentModuleHooks) {
    throw new Error("Pair test wasn't cleaned up");
  }
  currentModuleLabel = label;
  currentModuleHooks = hooks;
};

// Save the tests so we can instantiate each test with each module in the pair.
var pairTest = function(label, callback) {
  currentTests.push([label, callback]);
};

// This function is necessary to trigger the tests to be instantiated. We need
// to instantiate all the tests with one module and then all the tests with the
// second module. Without a function to conclude the batch, we won't know when
// the tests are done being defined.
var pairConclude = function() {
  if (!currentModuleLabel) {
    throw "Missing module";
  }

  var hooks = currentModuleHooks || {};
  var label = currentModuleLabel;
  var origBeforeEach = hooks.beforeEach;
  var origAfterEach = hooks.afterEach;

  // Build a module for when IS_MOBILE is true and one for when it's false
  [true,false].forEach(function(isMobile) {

    // Make a new beforeEach and afterEach function.
    hooks.beforeEach = function() {
      mobileDetection.fake(isMobile);
      if (!!origBeforeEach) {
        origBeforeEach.call({});
      }
    };
    hooks.afterEach = function() {
      if (!!origAfterEach) {
        origAfterEach.call({});
      }
      mobileDetection.detect();
    };

    // Instantiate a module with these updated hooks.
    var desc = isMobile ? "(mobile)" : "(desktop)";
    var fullLabel = label + " " + desc;
    module(fullLabel, hooks);

    // Instantiate one of each test for this module.
    currentTests.forEach(function(labelCallbackTuple) {
      var label = labelCallbackTuple[0];
      var callback = labelCallbackTuple[1];
      test(label, callback);
    });

  });

  // Cleanup.
  currentModuleLabel = null;
  currentModuleHooks = null;
  currentTests = [];
};

export { pairTest, pairModule, pairConclude };