text:
<?xml version="1.0" standalone="no" ?>
<!DOCTYPE pov SYSTEM "/usr/share/cgc-docs/replay.dtd">
<pov>
	<cbid>CROMU_00001</cbid>
	<replay>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>tvkrxpd\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>jxnzvly\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>kqnyvpu\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>2\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>tvkrxpd\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>Login Success\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
		<write echo="ascii"><data>jxnzvly\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
		<write echo="ascii"><data>lbnleiyqzjxzehoyuerdxvzfeu\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
		<write echo="ascii"><data>tvkrxpd\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
		<write echo="ascii"><data>fvdxglphcseibcszdwmjhviiatu\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>Unread messages:\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>1:  fvdxglphcseibcszdwmjhviiatu\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>3\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>1:  fvdxglphcseibcszdwmjhviiatu\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
		<write echo="ascii"><data>kqnyvpu\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
		<write echo="ascii"><data>zfgjymnteknfpbmeql\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
		<write echo="ascii"><data>jxnzvly\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
		<write echo="ascii"><data>cbvitxqcvhkprdnueebfy\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
		<write echo="ascii"><data>tvkrxpd\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
		<write echo="ascii"><data>kzpszqykwqzxgh\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>Unread messages:\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2:  kzpszqykwqzxgh\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
		<write echo="ascii"><data>jxnzvly\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
		<write echo="ascii"><data>dyyvmbizppphqtiphgazghrbj\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
		<write echo="ascii"><data>tvkrxpd\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
		<write echo="ascii"><data>jwihykhdfyitqnazyms\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>Unread messages:\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3:  jwihykhdfyitqnazyms\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>4\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>ID: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
		<write echo="ascii"><data>tvkrxpd\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
		<write echo="ascii"><data>gsiemeoirf\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>Unread messages:\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4:  gsiemeoirf\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
		<write echo="ascii"><data>kqnyvpu\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
		<write echo="ascii"><data>czkyhjmnd\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>3\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2:  kzpszqykwqzxgh\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3:  jwihykhdfyitqnazyms\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4:  gsiemeoirf\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
		<write echo="ascii"><data>jxnzvly\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
		<write echo="ascii"><data>ryjqtjhrieooexnzwz\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
		<write echo="ascii"><data>jxnzvly\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
		<write echo="ascii"><data>mlqrlfkvwjrw\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
		<write echo="ascii"><data>tvkrxpd\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
		<write echo="ascii"><data>snclmjplydetywzmyahfekgkw\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>Unread messages:\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5:  snclmjplydetywzmyahfekgkw\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>5\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>Logging out...\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>2\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>kqnyvpu\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>Login Success\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>Unread messages:\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>1:  zfgjymnteknfpbmeql\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2:  czkyhjmnd\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>6\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>Exiting...\n</data></match></read>
	</replay>
</pov>


text:
package org.estatio.module.lease.integtests.amendments;

import java.util.List;

import javax.inject.Inject;

import org.joda.time.LocalDate;
import org.junit.Before;
import org.junit.Test;

import org.apache.isis.applib.fixturescripts.FixtureScript;

import org.estatio.module.asset.fixtures.property.enums.Property_enum;
import org.estatio.module.lease.dom.Lease;
import org.estatio.module.lease.dom.amendments.LeaseAmendment;
import org.estatio.module.lease.dom.amendments.LeaseAmendmentAgreementTypeEnum;
import org.estatio.module.lease.dom.amendments.LeaseAmendmentState;
import org.estatio.module.lease.dom.amendments.LeaseAmendmentTemplate;
import org.estatio.module.lease.dom.amendments.LeaseAmendmentRepository;
import org.estatio.module.lease.fixtures.lease.enums.Lease_enum;
import org.estatio.module.lease.integtests.LeaseModuleIntegTestAbstract;

import static org.assertj.core.api.Assertions.assertThat;

public class LeaseAmendmentRepository_IntegTest extends LeaseModuleIntegTestAbstract {

    @Before
    public void setupData() {
        runFixtureScript(new FixtureScript() {
            @Override
            protected void execute(ExecutionContext executionContext) {
                executionContext.executeChild(this, Lease_enum.OxfMediaX002Gb.builder());
            }
        });
    }

    @Test
    public void upsert_and_finders_work() throws Exception {

        // given
        final Lease lease = Lease_enum.OxfMediaX002Gb.findUsing(serviceRegistry);
        final LocalDate startDate = new LocalDate(2020, 1, 15);
        final LocalDate endDate = new LocalDate(2020, 3, 31);
        final LeaseAmendmentState state = LeaseAmendmentState.PROPOSED;

        // when
        LeaseAmendment leaseAmendment = leaseAmendmentRepository
                .upsert(lease, LeaseAmendmentTemplate.DEMO_TYPE, state, startDate, endDate);

        // then
        assertThat(leaseAmendment.getLease()).isEqualTo(lease);
        assertThat(leaseAmendment.getState()).isEqualTo(state);
        assertThat(leaseAmendment.getStartDate()).isEqualTo(startDate);
        assertThat(leaseAmendment.getEndDate()).isEqualTo(endDate);
        assertThat(leaseAmendment.getType().getTitle()).isEqualTo(LeaseAmendmentAgreementTypeEnum.LEASE_AMENDMENT.getTitle());
        assertThat(leaseAmendment.getReference()).isEqualTo(lease.getReference().concat(LeaseAmendmentTemplate.DEMO_TYPE.getRef_suffix()));
        assertThat(leaseAmendment.getName()).isEqualTo(lease.getReference().concat(LeaseAmendmentTemplate.DEMO_TYPE.getRef_suffix()));
        assertThat(leaseAmendment.getAtPath()).isEqualTo(lease.getApplicationTenancyPath());
        assertThat(leaseAmendment.getApplicationTenancy()).isEqualTo(lease.getApplicationTenancy());
        assertThat(leaseAmendment.getRoles()).hasSize(2);
        assertThat(leaseAmendment.getPrimaryParty()).isEqualTo(lease.getPrimaryParty());
        assertThat(leaseAmendment.getSecondaryParty()).isEqualTo(lease.getSecondaryParty());

        // and when
        final List<LeaseAmendment> resultForLease = leaseAmendmentRepository.findByLease(lease);
        // then
        assertThat(resultForLease).hasSize(1);
        assertThat(resultForLease.get(0)).isEqualTo(leaseAmendment);

        // and when
        final List<LeaseAmendment> resultForState = leaseAmendmentRepository.findByState(state);
        // then
        assertThat(resultForState).hasSize(1);
        assertThat(resultForState.get(0)).isEqualTo(leaseAmendment);

        // and when
        final List<LeaseAmendment> resultsForDemoType = leaseAmendmentRepository.findByTemplate(LeaseAmendmentTemplate.DEMO_TYPE);
        final List<LeaseAmendment> resultsForDemoTypeOxf = leaseAmendmentRepository.findByTemplateAndProperty(
                LeaseAmendmentTemplate.DEMO_TYPE, Property_enum.OxfGb.findUsing(serviceRegistry));
        final List<LeaseAmendment> resultsForDemoTypeRon = leaseAmendmentRepository.findByTemplateAndProperty(
                LeaseAmendmentTemplate.DEMO_TYPE, Property_enum.RonIt.findUsing(serviceRegistry));
        final List<LeaseAmendment> resultsForOxf = leaseAmendmentRepository.findByProperty(Property_enum.OxfGb.findUsing(serviceRegistry));
        final List<LeaseAmendment> resultsForRon = leaseAmendmentRepository.findByProperty(Property_enum.RonIt.findUsing(serviceRegistry));
        final List<LeaseAmendment> resultsForOxfProposed = leaseAmendmentRepository.findByPropertyAndState(Property_enum.OxfGb.findUsing(serviceRegistry), LeaseAmendmentState.PROPOSED);
        final List<LeaseAmendment> resultsForOxfSigned = leaseAmendmentRepository.findByPropertyAndState(Property_enum.OxfGb.findUsing(serviceRegistry), LeaseAmendmentState.SIGNED);
        final List<LeaseAmendment> resultsForDemoTypeAndProposed = leaseAmendmentRepository.findByTemplateAndState(
                LeaseAmendmentTemplate.DEMO_TYPE, LeaseAmendmentState.PROPOSED);
        final List<LeaseAmendment> resultsForDemoTypeAndSigned = leaseAmendmentRepository.findByTemplateAndState(
                LeaseAmendmentTemplate.DEMO_TYPE, LeaseAmendmentState.SIGNED);
        final List<LeaseAmendment> resultsForDemoTypeAndProposedForOxf = leaseAmendmentRepository.findByTemplateAndStateAndProperty(
                LeaseAmendmentTemplate.DEMO_TYPE, LeaseAmendmentState.PROPOSED,
                Property_enum.OxfGb.findUsing(serviceRegistry));
        final List<LeaseAmendment> resultsForDemoTypeAndProposedForRon = leaseAmendmentRepository.findByTemplateAndStateAndProperty(
                LeaseAmendmentTemplate.DEMO_TYPE, LeaseAmendmentState.PROPOSED,
                Property_enum.RonIt.findUsing(serviceRegistry));
        final List<LeaseAmendment> resultsForOtherType = leaseAmendmentRepository.findByTemplate(LeaseAmendmentTemplate.COVID_ITA_FREQ_CHANGE_ONLY);
        // then
        assertThat(resultsForDemoType).hasSize(1);
        assertThat(resultsForDemoTypeOxf).hasSize(1);
        assertThat(resultsForDemoTypeRon).isEmpty();
        assertThat(resultsForOxf).hasSize(1);
        assertThat(resultsForRon).isEmpty();
        assertThat(resultsForOxfProposed).hasSize(1);
        assertThat(resultsForOxfSigned).isEmpty();
        assertThat(resultsForDemoTypeAndProposed).hasSize(1);
        assertThat(resultsForDemoTypeAndProposedForOxf).hasSize(1);
        assertThat(resultsForDemoType.get(0)).isEqualTo(leaseAmendment);
        assertThat(resultsForDemoTypeAndSigned).isEmpty();
        assertThat(resultsForDemoTypeAndProposedForRon).isEmpty();
        assertThat(resultsForOtherType).isEmpty();

        // and when
        final LeaseAmendmentState adaptedState = LeaseAmendmentState.SIGNED;
        final LocalDate adaptedStartDate = new LocalDate(2020, 1, 16);
        final LocalDate adaptedEndDate = new LocalDate(2020, 4, 1);
        leaseAmendment = leaseAmendmentRepository.upsert(lease, LeaseAmendmentTemplate.DEMO_TYPE,
                adaptedState, adaptedStartDate, adaptedEndDate);
        // then
        assertThat(leaseAmendment.getState()).isEqualTo(adaptedState);
        assertThat(leaseAmendment.getStartDate()).isEqualTo(adaptedStartDate);
        assertThat(leaseAmendment.getEndDate()).isEqualTo(adaptedEndDate);

    }

    @Inject
    LeaseAmendmentRepository leaseAmendmentRepository;
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.network.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Describes the connection monitor endpoint. */
@Fluent
public final class ConnectionMonitorEndpoint {
    /*
     * The name of the connection monitor endpoint.
     */
    @JsonProperty(value = "name", required = true)
    private String name;

    /*
     * The endpoint type.
     */
    @JsonProperty(value = "type")
    private EndpointType type;

    /*
     * Resource ID of the connection monitor endpoint.
     */
    @JsonProperty(value = "resourceId")
    private String resourceId;

    /*
     * Address of the connection monitor endpoint (IP or domain name).
     */
    @JsonProperty(value = "address")
    private String address;

    /*
     * Filter for sub-items within the endpoint.
     */
    @JsonProperty(value = "filter")
    private ConnectionMonitorEndpointFilter filter;

    /*
     * Endpoint scope.
     */
    @JsonProperty(value = "scope")
    private ConnectionMonitorEndpointScope scope;

    /*
     * Test coverage for the endpoint.
     */
    @JsonProperty(value = "coverageLevel")
    private CoverageLevel coverageLevel;

    /** Creates an instance of ConnectionMonitorEndpoint class. */
    public ConnectionMonitorEndpoint() {
    }

    /**
     * Get the name property: The name of the connection monitor endpoint.
     *
     * @return the name value.
     */
    public String name() {
        return this.name;
    }

    /**
     * Set the name property: The name of the connection monitor endpoint.
     *
     * @param name the name value to set.
     * @return the ConnectionMonitorEndpoint object itself.
     */
    public ConnectionMonitorEndpoint withName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Get the type property: The endpoint type.
     *
     * @return the type value.
     */
    public EndpointType type() {
        return this.type;
    }

    /**
     * Set the type property: The endpoint type.
     *
     * @param type the type value to set.
     * @return the ConnectionMonitorEndpoint object itself.
     */
    public ConnectionMonitorEndpoint withType(EndpointType type) {
        this.type = type;
        return this;
    }

    /**
     * Get the resourceId property: Resource ID of the connection monitor endpoint.
     *
     * @return the resourceId value.
     */
    public String resourceId() {
        return this.resourceId;
    }

    /**
     * Set the resourceId property: Resource ID of the connection monitor endpoint.
     *
     * @param resourceId the resourceId value to set.
     * @return the ConnectionMonitorEndpoint object itself.
     */
    public ConnectionMonitorEndpoint withResourceId(String resourceId) {
        this.resourceId = resourceId;
        return this;
    }

    /**
     * Get the address property: Address of the connection monitor endpoint (IP or domain name).
     *
     * @return the address value.
     */
    public String address() {
        return this.address;
    }

    /**
     * Set the address property: Address of the connection monitor endpoint (IP or domain name).
     *
     * @param address the address value to set.
     * @return the ConnectionMonitorEndpoint object itself.
     */
    public ConnectionMonitorEndpoint withAddress(String address) {
        this.address = address;
        return this;
    }

    /**
     * Get the filter property: Filter for sub-items within the endpoint.
     *
     * @return the filter value.
     */
    public ConnectionMonitorEndpointFilter filter() {
        return this.filter;
    }

    /**
     * Set the filter property: Filter for sub-items within the endpoint.
     *
     * @param filter the filter value to set.
     * @return the ConnectionMonitorEndpoint object itself.
     */
    public ConnectionMonitorEndpoint withFilter(ConnectionMonitorEndpointFilter filter) {
        this.filter = filter;
        return this;
    }

    /**
     * Get the scope property: Endpoint scope.
     *
     * @return the scope value.
     */
    public ConnectionMonitorEndpointScope scope() {
        return this.scope;
    }

    /**
     * Set the scope property: Endpoint scope.
     *
     * @param scope the scope value to set.
     * @return the ConnectionMonitorEndpoint object itself.
     */
    public ConnectionMonitorEndpoint withScope(ConnectionMonitorEndpointScope scope) {
        this.scope = scope;
        return this;
    }

    /**
     * Get the coverageLevel property: Test coverage for the endpoint.
     *
     * @return the coverageLevel value.
     */
    public CoverageLevel coverageLevel() {
        return this.coverageLevel;
    }

    /**
     * Set the coverageLevel property: Test coverage for the endpoint.
     *
     * @param coverageLevel the coverageLevel value to set.
     * @return the ConnectionMonitorEndpoint object itself.
     */
    public ConnectionMonitorEndpoint withCoverageLevel(CoverageLevel coverageLevel) {
        this.coverageLevel = coverageLevel;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (name() == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException("Missing required property name in model ConnectionMonitorEndpoint"));
        }
        if (filter() != null) {
            filter().validate();
        }
        if (scope() != null) {
            scope().validate();
        }
    }

    private static final ClientLogger LOGGER = new ClientLogger(ConnectionMonitorEndpoint.class);
}


text:
FROM node:4
ENV npm_config_spin=false npm_config_loglevel=http
RUN apt-get update && apt-get install libkrb5-dev
RUN npm cache clean && npm install -g grunt-cli gulp node-pre-gyp node-gyp node-inspector pm2 rimraf
EXPOSE 8080
CMD ["bash"]


text:
package org.apache.activemq.artemis.core.postoffice.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

public final class AddressPartNode<T> {

   protected final String ANY_CHILD;
   protected final String ANY_DESCENDENT;

   private final AddressPartNode<T> parent;
   private final List<T> values = new CopyOnWriteArrayList<>();
   private final Map<String, AddressPartNode<T>> childNodes = new ConcurrentHashMap<>();
   private final String path;

   public AddressPartNode(final String path, final AddressPartNode<T> parent) {
      this.parent = parent;
      this.ANY_DESCENDENT = parent.ANY_DESCENDENT;
      this.ANY_CHILD = parent.ANY_CHILD;

      // allow '==' equality wildcard nodes
      if (ANY_DESCENDENT.equals(path)) {
         this.path = ANY_DESCENDENT;
      } else if (ANY_CHILD.equals(path)) {
         this.path = ANY_CHILD;
      } else {
         this.path = path;
      }
   }

   public AddressPartNode(String anyDescendent, String anyChild) {
      ANY_DESCENDENT = anyDescendent;
      ANY_CHILD = anyChild;
      path = "Root";
      parent = null;
   }

   public AddressPartNode<T> getChild(final String path) {
      return childNodes.get(path);
   }

   public Collection<AddressPartNode<T>> getChildren() {
      return childNodes.values();
   }

   public AddressPartNode<T> getChildOrCreate(final String path) {
      AddressPartNode<T> answer = childNodes.get(path);
      if (answer == null) {
         answer = new AddressPartNode<>(path, this);
         childNodes.put(path, answer);
      }
      return answer;
   }

   public void add(final String[] paths, final int idx, final T value) {
      if (idx >= paths.length) {
         values.add(value);
      } else {
         getChildOrCreate(paths[idx]).add(paths, idx + 1, value);
      }
   }

   public void remove(final String[] paths, final int idx, final T value) {
      if (idx >= paths.length) {
         values.remove(value);
         pruneIfEmpty();
      } else {
         getChildOrCreate(paths[idx]).remove(paths, idx + 1, value);
      }
   }

   public void visitDescendantNonWildcardValues(final AddressMapVisitor<T> collector) throws Exception {
      visitValues(collector);
      for (AddressPartNode<T> child : childNodes.values()) {
         if (ANY_CHILD == child.getPath() || ANY_DESCENDENT == child.getPath()) {
            continue;
         }
         child.visitDescendantNonWildcardValues(collector);
      }
   }

   public void visitPathTailNonWildcard(final String[] paths,
                                  final int startIndex,
                                  final AddressMapVisitor<T> collector) throws Exception {

      if (childNodes.isEmpty()) {
         return;
      }

      // look for a path match after 0-N skips among children
      AddressPartNode<T> match = null;
      for (int i = startIndex; i < paths.length; i++) {
         match = getChild(paths[i]);
         if (match != null) {
            if (ANY_CHILD == match.getPath() || ANY_DESCENDENT == match.getPath()) {
               continue;
            }
            match.visitNonWildcard(paths, i + 1, collector);
            break;
         }
      }

      // walk the rest of the sub tree to find a tail path match
      for (AddressPartNode<T> child : childNodes.values()) {
         // instance equality arranged in node creation getChildOrCreate
         if (child != match && ANY_DESCENDENT != child.getPath() && ANY_CHILD != child.getPath()) {

            child.visitPathTailNonWildcard(paths, startIndex, collector);
         }
      }
   }

   public void visitPathTailMatch(final String[] paths, final int startIndex, final AddressMapVisitor<T> collector) throws Exception {

      if (childNodes.isEmpty()) {
         return;
      }

      // look for a path match after 0-N skips among immediate children
      ArrayList<AddressPartNode> visitedSet = new ArrayList<>(paths.length);
      for (int i = startIndex; i < paths.length; i++) {
         final AddressPartNode<T> match = getChild(paths[i]);
         if (match != null) {
            match.visitMatchingWildcards(paths, i + 1, collector);
            visitedSet.add(match);
         }
      }

      // walk the rest of the sub tree to find a tail path match
      for (AddressPartNode<T> child : childNodes.values()) {
         if (alreadyVisited(child, visitedSet)) {
            continue;
         }
         child.visitPathTailMatch(paths, startIndex, collector);
      }
   }

   private boolean alreadyVisited(final AddressPartNode<T> child, final ArrayList<AddressPartNode> matches) {
      if (!matches.isEmpty()) {
         for (AddressPartNode alreadyMatched : matches) {
            if (child == alreadyMatched) {
               return true;
            }
         }
      }
      return false;
   }

   // wildcards in the paths, ignore wildcard expansions in the map
   public void visitNonWildcard(final String[] paths, final int startIndex, final AddressMapVisitor<T> collector) throws Exception {
      boolean canVisitAnyDescendent = true;
      AddressPartNode<T> node = this;
      final int size = paths.length;
      for (int i = startIndex; i < size && node != null; i++) {

         final String path = paths[i];

         // snuff out any descendant postfix in the paths ....#
         if (ANY_DESCENDENT.equals(path)) {
            if (i == size - 1) {
               node.visitDescendantNonWildcardValues(collector);
               canVisitAnyDescendent = false;
               break;
            }
         }

         if (ANY_CHILD.equals(path)) {

            for (AddressPartNode<T> anyChild : node.getChildren()) {

               if (ANY_CHILD == anyChild.getPath() || ANY_DESCENDENT == anyChild.getPath()) {
                  continue;
               }

               anyChild.visitNonWildcard(paths, i + 1, collector);

            }
            // once we have done depth first on all children we are done with our paths
            return;

         } else if (ANY_DESCENDENT.equals(path)) {

            node.visitValues(collector);
            node.visitPathTailNonWildcard(paths, i + 1, collector);
            // once we have done depth first on all children we are done with our paths
            return;

         } else {

            node = node.getChild(path);

         }
      }
      if (node != null) {

         if (canVisitAnyDescendent) {

            node.visitValues(collector);

         }
      }
   }

   // non wildcard paths, match any expanded wildcards in the map
   public void visitMatchingWildcards(final String[] paths, final int startIndex, final AddressMapVisitor<T> collector) throws Exception {
      boolean canVisitAnyDescendent = true;
      AddressPartNode<T> node = this;
      AddressPartNode<T> anyDescendentNode = null;
      AddressPartNode<T> anyChildNode = null;
      final int size = paths.length;
      for (int i = startIndex; i < size && node != null; i++) {

         final String path = paths[i];

         anyDescendentNode = node.getChild(ANY_DESCENDENT);
         if (anyDescendentNode != null) {

            anyDescendentNode.visitValues(collector);
            // match tail with current path, such that ANY_DESCENDENT can match zero
            anyDescendentNode.visitPathTailMatch(paths, i, collector);
            canVisitAnyDescendent = false;
         }

         anyChildNode = node.getChild(ANY_CHILD);
         if (anyChildNode != null) {
            anyChildNode.visitMatchingWildcards(paths, i + 1, collector);
         }

         node = node.getChild(path);

         if (node != null && (node == anyChildNode || node == anyDescendentNode)) {
            // down that path before, out of here
            return;
         }

      }
      if (node != null) {

         node.visitValues(collector);

         if (canVisitAnyDescendent) {

            // allow zero node any descendant at the end of path node
            anyDescendentNode = node.getChild(ANY_DESCENDENT);
            if (anyDescendentNode != null) {
               anyDescendentNode.visitValues(collector);
            }
         }
      }
   }

   public void visitValues(final AddressMapVisitor<T> collector) throws Exception {
      for (T o : values) {
         collector.visit(o);
      }
   }

   public String getPath() {
      return path;
   }

   protected void pruneIfEmpty() {
      if (parent != null && childNodes.isEmpty() && values.isEmpty()) {
         parent.removeChild(this);
      }
   }

   protected void removeChild(final AddressPartNode<T> node) {
      childNodes.remove(node.getPath());
      pruneIfEmpty();
   }

   public void reset() {
      values.clear();
      childNodes.clear();
   }
}


text:
package eleme.openapi.sdk.api.service;

import eleme.openapi.sdk.api.annotation.Service;
import eleme.openapi.sdk.api.base.BaseNopService;
import eleme.openapi.sdk.api.exception.ServiceException;
import eleme.openapi.sdk.oauth.response.Token;
import eleme.openapi.sdk.config.Config;
import eleme.openapi.sdk.api.entity.shop.*;
import eleme.openapi.sdk.api.enumeration.shop.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;

/**
 * 店铺服务
 */
@Service("eleme.shop")
public class ShopService extends BaseNopService {
    public ShopService(Config config,Token token) {
        super(config, token, ShopService.class);
    }

    /**
     * 查询店铺信息
     *
     * @param shopId 店铺Id
     * @return 店铺
     * @throws ServiceException 服务异常
     */
    public OShop getShop(long shopId) throws ServiceException {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("shopId", shopId);
        return call("eleme.shop.getShop", params);
    }

    /**
     * 更新店铺基本信息
     *
     * @param shopId 店铺Id
     * @param properties 店铺属性
     * @return 店铺
     * @throws ServiceException 服务异常
     */
    public OShop updateShop(long shopId, Map<OShopProperty,Object> properties) throws ServiceException {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("shopId", shopId);
        params.put("properties", properties);
        return call("eleme.shop.updateShop", params);
    }

    /**
     * 批量获取店铺简要
     *
     * @param shopIds 店铺Id的列表
     * @return 店铺简要列表
     * @throws ServiceException 服务异常
     */
    public Map<Long,OSimpleShop> mgetShopStatus(List<Long> shopIds) throws ServiceException {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("shopIds", shopIds);
        return call("eleme.shop.mgetShopStatus", params);
    }

    /**
     * 设置送达时间
     *
     * @param shopId 店铺Id
     * @param deliveryBasicMins 配送基准时间(单位分钟)
     * @param deliveryAdjustMins 配送调整时间(单位分钟)
     * @throws ServiceException 服务异常
     */
    public void setDeliveryTime(long shopId, int deliveryBasicMins, int deliveryAdjustMins) throws ServiceException {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("shopId", shopId);
        params.put("deliveryBasicMins", deliveryBasicMins);
        params.put("deliveryAdjustMins", deliveryAdjustMins);
        call("eleme.shop.setDeliveryTime", params);
    }

    /**
     * 设置是否支持在线退单
     *
     * @param shopId 店铺Id
     * @param enable 是否支持
     * @throws ServiceException 服务异常
     */
    public void setOnlineRefund(long shopId, boolean enable) throws ServiceException {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("shopId", shopId);
        params.put("enable", enable);
        call("eleme.shop.setOnlineRefund", params);
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <meta name="viewport" content="width=device-width,initial-scale=1">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="lang:clipboard.copy" content="Copy to clipboard">
  <meta name="lang:clipboard.copied" content="Copied to clipboard">
  <meta name="lang:search.language" content="en">
  <meta name="lang:search.pipeline.stopwords" content="True">
  <meta name="lang:search.pipeline.trimmer" content="True">
  <meta name="lang:search.result.none" content="No matching documents">
  <meta name="lang:search.result.one" content="1 matching document">
  <meta name="lang:search.result.other" content="# matching documents">
  <meta name="lang:search.tokenizer" content="[\s\-]+">

    <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
    <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">

  <link rel="stylesheet" href="../../../../_static/stylesheets/application.css"/>
  <link rel="stylesheet" href="../../../../_static/stylesheets/application-palette.css"/>
  <link rel="stylesheet" href="../../../../_static/stylesheets/application-fixes.css"/>

  <link rel="stylesheet" href="../../../../_static/fonts/material-icons.css"/>

  <meta name="theme-color" content="#3f51b5">

    <title>statsmodels.genmod.families.varfuncs — statsmodels</title>
  <link rel="icon" type="image/png" sizes="32x32" href="../../../../_static/icons/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="../../../../_static/icons/favicon-16x16.png">
  <link rel="manifest" href="../../../../_static/icons/site.webmanifest">
  <link rel="mask-icon" href="../../../../_static/icons/safari-pinned-tab.svg" color="#919191">
  <meta name="msapplication-TileColor" content="#2b5797">
  <meta name="msapplication-config" content="../../../../_static/icons/browserconfig.xml">
  <link rel="stylesheet" href="../../../../_static/stylesheets/examples.css">
  <link rel="stylesheet" href="../../../../_static/stylesheets/deprecation.css">
    <link rel="stylesheet" type="text/css" href="../../../../_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../../../../_static/material.css" />
    <link rel="stylesheet" type="text/css" href="../../../../_static/graphviz.css" />
    <link rel="stylesheet" type="text/css" href="../../../../_static/plot_directive.css" />

    <link rel="shortcut icon" href="../../../../_static/favicon.ico"/>
    <link rel="author" title="About these documents" href="../../../../about.html" />
    <link rel="index" title="Index" href="../../../../genindex.html" />
    <link rel="search" title="Search" href="../../../../search.html" />

  <svg class="md-svg">
    <defs data-children-count="0">

      <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>

    </defs>
  </svg>

  <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
  <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">

   Skip to content

          statsmodels 0.13.3
           statsmodels.genmod.families.varfuncs

    <form class="md-search__form" action="../../../../search.html" method="get" name="search">
      <input type="text" class="md-search__input" name="q" placeholder="Search"
             autocapitalize="off" autocomplete="off" spellcheck="false"
             data-md-component="query" data-md-state="active">

      <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">
        
      </button>
    </form>

            Type to start searching

      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
        <use xlink:href="#__github" width="24" height="24"></use>
      </svg>

    statsmodels

Module code

    statsmodels 0.13.3

      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
        <use xlink:href="#__github" width="24" height="24"></use>
      </svg>

    statsmodels

      Installing statsmodels

      Getting started

      User Guide

      Examples

      API Reference

      About statsmodels

      Developer Page

      Release Notes

Source code for statsmodels.genmod.families.varfuncs

"""
Variance functions for use with the link functions in statsmodels.family.links
"""
import numpy as np
FLOAT_EPS = np.finfo(float).eps

[docs]class VarianceFunction(object):
    """
    Relates the variance of a random variable to its mean. Defaults to 1.

    Methods
    -------
    call
        Returns an array of ones that is the same shape as `mu`

    Notes
    -----
    After a variance function is initialized, its call method can be used.

    Alias for VarianceFunction:
    constant = VarianceFunction()

    See Also
    --------
    statsmodels.genmod.families.family
    """

    def __call__(self, mu):
        """
        Default variance function

        Parameters
        ----------
        mu : array_like
            mean parameters

        Returns
        -------
        v : ndarray
            ones(mu.shape)
        """
        mu = np.asarray(mu)
        return np.ones(mu.shape, np.float64)

[docs]    def deriv(self, mu):
        """
        Derivative of the variance function v'(mu)
        """
        return np.zeros_like(mu)

constant = VarianceFunction()
constant.__doc__ = """
The call method of constant returns a constant variance, i.e., a vector of
ones.

constant is an alias of VarianceFunction()
"""

[docs]class Power(object):
    """
    Power variance function

    Parameters
    ----------
    power : float
        exponent used in power variance function

    Methods
    -------
    call
        Returns the power variance

    Notes
    -----
    Formulas
       V(mu) = numpy.fabs(mu)**power

    Aliases for Power:
    mu = Power()
    mu_squared = Power(power=2)
    mu_cubed = Power(power=3)
    """

    def __init__(self, power=1.):
        self.power = power

    def __call__(self, mu):
        """
        Power variance function

        Parameters
        ----------
        mu : array_like
            mean parameters

        Returns
        -------
        variance : ndarray
            numpy.fabs(mu)**self.power
        """
        return np.power(np.fabs(mu), self.power)

[docs]    def deriv(self, mu):
        """
        Derivative of the variance function v'(mu)

        May be undefined at zero.
        """

        der = self.power * np.fabs(mu) ** (self.power - 1)
        ii = np.flatnonzero(mu < 0)
        der[ii] *= -1
        return der

mu = Power()
mu.__doc__ = """
Returns np.fabs(mu)

Notes
-----
This is an alias of Power()
"""
mu_squared = Power(power=2)
mu_squared.__doc__ = """
Returns np.fabs(mu)**2

Notes
-----
This is an alias of statsmodels.family.links.Power(power=2)
"""
mu_cubed = Power(power=3)
mu_cubed.__doc__ = """
Returns np.fabs(mu)**3

Notes
-----
This is an alias of statsmodels.family.links.Power(power=3)
"""

[docs]class Binomial(object):
    """
    Binomial variance function

    Parameters
    ----------
    n : int, optional
        The number of trials for a binomial variable.  The default is 1 for
        p in (0,1)

    Methods
    -------
    call
        Returns the binomial variance

    Notes
    -----
    Formulas :

       V(mu) = p * (1 - p) * n

    where p = mu / n

    Alias for Binomial:
    binary = Binomial()

    A private method _clean trims the data by machine epsilon so that p is
    in (0,1)
    """

    def __init__(self, n=1):
        self.n = n

    def _clean(self, p):
        return np.clip(p, FLOAT_EPS, 1 - FLOAT_EPS)

    def __call__(self, mu):
        """
        Binomial variance function

        Parameters
        ----------
        mu : array_like
            mean parameters

        Returns
        -------
        variance : ndarray
           variance = mu/n * (1 - mu/n) * self.n
        """
        p = self._clean(mu / self.n)
        return p * (1 - p) * self.n

    # TODO: inherit from super

[docs]    def deriv(self, mu):
        """
        Derivative of the variance function v'(mu)
        """
        return 1 - 2*mu

binary = Binomial()
binary.__doc__ = """
The binomial variance function for n = 1

Notes
-----
This is an alias of Binomial(n=1)
"""

[docs]class NegativeBinomial(object):
    '''
    Negative binomial variance function

    Parameters
    ----------
    alpha : float
        The ancillary parameter for the negative binomial variance function.
        `alpha` is assumed to be nonstochastic.  The default is 1.

    Methods
    -------
    call
        Returns the negative binomial variance

    Notes
    -----
    Formulas :

       V(mu) = mu + alpha*mu**2

    Alias for NegativeBinomial:
    nbinom = NegativeBinomial()

    A private method _clean trims the data by machine epsilon so that p is
    in (0,inf)
    '''

    def __init__(self, alpha=1.):
        self.alpha = alpha

    def _clean(self, p):
        return np.clip(p, FLOAT_EPS, np.inf)

    def __call__(self, mu):
        """
        Negative binomial variance function

        Parameters
        ----------
        mu : array_like
            mean parameters

        Returns
        -------
        variance : ndarray
            variance = mu + alpha*mu**2
        """
        p = self._clean(mu)
        return p + self.alpha*p**2

[docs]    def deriv(self, mu):
        """
        Derivative of the negative binomial variance function.
        """

        p = self._clean(mu)
        return 1 + 2 * self.alpha * p

nbinom = NegativeBinomial()
nbinom.__doc__ = """
Negative Binomial variance function.

Notes
-----
This is an alias of NegativeBinomial(alpha=1.)
"""

              © Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.

            Last updated on
              Nov 01, 2022.

            Created using
            Sphinx 5.3.0.
             and
            Material for
              Sphinx


text:
<!DOCTYPE html>

        <title>2. Music Catalog</title>
        <link href="styles/styles.css" rel="stylesheet" />

Music Categories

Even more websites all about website templates on Just Web Templates.

                    Listen
                    Add

If you're looking for beautiful and professionally made templates you can find them at Template Beauty.

                    Listen
                    Add

You can remove any link to our websites from this template you're free to use the template without linking back to us.

                    Listen
                    Add


text:
describe("ImportInfoSync", function() {

  var view;

  beforeEach(function() {
    view = new cdb.admin.ImportInfo.Sync();
  });

  it("should generate period combo", function() {
    expect(_.size(view._subviews)).toBe(1);
    expect(view.$('.period')).toBeDefined();
  });

  it("should change period if combo changes", function() {
    var called = false;
    view.bind('periodChange', function() {
      called = true;
    })
    view.$("select").val(["Every day", (60*60*24)]).trigger("change");
    expect(called).toBeTruthy()
  });

});


text:
function [C, sigma] = dataset3Params(X, y, Xval, yval)
%EX6PARAMS returns your choice of C and sigma for Part 3 of the exercise
%where you select the optimal (C, sigma) learning parameters to use for SVM
%with RBF kernel
%   [C, sigma] = EX6PARAMS(X, y, Xval, yval) returns your choice of C and
%   sigma. You should complete this function to return the optimal C and
%   sigma based on a cross-validation set.
%

% You need to return the following variables correctly.
C = 1;
sigma = 0.3;

% ====================== YOUR CODE HERE ======================
% Instructions: Fill in this function to return the optimal C and sigma
%               learning parameters found using the cross validation set.
%               You can use svmPredict to predict the labels on the cross
%               validation set. For example,
%                   predictions = svmPredict(model, Xval);
%               will return the predictions on the cross validation set.
%
%  Note: You can compute the prediction error using
%        mean(double(predictions ~= yval))
%

variants = [0.01, 0.03, 0.1, 0.3, 1, 3, 10, 30];
m = length(variants);
track = zeros(m, m);

for C_i = 1:m
  C_ = variants(C_i);
  for sigma_i = 1:m
    sigma_ = variants(sigma_i);
    % calc
    model= svmTrain(X, y, C_, @(x1, x2) gaussianKernel(x1, x2, sigma_));

    % checking
    predictions = svmPredict(model, Xval);
    err = mean(double(predictions ~= yval));

    % store
    track(C_i, sigma_i) = err;
  end
end
[x, y, v] = find(track == min(track(:)));

C = variants(x(1));
sigma = variants(y(1));

% =========================================================================

end


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Shouldly
{
    public static class TypeAssertExtensions
    {
        public static void ShouldBySameTypeAs<T>(this object instance, T their)
        {
            if (instance == null && their == null)
            {
                return;
            }

            if (instance == null)
            {
                Assert.Fail("Instance is null.");
            }

            if (their == null)
            {
                Assert.Fail("Their is null.");
            }

            if (instance.GetType() != their.GetType())
            {
                Assert.Fail($"Instance type '{instance.GetType().FullName}' is not equal type of their '{their.GetType().FullName}'");
            }
        }

        public static void ShouldNotBySameTypeAs<T>(this object instance, T their)
        {
            if (instance == null && their == null)
            {
                Assert.Fail("Instance and theri is both null.");
            }

            if (instance == null || their == null)
            {
                return;
            }

            if (instance.GetType() == their.GetType())
            {
                Assert.Fail($"Instance and their is same type '{instance.GetType().FullName}'.");
            }
        }
    }
}


text:
package br.unicamp.ic.sed.mobilemedia.mainuimidlet_album.impl;

import br.unicamp.ic.sed.mobilemedia.mainuimidlet_album.impl.IManager;

public class ComponentFactory {

	private static IManager manager = null;

	public static IManager createInstance(){// System.out.println("ComponentFactory.createInstance()");

		if (manager==null)
			manager = new Manager();

		return manager;
	}
}


text:
from importlib import import_module
import pytest
import re

from django.conf import settings
from django.test.utils import override_settings
from django.contrib.sessions.middleware import SessionMiddleware
from django.contrib.sessions.models import Session
from django.contrib.auth import SESSION_KEY
from unittest import mock

from awx.api.versioning import reverse

class AlwaysPassBackend(object):

    user = None

    def authenticate(self, **credentials):
        return AlwaysPassBackend.user

    @classmethod
    def get_backend_path(cls):
        return '{}.{}'.format(cls.__module__, cls.__name__)

@pytest.mark.django_db
@pytest.mark.parametrize('accept, status', [
    ['*/*', 200],
    ['text/html', 200],
    ['application/json', 406]
])
def test_login_json_not_allowed(get, accept, status):
    get(
        '/api/login/',
        HTTP_ACCEPT=accept,
        expect=status
    )

@pytest.mark.skip(reason="Needs Update - CA")
@pytest.mark.django_db
def test_session_create_delete(admin, post, get):
    AlwaysPassBackend.user = admin
    with override_settings(
        AUTHENTICATION_BACKENDS=(AlwaysPassBackend.get_backend_path(),),
        SESSION_COOKIE_NAME='session_id'
    ):
        response = post(
            '/api/login/',
            data={'username': admin.username, 'password': admin.password, 'next': '/api/'},
            expect=302, middleware=SessionMiddleware(), format='multipart'
        )
        assert 'session_id' in response.cookies
        session_key = re.findall(r'session_id=[a-zA-z0-9]+',
                                 str(response.cookies['session_id']))[0][len('session_id=') :]
        session = Session.objects.get(session_key=session_key)
        assert int(session.get_decoded()[SESSION_KEY]) == admin.pk
        response = get(
            '/api/logout/', middleware=SessionMiddleware(),
            cookies={'session_id': session_key}, expect=302
        )
        assert not Session.objects.filter(session_key=session_key).exists()

@pytest.mark.django_db
@mock.patch('awx.main.consumers.emit_channel_notification')
def test_sessions_unlimited(emit, admin):
    assert Session.objects.count() == 0
    for i in range(5):
        store = import_module(settings.SESSION_ENGINE).SessionStore()
        store.create_model_instance({SESSION_KEY: admin.pk}).save()
        assert Session.objects.count() == i + 1
    assert emit.call_count == 0

@pytest.mark.django_db
@mock.patch('awx.main.consumers.emit_channel_notification')
def test_session_overlimit(emit, admin, alice):
    # If SESSIONS_PER_USER=3, only persist the three most recently created sessions
    assert Session.objects.count() == 0
    with override_settings(SESSIONS_PER_USER=3):
        created = []
        for i in range(5):
            store = import_module(settings.SESSION_ENGINE).SessionStore()
            session = store.create_model_instance({SESSION_KEY: admin.pk})
            session.save()
            created.append(session.session_key)
    assert [s.pk for s in Session.objects.all()] == created[-3:]
    assert emit.call_count == 2  # 2 of 5 sessions were evicted
    emit.assert_called_with(
        'control-limit_reached_{}'.format(admin.pk),
        {'reason': 'limit_reached', 'group_name': 'control'}
    )

    # Allow sessions for a different user to be saved
    store = import_module(settings.SESSION_ENGINE).SessionStore()
    store.create_model_instance({SESSION_KEY: alice.pk}).save()
    assert Session.objects.count() == 4

@pytest.mark.skip(reason="Needs Update - CA")
@pytest.mark.django_db
def test_password_update_clears_sessions(admin, alice, post, patch):
    AlwaysPassBackend.user = alice
    with override_settings(
        AUTHENTICATION_BACKENDS=(AlwaysPassBackend.get_backend_path(),),
        SESSION_COOKIE_NAME='session_id'
    ):
        response = post(
            '/api/login/',
            data={'username': alice.username, 'password': alice.password, 'next': '/api/'},
            expect=302, middleware=SessionMiddleware(), format='multipart'
        )
        session_key = re.findall(
            r'session_id=[a-zA-z0-9]+',
            str(response.cookies['session_id'])
        )[0][len('session_id=') :]
        assert Session.objects.filter(session_key=session_key).exists()
        patch(
            reverse('api:user_detail', kwargs={'pk': alice.pk}), admin,
            data={'password': 'new_password'}, expect=200
        )
        assert not Session.objects.filter(session_key=session_key).exists()


text:
/*                                                                      *\
** Squants                                                              **
**                                                                      **
** Scala Quantities and Units of Measure Library and DSL                **
** (c) 2013-2015, Gary Keorkunian                                       **
**                                                                      **
\*                                                                      */

package squants

import squants.space.AngleUnit

/**
 * Root trait for representing Vectors
 *
 * @author garyKeorkunian
 * @since 0.3.0
 *
 * @tparam A Type for the Vector's coordinate values
 */
trait SVector[A] {

  type SVectorType <: SVector[A]

  /**
   * The list of values that makeup the Vector's Cartesian coordinates
   * @return
   */
  def coordinates: Seq[A]

  /**
   * The scalar value of the Vector
   * @return
   */
  def magnitude: A

  /**
   * The angle between the two Cartesian coordinates at the supplied indices
   * @param coordinateX index of the abscissa coordinate (defaults to 0)
   * @param coordinateY index of the ordinate coordinate (defaults to 1)
   * @param unit unit for the angle (theta) component (defaults to Radians)
   * @return Angle
   */
  def angle(coordinateX: Int = 0, coordinateY: Int = 1, unit: AngleUnit = Radians): Angle

  /**
   * The polar coordinates (r, theta) of the two Cartesian coordinates at the supplied indices
   * @param coordinateX index of the abscissa coordinate (defaults to 0)
   * @param coordinateY index of the ordinate coordinate (defaults to 1)
   * @param unit unit for the angle (theta) component (defaults to Radians)
   * @return (A, Angle)
   */
  def polar(coordinateX: Int = 0, coordinateY: Int = 1, unit: AngleUnit = Radians): (A, Angle) = (magnitude, angle(coordinateX, coordinateY, unit))

  /**
   * Creates the Unit Vector which corresponds to this vector
   * @return
   */
  def normalize: SVectorType

  /**
   * Add two Vectors
   * @param that Vector[A]
   * @return
   */
  def plus(that: SVectorType): SVectorType
  def + = plus _

  /**
   * Subtract two Vectors
   * @param that Vector[A]
   * @return
   */
  def minus(that: SVectorType): SVectorType
  def - = minus _

  /**
   * Scale a Vector
   * @param that Double
   * @return
   */
  def times(that: Double): SVectorType
  def * = times _

  /**
   * Reduce a Vector
   *
   * @param that Double
   * @return
   */
  def divide(that: Double): SVectorType
  def /(that: Double) = divide(that)

  /**
   * Create the Dot Product of two Vectors
   * @param that Double
   * @return
   */
  def dotProduct(that: DoubleVector): A
  def *(that: DoubleVector) = dotProduct(that)

  /**
   * Create the Cross Product of two Vectors
   * @param that Vector[A]
   * @return
   */
  def crossProduct(that: DoubleVector): SVector[A]
  def #* = crossProduct _

}

object SVector {

  def apply(coordinates: Double*): DoubleVector = DoubleVector(coordinates: _*)
  def apply[A <: Quantity[A]](coordinates: A*): QuantityVector[A] = QuantityVector[A](coordinates: _*)

  /**
   * Create a 2-dimensional DoubleVector from Polar Coordinates
   * @param radius the magnitude of the vector
   * @param theta the angle from the polar axis
   * @return
   */
  def apply(radius: Double, theta: Angle): DoubleVector = apply(radius * theta.cos, radius * theta.sin)

  /**
   * Create a 2-dimensional QuantityVector[A] from Polar Coordinates
   * @param radius the magnitude of the vector
   * @param theta the angle from the polar axis
   * @tparam A Quantity type
   * @return
   */
  def apply[A <: Quantity[A]](radius: A, theta: Angle): QuantityVector[A] = apply(radius * theta.cos, radius * theta.sin)
}

/**
 * Double (Real Number) Vector
 *
 * @author garyKeorkunian
 * @since 0.3.0
 *
 * @param coordinates Double*
 */
case class DoubleVector(coordinates: Double*) extends SVector[Double] {

  type SVectorType = DoubleVector

  def magnitude: Double = math.sqrt(coordinates.toTraversable.map(v ⇒ v * v).sum)
  def angle(coordinateX: Int = 0, coordinateY: Int = 1, unit: AngleUnit = Radians): Angle =
    Radians(math.atan2(coordinates(coordinateY), coordinates(coordinateX))) in unit

  def normalize: SVectorType = this.divide(magnitude)

  /**
   * Creates a DoubleVector by mapping over each coordinate with the supplied function
   * @param f A => Double map function
   * @return
   */
  def map[A <: Double](f: Double ⇒ Double): DoubleVector = DoubleVector(coordinates.toTraversable.map(f).toSeq: _*)

  /**
   * Creates a QuantityVector by mapping over each coordinate with the supplied function
   * @param f Double => B
   * @tparam A <: Quantity
   * @return
   */
  def map[A <: Quantity[A]](f: Double ⇒ A): QuantityVector[A] = QuantityVector(coordinates.toTraversable.map(f).toSeq: _*)

  def plus(that: SVectorType): SVectorType =
    DoubleVector(coordinates.toIterable.zipAll(that.coordinates.toIterable, 0d, 0d).toTraversable.map(v ⇒ v._1 + v._2).toSeq: _*)

  def minus(that: SVectorType): SVectorType =
    DoubleVector(coordinates.toIterable.zipAll(that.coordinates.toIterable, 0d, 0d).toTraversable.map(v ⇒ v._1 - v._2).toSeq: _*)

  def times(that: Double): SVectorType = map(_ * that)
  def times[A <: Quantity[A]](that: A): QuantityVector[A] = map(_ * that)

  def divide(that: Double): SVectorType = map(_ / that)

  def dotProduct(that: SVectorType): Double =
    coordinates.toIterable.zipAll(that.coordinates.toIterable, 0d, 0d).toTraversable.map(v ⇒ v._1 * v._2).sum

  def dotProduct[B <: Quantity[B]](that: QuantityVector[B]) = that dotProduct this

  def crossProduct(that: SVectorType) = (this.coordinates.length, that.coordinates.length) match {
    case (3, 3) ⇒
      DoubleVector(this.coordinates(1) * that.coordinates(2) - this.coordinates(2) * that.coordinates(1),
        coordinates(2) * that.coordinates(0) - this.coordinates(0) * that.coordinates(2),
        coordinates(0) * that.coordinates(1) - this.coordinates(1) * that.coordinates(0))
    case (7, 7) ⇒ throw new UnsupportedOperationException("Seven-dimensional cross product is not currently supported")
    case _      ⇒ throw new UnsupportedOperationException("Cross product is not supported on vectors with an arbitrary number of dimensions")
  }

  def crossProduct[B <: Quantity[B]](that: QuantityVector[B]) = that crossProduct this

}

/**
 * Quantity Vector
 *
 * @author garyKeorkunian
 * @since 0.3.0
 *
 * @param coordinates Variable list of A
 * @tparam A QuantityType
 */
case class QuantityVector[A <: Quantity[A]](coordinates: A*) extends SVector[A] {
  type SVectorType = QuantityVector[A]

  def valueUnit = coordinates(0).unit
  def magnitude: A = valueUnit(math.sqrt(coordinates.toTraversable.map(v ⇒ v.to(valueUnit) * v.to(valueUnit)).sum))
  def angle(coordinateX: Int = 0, coordinateY: Int = 1, unit: AngleUnit = Radians): Angle =
    Radians(math.atan(coordinates(coordinateY) / coordinates(coordinateX))) in unit

  def normalize: SVectorType = this / magnitude.to(valueUnit)

  /**
   * Creates the Unit Vector which corresponds to this vector using the given unit
   * @return
   */
  def normalize(unit: UnitOfMeasure[A]): SVectorType = this / magnitude.to(unit)

  /**
   * Creates a DoubleVector by mapping over each coordinate with the supplied function
   * @param f A => Double map function
   * @return
   */
  def map[B <: Double](f: A ⇒ Double): DoubleVector = DoubleVector(coordinates.toTraversable.map(f).toSeq: _*)

  /**
   * Creates a QuantityVector by mapping over each coordinate with the supplied function
   * @param f A => B
   * @tparam B <: Quantity
   * @return
   */
  def map[B <: Quantity[B]](f: A ⇒ B): QuantityVector[B] = QuantityVector(coordinates.toTraversable.map(f).toSeq: _*)

  def plus(that: SVectorType): SVectorType =
    QuantityVector(coordinates.toIterable.zipAll(that.coordinates.toIterable, valueUnit(0), valueUnit(0)).toTraversable.map(v ⇒ v._1 + v._2).toSeq: _*)
  def minus(that: SVectorType): SVectorType =
    QuantityVector(coordinates.toIterable.zipAll(that.coordinates.toIterable, valueUnit(0), valueUnit(0)).toTraversable.map(v ⇒ v._1 - v._2).toSeq: _*)

  def times(that: Double): SVectorType = map(_ * that)
  def *(that: Double): SVectorType = times(that)

  def times[B <: Quantity[B], C <: Quantity[C]](quantTimes: A ⇒ C): QuantityVector[C] = map(quantTimes)

  def divide(that: Double): SVectorType = map(_ / that)

  def divide(that: A): DoubleVector = map(_ / that)
  def /(that: A) = divide(that)

  def divide[B <: Quantity[B], C <: Quantity[C]](quantDiv: A ⇒ C): QuantityVector[C] = map(quantDiv(_))

  def dotProduct(that: DoubleVector): A =
    valueUnit(coordinates.toIterable.zipAll(that.coordinates.toIterable, valueUnit(0), 0d).toTraversable.map(v ⇒ v._1.to(valueUnit) * v._2).sum)

  def dotProduct[B <: Quantity[B], C <: Quantity[C]](that: SVector[B], quantTimes: (A, B) ⇒ C)(implicit num: Numeric[C]): C =
    coordinates.toIterable.zipAll(that.coordinates.toIterable, valueUnit(0), that.coordinates.head.unit(0)).toTraversable.map(v ⇒ quantTimes(v._1, v._2)).sum

  def crossProduct(that: DoubleVector): SVectorType = (this.coordinates.length, that.coordinates.length) match {
    case (3, 3) ⇒
      QuantityVector(
        (this.coordinates(1) * that.coordinates(2)) - (this.coordinates(2) * that.coordinates(1)),
        (this.coordinates(2) * that.coordinates(0)) - (this.coordinates(0) * that.coordinates(2)),
        (this.coordinates(0) * that.coordinates(1)) - (this.coordinates(1) * that.coordinates(0)))
    case (7, 7) ⇒ throw new UnsupportedOperationException("Seven-dimensional Cross Product is not currently supported")
    case _      ⇒ throw new UnsupportedOperationException("Cross Product is not supported on vectors with an arbitrary number of dimensions")
  }

  def crossProduct[B <: Quantity[B], C <: Quantity[C]](that: SVector[B], quantTimes: (A, B) ⇒ C)(implicit num: Numeric[C]): QuantityVector[C] = {
    (this.coordinates.length, that.coordinates.length) match {
      case (3, 3) ⇒
        QuantityVector(
          quantTimes(this.coordinates(1), that.coordinates(2)) - quantTimes(coordinates(2), that.coordinates(1)),
          quantTimes(this.coordinates(2), that.coordinates(0)) - quantTimes(coordinates(0), that.coordinates(2)),
          quantTimes(this.coordinates(0), that.coordinates(1)) - quantTimes(coordinates(1), that.coordinates(0)))
      case (7, 7) ⇒ throw new UnsupportedOperationException("Seven-dimensional Cross Product is not currently supported")
      case _      ⇒ throw new UnsupportedOperationException("Cross Product is not supported on vectors with an arbitrary number of dimensions")
    }
  }

  /**
   * Returns a DoubleVector representing the quantity values in terms of the supplied unit
   * @param uom UnitOfMeasure[A]
   * @return
   */
  def to(uom: UnitOfMeasure[A]): DoubleVector = this / uom(1)

  /**
   * Returns a QuantityVector with all coordinates set to the supplied unit
   * @param uom UnitOfMeasure[A]
   * @return
   */
  def in(uom: UnitOfMeasure[A]): QuantityVector[A] = map[A](_.in(uom))

}


text:
Solve it just for fun :)

quiz and explanation is located at http://tech.kakao.com/2017/09/27/kakao-blind-recruitment-round-1/


text:
describe('Array.prototypes', function(){
  var arr;
  beforeEach(function(){
    arr = [1,2,3]
  })
  describe('includes', function(){
    it('returns true if the array includes the argument', function(){
      expect(arr.includes(2)).toBe(true);
    });

    it('returns false if the array doesn\'t include the argument', function(){
      expect(arr.includes(4)).toBe(false);
    });
  })

  describe('clone', function(){
    it('returns a copy of the original array', function(){
      expect(arr.clone()).toEqual([1,2,3]);
    });

    it('doesn\'t return the same object', function(){
      expect(arr.clone()).not.toBe(arr);
    });

    it('cloned array is not affected by the modification of the original', function(){
      var clone = arr.clone();
      arr.push(4);
      expect(clone).not.toEqual(arr);
    })
  })

  describe('count', function(){
    it('returns 1 if the element occurs only once', function(){
      expect(arr.count(3)).toEqual(1);
    });

    it('returns 0 if the element doesn\t exist in the array', function(){
      expect(arr.count(5)).toEqual(0);
    });

    it('returns 3 for an element that occurs 3 times', function(){
      arr.push(2);
      arr.push(2);
      expect(arr.count(2)).toEqual(3);
    });
  });

  describe('min and max', function(){
    it('min returns the smallest value of an array', function(){
      expect(arr.min()).toEqual(1);
      expect([2, 1, 3].min()).toEqual(1);
    })

    it('max returns the biggest value of an array', function(){
      expect(arr.max()).toEqual(3);
    })
  })

  describe('equals', function(){
    it('returns true if the two arrays have same length and same elements in the same order', function(){
      expect(arr.equals([1,2,3])).toBe(true);
    })

    it('returns false if the two arrays are different', function(){
      expect(arr.equals([1,3,5])).toBe(false)
      expect(arr.equals([1,3,2])).toBe(false)
      expect(arr.equals([1,2])).toBe(false)
    })
  })
});


text:
module NamespacesHelper
  def namespace_id_from(params)
    params.dig(:project, :namespace_id) || params[:namespace_id]
  end

  def namespaces_options(selected = :current_user, display_path: false, extra_group: nil)
    groups = current_user.owned_groups + current_user.masters_groups

    unless extra_group.nil? || extra_group.is_a?(Group)
      extra_group = Group.find(extra_group) if Namespace.find(extra_group).kind == 'group'
    end

    if extra_group && extra_group.is_a?(Group) && (!Group.exists?(name: extra_group.name) || Ability.allowed?(current_user, :read_group, extra_group))
      groups |= [extra_group]
    end

    users = [current_user.namespace]

    data_attr_group = { 'data-options-parent' => 'groups' }
    data_attr_users = { 'data-options-parent' => 'users' }

    group_opts = [
      "Groups", groups.sort_by(&:human_name).map { |g| [display_path ? g.full_path : g.human_name, g.id, data_attr_group] }
    ]

    users_opts = [
      "Users", users.sort_by(&:human_name).map { |u| [display_path ? u.path : u.human_name, u.id, data_attr_users] }
    ]

    options = []
    options << group_opts
    options << users_opts

    if selected == :current_user && current_user.namespace
      selected = current_user.namespace.id
    end

    grouped_options_for_select(options, selected)
  end

  def namespace_icon(namespace, size = 40)
    if namespace.is_a?(Group)
      group_icon(namespace)
    else
      avatar_icon(namespace.owner.email, size)
    end
  end
end


text:
<?php

namespace Sylius\Bundle\ThemeBundle\Form\Type;

use Sylius\Bundle\ThemeBundle\Repository\ThemeRepositoryInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\ChoiceList\ObjectChoiceList;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * @author Majid Golshadi <golshadi.majid@gmail.com>
 */
class ThemeChoiceType extends AbstractType
{
    /**
     * @var ThemeRepositoryInterface
     */
    protected $themeRepository;

    /**
     * @param ThemeRepositoryInterface $themeRepository
     */
    public function __construct(ThemeRepositoryInterface $themeRepository)
    {
        $this->themeRepository = $themeRepository;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $themes = $this->themeRepository->findAll();

        $resolver->setDefault('choice_list', new ObjectChoiceList($themes, 'title', [], null, 'name'));
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return ChoiceType::class;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'sylius_theme_choice';
    }
}


text:
			Log in
			Sign up


text:
// [Threading] Thread Throttling Support

#include "BaseLib/MMSwitcher.h"

#include "ThreadThrottler.h"
#include <thread>

#define TTLogTag _T("T.Throttler '%s'")
#define TTLogHeader _T("{") TTLogTag _T("} ")

//! @ingroup Threading
//! Raise an exception within a thread throttler with formatted string message
#define TTFAIL(...)																	\
{																					\
	SOURCEMARK;																		\
	throw new ThreadThrottlerException(*this, std::move(__SrcMark), __VA_ARGS__);	\
}

//! Perform logging within a synchronized queue
#define TTLOG(s, ...) LOG(TTLogHeader s, Name.c_str(), __VA_ARGS__)
#define TTLOGV(s, ...) LOGV(TTLogHeader s, Name.c_str(), __VA_ARGS__)
#define TTLOGVV(s, ...) LOGVV(TTLogHeader s, Name.c_str(), __VA_ARGS__)

DWORD const ThreadThrottler::MIntervalMin = 100;
DWORD const ThreadThrottler::MIntervalMax = 30000;
DWORD const ThreadThrottler::TIntervalMin = 10;
DWORD const ThreadThrottler::TIntervalMax = 100;
DWORD const ThreadThrottler::MTRatioSmall = 10;
DWORD const ThreadThrottler::MTRatioLarge = 100;
DWORD const ThreadThrottler::MTRatioMin = 5;
DWORD const ThreadThrottler::MTRatioMax = 500;
DWORD const ThreadThrottler::MAXLOAD = std::thread::hardware_concurrency() * MSTime_aSecond;

ThreadThrottler::ThreadThrottler(TString const &xName, DWORD xLoadLimit, DWORD xMInterval, DWORD xTInterval) :
Name(xName), LoadLimit(xLoadLimit), MInterval(xMInterval), TInterval(xTInterval),
rState(State::Monitoring), ThrottleCount(0), ThrottleTime(0), WaitEvent(true),
CurLoad(0), SampleCount(xMInterval / xTInterval), SamplePtr(0), Samples(SampleCount) {
	if ((xMInterval < MIntervalMin) || (xMInterval > MIntervalMax))
		TTFAIL(_T("Invliad monitoring interval %d (must be between %d and %d)"), xMInterval, MIntervalMin, MIntervalMax);
	if ((xTInterval < TIntervalMin) || (xTInterval > TIntervalMax))
		TTFAIL(_T("Invliad throttling interval %d (must be between %d and %d)"), xTInterval, TIntervalMin, TIntervalMax);
	if (SampleCount < MTRatioMin)
		TTFAIL(_T("Invliad throttling interval %d (must be smaller than %d)"), xTInterval, xMInterval / MTRatioMin);
	if (SampleCount > MTRatioMax)
		TTFAIL(_T("Invliad throttling interval %d (must be larger than %d)"), xTInterval, xMInterval / MTRatioMax);
	if (SampleCount < MTRatioSmall)
		TTFAIL(_T("WARNING: Throttling interval %d larger than recommended value %d"), xTInterval, xMInterval / MTRatioSmall);
	if (SampleCount > MTRatioLarge)
		TTFAIL(_T("WARNING: Throttling interval %d smaller than recommended value %d"), xTInterval, xMInterval / MTRatioLarge);
	if (xLoadLimit >= MAXLOAD)
		TTLOG(_T("WARNING: Load limit %d is higher than the maximum hardware concurrency (%d)"), xLoadLimit, MAXLOAD);
}

LPCTSTR ThreadThrottler::STR_State(State const &xState) {
	static LPCTSTR const _STR_State[] = {
		_T("Monitoring"),
		_T("Activated"),
		_T("Throttling"),
	};
	return _STR_State[(int)xState];
}

void ThreadThrottler::RegisterWorker(TWorkerThread *Worker) {
	HANDLE WThread = Worker->rThread;
	Synchronized(RunLock, {
		for (size_t i = 0; i < Threads.size(); i++) {
			HANDLE TThread = Threads[i].first->rThread;
			if (TThread == WThread)
				FAIL(_T("{Throttler %s} WorkerThread '%s' already registered"), Name.c_str(), Worker->Name.c_str());
		}

		Flatten_FILETIME TTimes[4];
		GetThreadTimes(WThread, &TTimes[0].FileTime, &TTimes[1].FileTime, &TTimes[2].FileTime, &TTimes[3].FileTime);
		Threads.emplace_back(Worker, TTimes[2].U64 + TTimes[3].U64);
	});
	LOGV(_T("{Throttler %s} Registered WorkerThread '%s'"), Name.c_str(), Worker->Name.c_str());
}

void ThreadThrottler::UnregisterWorker(TWorkerThread *Worker) {
	HANDLE WThread = Worker->rThread;
	Synchronized(RunLock, {
		for (size_t i = 0; i < Threads.size(); i++) {
			HANDLE TThread = Threads[i].first->rThread;
			if (TThread == WThread) {
				Threads.erase(Threads.cbegin() + i);
				LOGV(_T("{Throttler %s} Unregistered WorkerThread '%s'"), Name.c_str(), Worker->Name.c_str());
				if (rState == State::Throttling)
					ResumeThread(WThread);
				Worker = nullptr;
				break;
			}
		}
	});
	if (Worker) {
		LOGV(_T("{Throttler %s} WARNING: WorkerThread '%s' not registered"), Name.c_str(), Worker->Name.c_str());
	}
}

void ThreadThrottler::Bump(void) {
	WaitEvent.Pulse();
}

double ThreadThrottler::GetLoadFactor(void) const {
	Synchronized((*const_cast<TLockableCS*>(&RunLock)), {
		return LoadLimit ? (double)CurLoad / LoadLimit : INFINITY;
	});
}

ThreadThrottler::State ThreadThrottler::CurrentState(void) const {
	Synchronized((*const_cast<TLockableCS*>(&RunLock)), {
		return rState;
	});
}

UINT64 ThreadThrottler::GetThrottleCount(void) const {
	Synchronized((*const_cast<TLockableCS*>(&RunLock)), {
		return ThrottleCount;
	});
}

UINT64 ThreadThrottler::GetThrottleTime(void) const {
	Synchronized((*const_cast<TLockableCS*>(&RunLock)), {
		return ThrottleTime;
	});
}

void ThreadThrottler::StateCheck(DWORD &WaitTime) {
	Flatten_FILETIME PrevTS;
	Flatten_FILETIME CurTS;
	UINT64 RawLoad;
	UINT64 DeltaTime;
	DWORD TMultiplier = 0;

	DWORD HistDuration = MInterval * MSTime_o100ns;
	DWORD const LoadSentinal = LoadLimit * 95 / 100;

	GetSystemTimeAsFileTime(&PrevTS.FileTime);
	Samples[SamplePtr].Dur = PrevTS.U64;
	Samples[SamplePtr].RL = 0;

	Synchronized(RunLock, {
		switch (rState) {
			case State::Monitoring:
			case State::Activiated:
				// Record the sample time
				GetSystemTimeAsFileTime(&CurTS.FileTime);
				DeltaTime = CurTS.U64 - PrevTS.U64;
				if (DeltaTime == 0)
					return;
				PrevTS.U64 = CurTS.U64;

				// Record the load time since last sample
				RawLoad = 0;
				for (size_t i = 0; i < Threads.size(); i++) {
					Flatten_FILETIME TTimes[4];
					if (GetThreadTimes(Threads[i].first->rThread, &TTimes[0].FileTime, &TTimes[1].FileTime, &TTimes[2].FileTime, &TTimes[3].FileTime)) {
						UINT64 LTime = TTimes[2].U64 + TTimes[3].U64;
						RawLoad += LTime - Threads[i].second;
						Threads[i].second = LTime;
					} else {
						LOGSYSERR(_T("WARNING: Failed to query time information for WorkerThread '%s'"), Threads[i].first->Name.c_str());
					}
				}

				SamplePtr = (SamplePtr + 1) % SampleCount;
				Samples[SamplePtr].Dur = DeltaTime;
				Samples[SamplePtr].RL = RawLoad;

				for (int SampleIdx = SamplePtr ? SamplePtr - 1 : SampleCount - 1; SampleIdx != SamplePtr; SampleIdx = SampleIdx ? SampleIdx - 1 : SampleCount - 1) {
					if (DeltaTime + Samples[SampleIdx].Dur < HistDuration) {
						DeltaTime += Samples[SampleIdx].Dur;
						RawLoad += Samples[SampleIdx].RL;
					} else break;
				}

				// Derive the x1000 load factor
				CurLoad = (DWORD)(RawLoad * MSTime_aSecond / DeltaTime);

				if (CurLoad <= LoadSentinal) {
					if (TMultiplier > 1) {
						HistDuration = max(TInterval, MInterval / TMultiplier) * MSTime_o100ns;
						WaitTime = TInterval * --TMultiplier;
						//TTLOGVV(_T("Throttle less @%d"), WaitTime);
					} else {
						if (TMultiplier) {
							--TMultiplier;
							//WaitTime = TInterval;
							//TTLOGVV(_T("Watch start @%d"), WaitTime);
							HistDuration = MInterval * MSTime_o100ns;
						} else {
							//DEBUGVV({if (WaitTime < MInterval) TTLOG(_T("Watch Relax @%d"), min(MInterval, WaitTime * 2));});
							WaitTime = min(MInterval, WaitTime + TInterval);
						}
					}
				} else if (CurLoad <= LoadLimit) {
					if (TMultiplier > 0) {
						WaitTime = TInterval * TMultiplier;
					} else {
						//DEBUGVV({if (WaitTime > TInterval) TTLOG(_T("Watch Tight @%d"), max(TInterval, WaitTime / 2)); });
						WaitTime = max(TInterval, WaitTime / 2);
					}
				} else {
					WaitTime = TInterval * ++TMultiplier;
					//DEBUGVV({if (TMultiplier > 1) TTLOGVV(_T("Throttle More @%d"), WaitTime) else TTLOGVV(_T("Throttle Start @%d"), WaitTime)});
					HistDuration = max(TInterval, MInterval / (TMultiplier + 1)) * MSTime_o100ns;
				}

				if (TMultiplier) {
					rState = State::Throttling;
					for (size_t i = 0; i < Threads.size(); i++)
						SuspendThread(Threads[i].first->rThread);
					++ThrottleCount;
					ThrottleTime += WaitTime;
				} else
					rState = State::Monitoring;
				break;

			case State::Throttling:
				for (size_t i = 0; i < Threads.size(); i++)
					ResumeThread(Threads[i].first->rThread);
				rState = State::Activiated;
				WaitTime = TInterval;
				break;
		}
	});
}

void* ThreadThrottler::Run(TWorkerThread& WorkerThread, void* NoUse) {
	DWORD WaitTime = MInterval;

	__try {
		while (WorkerThread.CurrentState() == TWorkerThread::State::Running) {
			WaitEvent.WaitFor(WaitTime);
			StateCheck(WaitTime);
		}
	} __finally {
		if (rState == State::Throttling) {
			for (size_t i = 0; i < Threads.size(); i++)
				ResumeThread(Threads[i].first->rThread);
		}
	}
	return nullptr;
}

void ThreadThrottler::StopNotify(void) {
	WaitEvent.Set();
}

LPCTSTR ThreadThrottlerException::Why(void) const {
	if (rWhy.length() == 0) {
		TString tWhy = Exception::Why();
		const_cast<TString*>(&rWhy)->resize(__DefErrorMsgBufferLen, NullWChar);
		int MsgLen = _sntprintf_s((TCHAR*)&rWhy.front(), __DefErrorMsgBufferLen, _TRUNCATE, TTLogHeader _T("%s"), ThreadThrottlerName.c_str(), tWhy.c_str());
		if (MsgLen >= 0)
			const_cast<TString*>(&rWhy)->resize(MsgLen);
	}
	return rWhy.c_str();
}

#undef TTFAIL
#undef TTLOG
#undef TTLOGV
#undef TTLOGVV


text:
"use strict";

var $            = require("jquery");
var conf         = require("./conf.json");
var firefox      = require('./firefox/firefox.js');
var Track        = require("./modules/Track");
var plugins      = require("./plugins");
var currentTrack = null;
var host         = null;
var poller       = null;

function createGUID() {

    function S4() {
        return Math.floor(Math.random() * 0x10000).toString(16);
    }

    return (
        S4() + S4() + "-" +
        S4() + "-" +
        S4() + "-" +
        S4() + "-" +
        S4() + S4() + S4()
    );
}

function getAccessToken() {

    if (/scroblr\.fm\/access\-granted/i.test(window.location.href)) {

        if (!/token=.+/i.test(window.location.search)) {
            return true;
        }

        var token = window.location.search.split('=')[1];

        if (typeof chrome != 'undefined') {
            chrome.extension.sendMessage({
                name: 'accessGranted',
                message: token
            });
        } else if (typeof safari != 'undefined') {
            safari.self.tab.dispatchMessage('accessGranted', token);
        } else if (firefox) {
            firefox.postMessage({
                name: 'accessGranted',
                message: token
            });
        }
        return true;
    }
    return false;
}

/**
 * Calculates the amount of milliseconds that have passed since the track
 * started playing.
 *
 * @param {Number} dateTime - Datetime value
 */
function getElapsedTime(dateTime) {
    var now = (new Date()).valueOf();
    return now - dateTime;
}

/**
 * Initialization method
 */
function init() {

    for (var key in plugins) {

        if (conf.DEBUG) {
            console.log("SCROBLR::::: Testing plugin ", key, document.location.hostname);
        }

        if (plugins.hasOwnProperty(key) && plugins[key].test()) {
            host    = plugins[key];
            host.id = host.name.toUpperCase() + (new Date()).valueOf();
            plugins.length = 0;

            if (conf.DEBUG) {
                console.log("SCROBLR::::: Initializing plugin ", key);
            }

            if (typeof host.initialize === "function") {
                host.initialize();
            }

            poller = window.setInterval(pollTrackInfo, 5000);
            break;
        }
    }
}

function pollTrackInfo() {
    var newTrack  = Object.create(Track);
    var prevTrack = currentTrack || {toString: function () {return "";}};
    var updateObj = {};

    newTrack.init(host.scrape(), host.name, host.id);

    if (!newTrack.toString()) {

		if (newTrack.hasOwnProperty("reset") && newTrack.reset === true) {
			currentTrack = null;
		}
        return false;
    }

    // A new track is playing
    if (newTrack.toString() !== prevTrack.toString()) {
        newTrack.id  = createGUID();
        currentTrack = newTrack;
        sendMessage("nowPlaying", newTrack);

    // A track continues to play
    } else if (!newTrack.stopped) {
        newTrack.id  = prevTrack.id;
        updateObj.id = newTrack.id;

        ["album", "duration", "elapsed", "percent", "score", "stopped"].forEach(
                function (val) {

            if (newTrack.hasOwnProperty(val) && newTrack[val] !==
					prevTrack[val]) {
                prevTrack[val] = newTrack[val];
                updateObj[val] = newTrack[val];
            } else if (val === "elapsed" && !newTrack.hasOwnProperty(val)) {
                prevTrack[val] = getElapsedTime(prevTrack.dateTime);
                updateObj[val] = prevTrack[val];
            }
        });

        sendMessage("updateCurrentTrack", updateObj);

    // A track is paused
    } else if (newTrack.stopped) {
		updateObj.id = prevTrack.id;
        sendMessage("updateCurrentTrack", updateObj);
    }
}

/**
 * @param {string} name
 * @param {object} message
 */
function sendMessage(name, message) {
	var key, msg;

	if (conf.DEBUG) {
		console.log("SCROBLR::::: ", name, message);
	}

    if (typeof chrome != "undefined") {
        chrome.extension.sendMessage({
            name: name,
            message: message
        });
    } else if (typeof safari != "undefined") {
		msg = $.extend({}, message);

		/*
		 * If you try passing an object with functions in it through Safari's
		 * dispatchMessage method, it will quietly suppress the message and not
		 * do anything. This enumerator will remove any functions from the
		 * message object by setting them to null.
		 */
		for (key in msg) {

			if (msg.hasOwnProperty(key) && typeof msg[key] === "function") {
				msg[key] = null;
			}
		}
        safari.self.tab.dispatchMessage(name, msg);
    } else if (firefox) {
        firefox.postMessage({
            name: name,
            message: message
        });
    }
}

/*
 * Check for the access granted token on the scroblr access granted site. If
 * not available, proceed as normal and initialize the content script.
 */
if (!getAccessToken()) {
    init();
}