text:
package test.com.wirelust.bitbucket.client;

import com.wirelust.bitbucket.client.BitBucketUndocumentedClient;
import com.wirelust.bitbucket.client.BitbucketAuthClient;
import com.wirelust.bitbucket.client.BitbucketV1Client;
import com.wirelust.bitbucket.client.BitbucketV2Client;
import com.wirelust.bitbucket.client.Constants;
import com.wirelust.bitbucket.client.representations.*;
import com.wirelust.bitbucket.client.representations.auth.OauthAccessToken;
import com.wirelust.bitbucket.client.representations.v1.Privilege;
import com.wirelust.bitbucket.client.representations.v1.V1Comment;
import com.wirelust.bitbucket.client.representations.v1.V1Repo;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.ConfigurableMavenResolverSystem;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.jboss.shrinkwrap.resolver.api.maven.PomEquippedResolveStage;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wickedsource.diffparser.api.DiffParser;
import org.wickedsource.diffparser.api.UnifiedDiffParser;
import org.wickedsource.diffparser.api.model.Diff;
import test.com.wirelust.bitbucket.client.providers.JacksonConfigurationProvider;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.Response;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

/**
 * Date: 07-Oct-2015
 *
 * @author T. Curran
 */
@RunWith(Arquillian.class)
public class EndpointTest {
	private static final Logger LOGGER = LoggerFactory.getLogger(EndpointTest.class);

	static final String ROOT_URL = "http://localhost:8080/client-test/api/";
	static final String AUTH_ROOT_URL = "http://localhost:8080/client-test/site/";

	static final String DATE_FORMAT = "yyyy-MM-dd";
	static final String DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX";

	static final String MOCK_USER_ID = "-";

	ResteasyClient client;
	ResteasyWebTarget target;
	BitbucketV1Client bitbucketV1Client;
	BitbucketV2Client bitbucketV2Client;
	BitBucketUndocumentedClient bitBucketUndocumentedClient;
	BitbucketAuthClient bitbucketAuthClient;
	SimpleDateFormat simpleDateFormat;
	SimpleDateFormat simpleDateTimeFormat;
	SimpleDateFormat simpleDateTimeFormat2;

	@Deployment
	public static WebArchive create() {
		WebArchive testWar = ShrinkWrap.create(WebArchive.class, "client-test.war");
		testWar.addPackages(true, "com.wirelust.bitbucket.client");
		testWar.addPackages(true, "test.com.wirelust.bitbucket.client");
		testWar.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));

		File dir = new File("src/test/resources");
		addResourceFilesToArchive(testWar, dir);

		ConfigurableMavenResolverSystem mvnResolver = Maven.configureResolver();
		PomEquippedResolveStage pers = mvnResolver.loadPomFromFile("pom.xml");
		testWar.addAsLibraries(pers.resolve("org.apache.commons:commons-io").withTransitivity().asFile());
		testWar.addAsLibraries(pers.resolve("org.wickedsource:diffparser").withTransitivity().asFile());

		// I'm not including all of the TEST scoped dependencies any longer because jacoco will get an error on startup
		//testWar.addAsLibraries(Maven.resolver().loadPomFromFile("pom.xml").importDependencies(ScopeType.TEST).resolve
		//	().withTransitivity().asFile());

		System.out.println("test.war:" + testWar.toString(true));
		LOGGER.debug("test deployment: {}", testWar.toString(true));

		return testWar;
	}

	@Before
	public void init() {
		client = new ResteasyClientBuilder().build();
		client.register(JacksonConfigurationProvider.class);

		target = client.target(ROOT_URL);
		bitbucketV1Client = target.proxy(BitbucketV1Client.class);

		target = client.target(ROOT_URL);
		bitbucketV2Client = target.proxy(BitbucketV2Client.class);
		bitBucketUndocumentedClient = target.proxy(BitBucketUndocumentedClient.class);

		target = client.target(AUTH_ROOT_URL);
		bitbucketAuthClient = target.proxy(BitbucketAuthClient.class);

		TimeZone gmtZone = TimeZone.getTimeZone("GMT+0");

		simpleDateFormat = new SimpleDateFormat(DATE_FORMAT);
		simpleDateFormat.setTimeZone(gmtZone);

		simpleDateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
		simpleDateTimeFormat.setTimeZone(gmtZone);

		simpleDateTimeFormat2 = new SimpleDateFormat(Constants.DATE_TIME_FORMAT_2);
		simpleDateTimeFormat2.setTimeZone(gmtZone);
	}

	@After
	public void destroy() {
	}

	@Test
	public void shouldBeAbleToDeseralizeAuthToken() throws Exception {

		Response response = bitbucketAuthClient.getTokenByUsernamePassword("password", "username", "password");
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		OauthAccessToken accessToken = response.readEntity(OauthAccessToken.class);
		Assert.assertEquals("gX0XmlxGGOmJXT3dBiurs8nkfgqNXlqni-nplZbOyEDwuvIWTpldCW-FRlFcP4YWtrQJSTtBcDdt324",
			accessToken.getAccessToken());
		Assert.assertEquals("repository:admin team:write account:write", accessToken.getScopes());
		Assert.assertEquals(3600, (long)accessToken.getExpiresIn());
		Assert.assertEquals("E7fNADEJvW834Es8nz", accessToken.getRefreshToken());
		Assert.assertEquals("bearer", accessToken.getTokenType());
	}

	@Test
	public void shouldBeAbleToDeseralizeGetAllRepositories() throws Exception {

		Response response = bitbucketV2Client.getAllRepositories();
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		RepositoryList repositoryList = response.readEntity(RepositoryList.class);

		Assert.assertEquals(10, (long) repositoryList.getPagelen());

		Repository repository = repositoryList.getValues().get(0);
		Assert.assertEquals("hg", repository.getScm());

		Date createdDate = simpleDateTimeFormat.parse("2008-06-25T00:53:00.273366+00:00");
		Assert.assertEquals(createdDate, repository.getCreatedOn());

		Map<String, List<Link>> links = repository.getLinks();
		Assert.assertEquals(8, links.size());

		List<Link> cloneLinks = links.get("clone");
		Assert.assertEquals(2, cloneLinks.size());

		Link firstCloneLink = cloneLinks.get(0);
		Assert.assertEquals("https://bitbucket.org/phlogistonjohn/tweakmsg", firstCloneLink.getHref());
		Assert.assertEquals("https", firstCloneLink.getName());
	}

	@Test
	public void shouldBeAbleToDeseralizeGetBuildStatus() throws Exception {
		Response response = bitbucketV2Client.getBuildStatus("owner", "repo_slug", "revision", "key");
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		BuildStatusWithLinks buildStatus = response.readEntity(BuildStatusWithLinks.class);
		Assert.assertEquals(BuildStatus.State.FAILED, buildStatus.getState());
		Assert.assertEquals("build", buildStatus.getType());
		Assert.assertEquals("BAMBOO-PROJECT-X", buildStatus.getKey());
		Assert.assertEquals("Build #34", buildStatus.getName());
		Assert.assertEquals("https://example.com/path/to/build", buildStatus.getUrl());
		Assert.assertEquals("Changes by John Doe", buildStatus.getDescription());

		Map<String, List<Link>> links = buildStatus.getLinks();
		Assert.assertEquals(2, links.size());

		List<Link> selfLinks = links.get("self");
		Assert.assertEquals(1, selfLinks.size());

		Link firstSelfLink = selfLinks.get(0);
		Assert.assertEquals("http://www.google.com/self", firstSelfLink.getHref());

		List<Link> commitLinks = links.get("commit");
		Assert.assertEquals(1, commitLinks.size());

		Link firstCommitLink = commitLinks.get(0);
		Assert.assertEquals("http://www.google.com/commit", firstCommitLink.getHref());
	}

	@Test
	public void shouldBeAbleToPostBuildStatus() throws Exception {
		BuildStatus buildStatus = new BuildStatus();
		buildStatus.setState(BuildStatus.State.FAILED);
		buildStatus.setKey("key");
		buildStatus.setType("build");

		Response response = bitbucketV2Client.postBuildStatus("owner", "repo_slug", "revision", buildStatus);
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
		Assert.assertEquals(BuildStatus.State.FAILED, buildStatus.getState());
	}

	@Test
	public void shouldBeAbleToPutBuildStatus() throws Exception {
		BuildStatus buildStatus = new BuildStatus();
		buildStatus.setState(BuildStatus.State.FAILED);
		buildStatus.setKey("key");
		buildStatus.setType("build");

		Response response = bitbucketV2Client.putBuildStatus("owner", "repo_slug", "revision", "key", buildStatus);
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
		Assert.assertEquals(BuildStatus.State.FAILED, buildStatus.getState());
	}

	@Test
	public void shouldBeAbleToDeseralizeGetPerivileges() throws Exception {
		Response response = bitbucketV2Client.getPrivileges("owner", Privilege.Type.ADMIN);
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		List<Privilege> privileges = response.readEntity(new GenericType<List<Privilege>>() {});

		Assert.assertEquals(1, privileges.size());

		Privilege privilege = privileges.get(0);
		Assert.assertEquals("tutorials/tutorials.bitbucket.org", privilege.getRepo());
		Assert.assertEquals(Privilege.Type.WRITE, privilege.getPrivilege());

		User user = privilege.getUser();
		Assert.assertEquals("cburwinkle", user.getUsername());
		Assert.assertEquals("Christine", user.getFirstName());
		Assert.assertEquals("Burwinkle", user.getLastName());
		Assert.assertEquals("https://secure.gravatar.com/avatar/test.png", user.getAvatar());
		Assert.assertEquals(false, user.getIsTeam());
	}

	@Test
	public void shouldBeAbleToDeseralizeGetPerivilegesForRepo() throws Exception {
		Response response = bitbucketV2Client.getPrivileges("owner", "repo_slug", Privilege.Type.ADMIN);
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		List<Privilege> privileges = response.readEntity(new GenericType<List<Privilege>>() {});

		Assert.assertEquals(2, privileges.size());

		Privilege privilege = privileges.get(1);
		Assert.assertEquals("tutorials/tutorials.bitbucket.org", privilege.getRepo());
		Assert.assertEquals(Privilege.Type.READ, privilege.getPrivilege());

		Repository repository = privilege.getRepository();
		Assert.assertEquals("tutorials.bitbucket.org", repository.getName());
		Assert.assertEquals("tutorials.bitbucket.org", repository.getSlug());
	}

	@Test
	public void shouldBeAbleToDeseralizeGetRepositoriesByOwner() throws Exception {
		Response response = bitbucketV2Client.getRepositoriesByOwner("owner");
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		RepositoryList repositoryList = response.readEntity(RepositoryList.class);

		Assert.assertEquals(10, (long) repositoryList.getPagelen());

		Repository repository = repositoryList.getValues().get(0);
		Assert.assertEquals("git", repository.getScm());
		Assert.assertEquals("allow_forks", repository.getForkPolicy());
		Assert.assertEquals("dans9190/new-repository", repository.getFullName());
		Assert.assertEquals("This repo ", repository.getDescription());
		Assert.assertEquals(true, repository.getHasIssues());
		Assert.assertEquals(true, repository.getHasWiki());
		Assert.assertEquals(true, repository.getIsPrivate());
		Assert.assertEquals("en_US", repository.getLanguage());
		Assert.assertEquals(33348, (long)repository.getSize());
		Assert.assertEquals("{9bdd6b69-3dc4-406b-a8dd-ff5119aefc61}", repository.getUuid());

		Date createdDate = simpleDateTimeFormat.parse("2014-08-13T19:05:22.148829+00:00");
		Assert.assertEquals(createdDate, repository.getCreatedOn());

		Date modifiedDate = simpleDateTimeFormat.parse("2014-08-13T19:05:22.168083+00:00");
		Assert.assertEquals(modifiedDate, repository.getUpdatedOn());

		Map<String, List<Link>> links = repository.getLinks();
		Assert.assertEquals(8, links.size());

		List<Link> cloneLinks = links.get("clone");
		Assert.assertEquals(2, cloneLinks.size());

		Link firstCloneLink = cloneLinks.get(1);
		Assert.assertEquals("ssh://git@bitbucket.org/dans9190/new-repository.git", firstCloneLink.getHref());
		Assert.assertEquals("ssh", firstCloneLink.getName());

		User owner = repository.getOwner();
		Assert.assertEquals("Daniel  Stevens", owner.getDisplayName());

		Map<String, List<Link>> ownerLinks = owner.getLinks();
		Assert.assertEquals(3, ownerLinks.size());
	}

	@Test
	public void shouldBeAbleToDeseralizeRepositoryByOwnerSlug() throws Exception {

		Response response = bitbucketV2Client.getRepositoryByOwnerRepo("owner", "repo_slug");
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		Repository repository = response.readEntity(Repository.class);

		Assert.assertEquals("hg", repository.getScm());

		Date createdDate = simpleDateTimeFormat.parse("2011-12-20T16:35:06.480042+00:00");
		Assert.assertEquals(createdDate, repository.getCreatedOn());

		Date modifiedDate = simpleDateTimeFormat.parse("2014-11-03T02:24:08.409995+00:00");
		Assert.assertEquals(modifiedDate, repository.getUpdatedOn());

		Map<String, List<Link>> links = repository.getLinks();
		Assert.assertEquals(8, links.size());

		List<Link> cloneLinks = links.get("clone");
		Assert.assertEquals(2, cloneLinks.size());

		Link firstCloneLink = cloneLinks.get(1);
		Assert.assertEquals("ssh://hg@bitbucket.org/tutorials/tutorials.bitbucket.org", firstCloneLink.getHref());
		Assert.assertEquals("ssh", firstCloneLink.getName());

		User owner = repository.getOwner();
		Assert.assertEquals("tutorials account", owner.getDisplayName());

		Map<String, List<Link>> ownerLinks = owner.getLinks();
		Assert.assertEquals(3, ownerLinks.size());
	}

	@Test
	public void shouldBeAbleToDeseralizePullRequestList() throws Exception {
		Response response = bitbucketV2Client.getPullRequests("owner", "repo_slug", "OPEN");
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		PullRequestList pullRequestList = response.readEntity(PullRequestList.class);

		Assert.assertEquals(1, (long)pullRequestList.getPage());
		Assert.assertEquals(12, (long)pullRequestList.getSize());
		Assert.assertEquals(1, (long)pullRequestList.getPagelen());
		Assert.assertEquals("http://www.google.com/fakeurl2", pullRequestList.getNext());

		List<PullRequest> pullRequests = pullRequestList.getValues();
		Assert.assertEquals(1, pullRequests.size());

		PullRequest firstPullRequest = pullRequests.get(0);
		Assert.assertEquals(true, firstPullRequest.getCloseSourceBranch());

		Map<String, List<Link>> links = firstPullRequest.getLinks();
		Assert.assertEquals(10, links.size());

		CommitSource commitSource = firstPullRequest.getSource();
		Assert.assertEquals("mfrauenholtz/team-removal/admin-links", commitSource.getBranch().getName());
		Assert.assertEquals("2a81a1edc0c2", commitSource.getCommit().getHash());
		Assert.assertEquals(1, commitSource.getCommit().getLinks().size());

		CommitSource commitDestination = firstPullRequest.getDestination();
		Assert.assertEquals("staging", commitDestination.getBranch().getName());
		Assert.assertEquals("e04099ba977c", commitDestination.getCommit().getHash());
		Assert.assertEquals(1, commitDestination.getCommit().getLinks().size());
	}

	@Test
	public void shouldBeAbleToDeseralizePullRequest() throws Exception {
		Response response = bitbucketV2Client.getPullRequestById("owner", "repo_slug", (long)1);
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		PullRequest pullRequest = response.readEntity(PullRequest.class);
		Assert.assertEquals(3767, (long)pullRequest.getId());
		Assert.assertEquals("BB-9500: Remove certain admin links for Team accounts", pullRequest.getTitle());
		Assert.assertEquals("Change username * Delete account (rename to delete team)", pullRequest.getDescription());
		Assert.assertEquals("What does this field do?", pullRequest.getReason());
		Assert.assertEquals(true, pullRequest.getCloseSourceBranch());
		Assert.assertNull(pullRequest.getClosedBy());
		Assert.assertEquals(PullRequest.State.OPEN, pullRequest.getState());
		Assert.assertNull(pullRequest.getMergeCommit());

		Date dateCreated = simpleDateTimeFormat.parse("2013-11-05T23:59:26.480984+00:00");
		Assert.assertEquals(dateCreated, pullRequest.getCreatedOn());

		Date dateUpdated = simpleDateTimeFormat.parse("2013-11-07T00:17:41.061613+00:00");
		Assert.assertEquals(dateUpdated, pullRequest.getUpdatedOn());

		Map<String, List<Link>> links = pullRequest.getLinks();
		Assert.assertEquals(10, links.size());

		User author = pullRequest.getAuthor();
		Assert.assertEquals("mfrauenholtz", author.getUsername());

		CommitSource commitSource = pullRequest.getSource();
		Assert.assertEquals("mfrauenholtz/team-removal/admin-links", commitSource.getBranch().getName());
		Assert.assertEquals("2a81a1edc0c2", commitSource.getCommit().getHash());
		Assert.assertEquals(1, commitSource.getCommit().getLinks().size());
		Assert.assertEquals("bitbucket", commitSource.getRepository().getName());

		CommitSource commitDestination = pullRequest.getDestination();
		Assert.assertEquals("staging", commitDestination.getBranch().getName());
		Assert.assertEquals("e04099ba977c", commitDestination.getCommit().getHash());
		Assert.assertEquals(1, commitDestination.getCommit().getLinks().size());

		Assert.assertEquals(1, pullRequest.getReviewers().size());
		Assert.assertEquals("bnguyen", pullRequest.getReviewers().get(0).getUsername());

		Assert.assertEquals(3, pullRequest.getParticipants().size());
		Assert.assertEquals("PARTICIPANT", pullRequest.getParticipants().get(0).getRole());
		Assert.assertEquals("mfrauenholtz", pullRequest.getParticipants().get(0).getUser().getUsername());
		Assert.assertEquals("PARTICIPANT", pullRequest.getParticipants().get(1).getRole());
		Assert.assertEquals("dbennett", pullRequest.getParticipants().get(1).getUser().getUsername());

	}

	@Test
	public void shouldBeAbleToDeseralizeRepoCommitList() throws Exception {
		Response response = bitbucketV2Client.getCommitsByOwnerRepo("owner", "repo_slug");
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		CommitList commitList = response.readEntity(CommitList.class);

		Assert.assertEquals(1, (long) commitList.getPage());
		Assert.assertEquals(30, (long) commitList.getPagelen());

		List<Commit> commits = commitList.getValues();
		Assert.assertEquals(1, commits.size());

		Commit firstCommit = commits.get(0);
		Assert.assertEquals("61d9e64348f9da407e62f64726337fd3bb24b466", firstCommit.getHash());
		Assert.assertEquals("atlassian-rest", firstCommit.getRepository().getName());

		Map<String, List<Link>> links = firstCommit.getLinks();
		Assert.assertEquals(6, links.size());

		Assert.assertEquals("59721f593b020123a75424285845325126f56e2e", firstCommit.getParents().get(0).getHash());

		Date date = simpleDateTimeFormat2.parse("2013-10-21T07:21:51+00:00");
		Assert.assertEquals(date, firstCommit.getDate());

		Assert.assertEquals("Merge remote-tracking branch 'origin/rest-2.8.x' ", firstCommit.getMessage());

		Assert.assertEquals("Joseph Walton", firstCommit.getAuthor().getUser().getDisplayName());
		Assert.assertEquals("jwalton", firstCommit.getAuthor().getUser().getUsername());
	}

	@Test
	public void shouldBeAbleToDeseralizeRepoCommit() throws Exception {
		Response response = bitbucketV2Client.getCommitByOwnerRepoRevision("owner", "repo_slug", "revision");
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		Commit commit = response.readEntity(Commit.class);

		Assert.assertEquals("61d9e64348f9da407e62f64726337fd3bb24b466", commit.getHash());

		Map<String, List<Link>> links = commit.getLinks();
		Assert.assertEquals(6, links.size());

		List<Participant> participants = commit.getParticipants();
		Assert.assertEquals(1, participants.size());
		Assert.assertFalse(participants.get(0).isApproved());

		Assert.assertEquals("59721f593b020123a75424285845325126f56e2e", commit.getParents().get(0).getHash());

		Date date = simpleDateTimeFormat2.parse("2013-10-21T07:21:51+00:00");
		Assert.assertEquals(date, commit.getDate());

		Assert.assertEquals("Merge remote-tracking branch 'origin/rest-2.8.x' ", commit.getMessage());

		Assert.assertEquals("Joseph Walton", commit.getAuthor().getUser().getDisplayName());
		Assert.assertEquals("jwalton", commit.getAuthor().getUser().getUsername());
	}

	@Test
	public void shouldBeAbleToDeseralizePullRequestCommitList() throws Exception {
		Response response = bitbucketV2Client.getPullRequestCommits("owner", "repo_slug", (long)1);
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		CommitList commitList = response.readEntity(CommitList.class);

		Assert.assertEquals(1, (long) commitList.getPage());
		Assert.assertEquals(11, (long) commitList.getSize());
		Assert.assertEquals(1, (long) commitList.getPagelen());
		Assert.assertEquals("http://www.google.com/fakeurl", commitList.getNext());

		List<Commit> commits = commitList.getValues();
		Assert.assertEquals(1, commits.size());

		Commit firstCommit = commits.get(0);
		Assert.assertEquals("ad758aeba36fa4b9d258ac1667f55cfb811e6df3", firstCommit.getHash());

		Map<String, List<Link>> links = firstCommit.getLinks();
		Assert.assertEquals(6, links.size());

		Assert.assertEquals("16929c2f94828ca9d8adb5b91e7db7b274aae318", firstCommit.getParents().get(0).getHash());

		Date date = simpleDateTimeFormat2.parse("2013-11-07T00:17:05+00:00");
		Assert.assertEquals(date, firstCommit.getDate());

		Assert.assertEquals("Reorder imports. ", firstCommit.getMessage());

		Assert.assertEquals("Erik van Zijst <erik.van.zijst@gmail.com>", firstCommit.getAuthor().getRaw());
		Assert.assertEquals("erik", firstCommit.getAuthor().getUser().getUsername());
	}

	@Test
	public void shouldBeAbleToDeseralizeCommitCommentList() throws Exception {
		Response response = bitbucketV2Client.getCommentsByOwnerRepoRevision("owner", "repo_slug", "revision");
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		CommentList commentList = response.readEntity(CommentList.class);
		Assert.assertEquals("http://www.google.com/fakeurl4", commentList.getNext());

		List<Comment> comments = commentList.getValues();
		Assert.assertEquals(1, comments.size());

		Comment firstComment = comments.get(0);
		Assert.assertEquals(530189, (long)firstComment.getId());

		Date dateCreated = simpleDateTimeFormat.parse("2013-11-07T23:55:24.486865+00:00");
		Assert.assertEquals(dateCreated, firstComment.getCreatedOn());

		Date dateModified = simpleDateTimeFormat.parse("2013-11-07T23:55:24.502477+00:00");
		Assert.assertEquals(dateModified, firstComment.getUpdatedOn());
	}

	@Test
	public void shouldBeAbleToDeseralizeCommitComment() throws Exception {
		Response response = bitbucketV2Client.getCommentByOwnerRepoRevisionId("owner", "repo_slug", "revision",
			"comment_id");
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		Comment comment = response.readEntity(Comment.class);

		Assert.assertEquals(530189, (long)comment.getId());
		Assert.assertEquals("Inline test comment.", comment.getContent().getRaw());
		Assert.assertEquals("<p>Inline test comment.</p>", comment.getContent().getHtml());

		Date dateCreated = simpleDateTimeFormat.parse("2013-11-07T23:55:24.486865+00:00");
		Assert.assertEquals(dateCreated, comment.getCreatedOn());

		Date dateModified = simpleDateTimeFormat.parse("2013-11-07T23:55:24.502477+00:00");
		Assert.assertEquals(dateModified, comment.getUpdatedOn());

		Map<String, List<Link>> links = comment.getLinks();
		Assert.assertEquals("http://www.google.com", links.get("self").get(0).getHref());

		CommentLine commentLine = comment.getInline();
		Assert.assertEquals(381, (int)commentLine.getFrom());
		Assert.assertNull(commentLine.getTo());
		Assert.assertEquals("pom.xml", commentLine.getPath());
	}

	@Test
	public void shouldBeAbleToDeseralizePullRequestCommentList() throws Exception {
		Response response = bitbucketV2Client.getPullRequestComments("owner", "repo_slug", (long)1);
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		CommentList commentList = response.readEntity(CommentList.class);

		Assert.assertEquals(1, (long) commentList.getPage());
		Assert.assertEquals(4, (long) commentList.getSize());
		Assert.assertEquals(1, (long) commentList.getPagelen());

		List<Comment> comments = commentList.getValues();
		Assert.assertEquals(1, comments.size());

		Comment firstComment = comments.get(0);
		Assert.assertEquals(25337, (long)firstComment.getId());

		Assert.assertEquals(25334, (long)firstComment.getParent().getId());

		Assert.assertEquals("markdown", firstComment.getContent().getMarkup());
	}

	@Test
	public void shouldBeAbleToDeseralizePullRequestActivity() throws Exception {
		Response response = bitbucketV2Client.getPullRequestActivity("owner", "repo_slug");
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		PullRequestActivityList activityList = response.readEntity(PullRequestActivityList.class);

		Assert.assertEquals(10965, (long)activityList.getSize());
		Assert.assertEquals("http://www.google.com/fakeurl5", activityList.getNext());

		List<PullRequestActivity> activities = activityList.getValues();
		Assert.assertEquals(2, activities.size());

		PullRequestActivity firstActivity = activities.get(0);
		Assert.assertEquals(3662, (long)firstActivity.getPullRequest().getId());

		Update update = firstActivity.getUpdate();
		Assert.assertEquals("editme.html edited online", update.getDescription());
		Assert.assertEquals(Update.State.OPEN, update.getState());
		Assert.assertEquals("editme.html edited online with Bitbucket", update.getTitle());
		Assert.assertEquals("160c67046cbd", update.getDestination().getCommit().getHash());
		Assert.assertEquals("e38157163256", update.getSource().getCommit().getHash());
		Assert.assertEquals("valid reason", update.getReason());
		Assert.assertEquals("yogaswara", update.getAuthor().getUsername());
		Date updateDate = simpleDateTimeFormat.parse("2014-04-17T11:43:06.043720+00:00");
		Assert.assertEquals(updateDate, update.getDate());

		PullRequestActivity secondActivity = activities.get(1);
		Comment comment = secondActivity.getComment();
		Assert.assertEquals("dans9190", comment.getUser().getUsername());

	}

	@Test
	public void shouldBeAbleToDeseralizePullRequestActivityById() throws Exception {
		Response response = bitbucketV2Client.getPullRequestActivityById("owner", "repo_slug", (long)1);
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		PullRequestActivityList activityList = response.readEntity(PullRequestActivityList.class);

		Assert.assertEquals(10, (long) activityList.getSize());
	}

	@Test
	public void shouldBeAbleToGetPullRequestDiff() throws Exception {
		Response response = bitbucketV2Client.getPullRequestDiff("owner", "repo_slug", (long)1);
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		String diffString = response.readEntity(String.class);
		InputStream diffStream = new ByteArrayInputStream(diffString.getBytes(StandardCharsets.UTF_8));

		DiffParser parser = new UnifiedDiffParser();
		List<Diff> diff = parser.parse(diffStream);
		Assert.assertEquals(5, diff.size());
	}

	@Test
	public void shouldBeAbleToDeseralizePullRequestTaskPost() throws Exception {
		/*
		{
			"content": {
				"raw": "bookType.isDeleted()"
			},
			"comment": {
				"id": 27219095
			},
			"completed": false,
			"state": "UNRESOLVED"
		}
		*/
		Content content = new Content();
		content.setRaw("remove casting here");

		Comment comment = new Comment();
		comment.setId(1L);

		Task task = new Task();
		task.setState(Task.State.UNRESOLVED);
		task.setContent(content);
		task.setComment(comment);

		Response response = bitBucketUndocumentedClient.postPullRequestTask("owner", "repo_slug", (long)1, task);
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		Task taskResponse = response.readEntity(Task.class);

		Assert.assertEquals("markdown", taskResponse.getContent().getMarkup());
	}

	@Test
	public void shouldBeAbleToDeseralizeSnippitByUsernameId() throws Exception {
		Response response = bitbucketV2Client.getSnippetByUsernameId("username", "kypj");
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		Snippet snippet = response.readEntity(Snippet.class);

		Assert.assertEquals("kypj", snippet.getId());
		Assert.assertEquals(false, snippet.getIsPrivate());
		Assert.assertEquals("Daniel  Stevens", snippet.getCreator().getDisplayName());
		Assert.assertEquals("Teams In Space", snippet.getOwner().getDisplayName());
		Assert.assertEquals("git", snippet.getScm());
		Assert.assertEquals("API docs snippet", snippet.getTitle());

		Map<String, BBFile> files = snippet.getFiles();
		Assert.assertTrue(files.containsKey("README.md"));
		Assert.assertTrue(files.containsKey("myquote2.html"));

		BBFile readmeFile = files.get("README.md");
		Assert.assertEquals(2, readmeFile.getLinks().size());

		Assert.assertEquals(7, snippet.getLinks().size());
		Date createdOn = simpleDateTimeFormat.parse("2015-03-18T19:56:51.269348+00:00");
		Assert.assertEquals(createdOn, snippet.getCreatedOn());

		Date updatedOn = simpleDateTimeFormat.parse("2015-03-18T19:56:51.269378+00:00");
		Assert.assertEquals(updatedOn, snippet.getUpdatedOn());
	}

	@Test
	public void shouldBeAbleToDeseralizeTeam() throws Exception {
		Response response = bitbucketV2Client.getTeamByName("teamname");
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		Team team = response.readEntity(Team.class);
		Assert.assertEquals("teamsinspace", team.getUsername());
		Assert.assertEquals("Teams In Space", team.getDisplayName());
		Assert.assertEquals("{61fc5cf6-d054-47d2-b4a9-061ccf858379}", team.getUuid());
		Assert.assertEquals(7, team.getLinks().size());

		Date dateCreated = simpleDateTimeFormat.parse("2014-04-08T00:00:14.070969+00:00");
		Assert.assertEquals(dateCreated, team.getCreatedOn());
	}

	@Test
	public void shouldBeAbleToDeseralizeTeamFollowers() throws Exception {
		Response response = bitbucketV2Client.getTeamFollowers("teamname");
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		UserList userList = response.readEntity(UserList.class);
		Assert.assertEquals(1, userList.getValues().size());

		User user = userList.getValues().get(0);
		Assert.assertEquals("tutorials", user.getUsername());
		Assert.assertEquals("team", user.getKind());
	}

	@Test
	public void shouldBeAbleToDeseralizeTeamRepository() throws Exception {
		Response response = bitbucketV2Client.getTeamRepositories("teamname");
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		RepositoryList repositoryList = response.readEntity(RepositoryList.class);
		Assert.assertEquals(2, repositoryList.getValues().size());

		Repository repository = repositoryList.getValues().get(0);
		Assert.assertEquals("hg", repository.getScm());
	}

	@Test
	public void shouldBeAbleToDeseralizeTeamFollowing() throws Exception {
		Response response = bitbucketV2Client.getTeamFollowing("teamname");
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		UserList userList = response.readEntity(UserList.class);
		Assert.assertEquals(1, userList.getValues().size());

		User user = userList.getValues().get(0);
		Assert.assertEquals("bitbucket", user.getUsername());
	}

	@Test
	public void shouldBeAbleToDeseralizeTeams() throws Exception {
		Response response = bitbucketV2Client.getTeams("contributor");
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		UserList teamList = response.readEntity(UserList.class);
		Assert.assertEquals(10, (long)teamList.getPagelen());

		List<User> users = teamList.getValues();
		Assert.assertEquals(2, users.size());

		User firstUser = users.get(0);
		Assert.assertEquals("1team", firstUser.getUsername());
		Assert.assertEquals("the team", firstUser.getDisplayName());
	}

	@Test
	public void shouldBeAbleToDeseralizeTeamMembers() throws Exception {
		Response response = bitbucketV2Client.getTeamMembers("teamname");
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		UserList userList = response.readEntity(UserList.class);
		Assert.assertEquals(1, userList.getValues().size());

		User user = userList.getValues().get(0);
		Assert.assertEquals("Alana-dev", user.getUsername());
	}

	@Test
	public void shouldBeAbleToDeseralizeUser() throws Exception {
		Response response = bitbucketV2Client.getUser("username");
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		User user = response.readEntity(User.class);

		Assert.assertEquals("tutorials", user.getUsername());
		Assert.assertEquals("https://tutorials.bitbucket.org/", user.getWebsite());
		Assert.assertEquals("tutorials account", user.getDisplayName());
		Assert.assertEquals("Santa Monica, CA", user.getLocation());
		Assert.assertEquals("user", user.getType());

		Map<String, List<Link>> links = user.getLinks();
		Assert.assertEquals(6, links.size());

		Date dateModified = simpleDateTimeFormat.parse("2011-12-20T16:34:07.132459+00:00");
		Assert.assertEquals(dateModified, user.getCreatedOn());
	}

	@Test
	public void shouldBeAbleToDeseralizeUserByUsername() throws Exception {
		Response response = bitbucketV2Client.getUser("username");
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		User user = response.readEntity(User.class);

		Assert.assertEquals("tutorials", user.getUsername());
		Assert.assertEquals("https://tutorials.bitbucket.org/", user.getWebsite());
		Assert.assertEquals("tutorials account", user.getDisplayName());
		Assert.assertEquals("Santa Monica, CA", user.getLocation());
		Assert.assertEquals("user", user.getType());

		Map<String, List<Link>> links = user.getLinks();
		Assert.assertEquals(6, links.size());

		Date dateModified = simpleDateTimeFormat.parse("2011-12-20T16:34:07.132459+00:00");
		Assert.assertEquals(dateModified, user.getCreatedOn());
	}

	@Test
	public void shouldBeAbleToDeseralizeUserFollowers() throws Exception {
		Response response = bitbucketV2Client.getUserFollowers("username");
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		UserFollowerList followerList = response.readEntity(UserFollowerList.class);

		Assert.assertEquals(10, (long)followerList.getPagelen());
		Assert.assertEquals(1, (long) followerList.getPage());
		Assert.assertEquals(1, (long)followerList.getSize());

		List<User> followers = followerList.getValues();
		Assert.assertEquals(1, followers.size());

		User firstFollower = followers.get(0);
		Assert.assertEquals("tutorials", firstFollower.getUsername());
	}

	@Test
	public void shouldBeAbleToPostComment() throws Exception {
		Response response = bitbucketV1Client.postPullRequestComment("owner", "repo_slug", 1L, "comment");
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		V1Comment v1Comment = response.readEntity(V1Comment.class);
		Assert.assertEquals(672, (long)v1Comment.getPullRequestId());
		Assert.assertEquals("pom.xml", v1Comment.getFilename());

		V1Repo repo = v1Comment.getPrRepo();
		Assert.assertEquals("tutorials", repo.getOwner());
		Assert.assertEquals("tutorials-repo", repo.getSlug());
	}

	@Test
	public void shouldBeAbleToPostCommentObject() throws Exception {
		V1Comment comment = new V1Comment();
		comment.setLineTo(59);
		comment.setFilename("/test/file.xml");
		comment.setContent("test comment");

		Response response = bitbucketV1Client.postPullRequestComment("owner", "repo_slug", 1L, comment);
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		V1Comment v1Comment = response.readEntity(V1Comment.class);
		Assert.assertEquals(672, (long)v1Comment.getPullRequestId());
	}

	@Test
	public void shouldBeAbleToUpdateComment() throws Exception {
		V1Comment comment = new V1Comment();
		comment.setLineTo(59);
		comment.setFilename("/test/file.xml");
		comment.setContent("test comment");

		Response response = bitbucketV1Client.putPullRequestComment("owner", "repo_slug", 1L, 1L, comment);
		Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());

		V1Comment v1Comment = response.readEntity(V1Comment.class);
		Assert.assertEquals(672L, (long)v1Comment.getPullRequestId());
	}

	private static void addFilesToWebArchive(WebArchive war, File dir) throws IllegalArgumentException {
		if (dir == null || !dir.isDirectory()) {
			throw new IllegalArgumentException("not a directory");
		}
		for (File f : dir.listFiles()) {
			if (f.isFile()) {
				war.addAsWebResource(f, f.getPath().replace("\\", "/").substring("src/test/resources/".length()));
			} else {
				addFilesToWebArchive(war, f);
			}
		}
	}

	private static void addResourceFilesToArchive(WebArchive war, File dir) throws IllegalArgumentException {
		if (dir == null || !dir.isDirectory()) {
			throw new IllegalArgumentException("not a directory");
		}
		for (File f : dir.listFiles()) {
			if (f.isFile()) {
				war.addAsResource(f, f.getPath().replace("\\", "/").substring("src/test/resources/".length()));
			} else {
				addResourceFilesToArchive(war, f);
			}
		}
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Variable_in_Hexadecimal_Format
{
    class Program
    {
        static void Main(string[] args)
        {
            string hexademical = Console.ReadLine();
            Console.WriteLine(Convert.ToInt16(hexademical, 16));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
// ----------------------------------------------------------------------------
// <copyright file="PhotonRigidbodyView.cs" company="Exit Games GmbH">
//   PhotonNetwork Framework for Unity - Copyright (C) 2018 Exit Games GmbH
// </copyright>
// <summary>
//   Component to synchronize rigidbodies via PUN.
// </summary>
// <author>developer@exitgames.com</author>
// ----------------------------------------------------------------------------

namespace Photon.Pun
{
    using UnityEngine;

    [RequireComponent(typeof(PhotonView))]
    [RequireComponent(typeof(Rigidbody))]
    [AddComponentMenu("Photon Networking/Photon Rigidbody View")]
    public class PhotonRigidbodyView : MonoBehaviour, IPunObservable
    {
        private float m_Distance;
        private float m_Angle;

        private Rigidbody m_Body;

        private PhotonView m_PhotonView;

        private Vector3 m_NetworkPosition;

        private Quaternion m_NetworkRotation;

        public bool m_SynchronizeVelocity = true;
        public bool m_SynchronizeAngularVelocity = false;

        public bool m_TeleportEnabled = false;
        public float m_TeleportIfDistanceGreaterThan = 3.0f;

        public void Awake()
        {
            this.m_Body = GetComponent<Rigidbody>();
            this.m_PhotonView = GetComponent<PhotonView>();

            this.m_NetworkPosition = new Vector3();
            this.m_NetworkRotation = new Quaternion();
        }

        public void FixedUpdate()
        {
            if (!this.m_PhotonView.IsMine)
            {
                this.m_Body.position = Vector3.MoveTowards(this.m_Body.position, this.m_NetworkPosition, this.m_Distance * (1.0f / PhotonNetwork.SerializationRate));
                this.m_Body.rotation = Quaternion.RotateTowards(this.m_Body.rotation, this.m_NetworkRotation, this.m_Angle * (1.0f / PhotonNetwork.SerializationRate));
            }
        }

        public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
        {
            if (stream.IsWriting)
            {
                stream.SendNext(this.m_Body.position);
                stream.SendNext(this.m_Body.rotation);

                if (this.m_SynchronizeVelocity)
                {
                    stream.SendNext(this.m_Body.velocity);
                }

                if (this.m_SynchronizeAngularVelocity)
                {
                    stream.SendNext(this.m_Body.angularVelocity);
                }
            }
            else
            {
                this.m_NetworkPosition = (Vector3)stream.ReceiveNext();
                this.m_NetworkRotation = (Quaternion)stream.ReceiveNext();

                if (this.m_TeleportEnabled)
                {
                    if (Vector3.Distance(this.m_Body.position, this.m_NetworkPosition) > this.m_TeleportIfDistanceGreaterThan)
                    {
                        this.m_Body.position = this.m_NetworkPosition;
                    }
                }

                if (this.m_SynchronizeVelocity || this.m_SynchronizeAngularVelocity)
                {
                    float lag = Mathf.Abs((float)(PhotonNetwork.Time - info.SentServerTime));

                    if (this.m_SynchronizeVelocity)
                    {
                        this.m_Body.velocity = (Vector3)stream.ReceiveNext();

                        this.m_NetworkPosition += this.m_Body.velocity * lag;

                        this.m_Distance = Vector3.Distance(this.m_Body.position, this.m_NetworkPosition);
                    }

                    if (this.m_SynchronizeAngularVelocity)
                    {
                        this.m_Body.angularVelocity = (Vector3)stream.ReceiveNext();

                        this.m_NetworkRotation = Quaternion.Euler(this.m_Body.angularVelocity * lag) * this.m_NetworkRotation;

                        this.m_Angle = Quaternion.Angle(this.m_Body.rotation, this.m_NetworkRotation);
                    }
                }
            }
        }
    }
}


text:
/*
 * $Id: DOMErrorImpl.cpp 568078 2007-08-21 11:43:25Z amassari $
 */

#include "DOMErrorImpl.hpp"
#include <xercesc/dom/DOMException.hpp>
#include <xercesc/dom/DOMLocator.hpp>

XERCES_CPP_NAMESPACE_BEGIN

// ---------------------------------------------------------------------------
//  DOMErrorImpl: Constructors and Destructor
// ---------------------------------------------------------------------------
DOMErrorImpl::DOMErrorImpl(const short severity) :
fAdoptLocation(false)
, fSeverity(severity)
, fMessage(0)
, fLocation(0)
, fType(0)
, fRelatedData(0)
{
}

DOMErrorImpl::DOMErrorImpl(const short severity,
                           const XMLCh* const message,
                           DOMLocator* const location) :
fAdoptLocation(false)
, fSeverity(severity)
, fMessage(message)
, fLocation(location)
, fType(0)
, fRelatedData(0)
{
}

DOMErrorImpl::DOMErrorImpl(const short severity,
                           const XMLCh* type,
                           const XMLCh* message,
                           void* relatedData) :
fAdoptLocation(false)
, fSeverity(severity)
, fMessage(message)
, fLocation(0)
, fType(type)
, fRelatedData(relatedData)
{

}

DOMErrorImpl::~DOMErrorImpl()
{
    if (fAdoptLocation)
        delete fLocation;
}

// ---------------------------------------------------------------------------
//  DOMErrorImpl: Setter methods
// ---------------------------------------------------------------------------
void DOMErrorImpl::setLocation(DOMLocator* const location)
{
    if (fAdoptLocation)
        delete fLocation;

    fLocation = location;
}

void DOMErrorImpl::setRelatedException(void*) const
{
    throw DOMException(DOMException::NOT_SUPPORTED_ERR, 0);
}

XERCES_CPP_NAMESPACE_END


text:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeFixes;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using System.Linq;

namespace RefactoringEssentials.CSharp.Diagnostics
{

    [ExportCodeFixProvider(LanguageNames.CSharp), System.Composition.Shared]
    public class CallToObjectEqualsViaBaseCodeFixProvider : CodeFixProvider
    {
        public override ImmutableArray<string> FixableDiagnosticIds
        {
            get
            {
                return ImmutableArray.Create(CSharpDiagnosticIDs.CallToObjectEqualsViaBaseAnalyzerID);
            }
        }

        // TODO : not sure if this makes sense
        // Test and enable or add comment with reason
        //public override FixAllProvider GetFixAllProvider()
        //{
        //	return WellKnownFixAllProviders.BatchFixer;
        //}

        public async override Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var document = context.Document;
            var cancellationToken = context.CancellationToken;
            var span = context.Span;
            var diagnostics = context.Diagnostics;
            var root = await document.GetSyntaxRootAsync(cancellationToken);
            var diagnostic = diagnostics.First();
            var node = root.FindNode(context.Span) as InvocationExpressionSyntax;
            if (node == null)
                return;

            context.RegisterCodeFix(CodeActionFactory.Create(node.Span, diagnostic.Severity, "Change invocation to call 'object.ReferenceEquals'", arg =>
            {
                var arguments = new SeparatedSyntaxList<ArgumentSyntax>();
                arguments = arguments.Add(SyntaxFactory.Argument(SyntaxFactory.ThisExpression()));
                arguments = arguments.Add(node.ArgumentList.Arguments[0]);

                return Task.FromResult(document.WithSyntaxRoot(
                    root.ReplaceNode((SyntaxNode)
                        node,
                        SyntaxFactory.InvocationExpression(
                            SyntaxFactory.ParseExpression("object.ReferenceEquals"),
                            SyntaxFactory.ArgumentList(arguments)
                        )
                            .WithLeadingTrivia(node.GetLeadingTrivia())
                            .WithAdditionalAnnotations(Formatter.Annotation))
                    )
                );
            }), diagnostic);

            context.RegisterCodeFix(CodeActionFactory.Create(node.Span, diagnostic.Severity, "Remove 'base.'", arg =>
            {
                return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode((SyntaxNode)node, node.WithExpression(SyntaxFactory.IdentifierName("Equals")))));
            }), diagnostic);
        }
    }
}


text:
package stats;

import galaxy.Player;
import galaxy.Stats;

import java.util.LinkedList;

public final class DefaultStats extends Stats {
   int wins = 0, losses = 0;

   public DefaultStats(Player p) {
      super(p);
   }

   @Override
   protected void updateStats(LinkedList<Player> active, Player winner) {
      // List of active is so more stats can be added later.
      // For now, just win/loss record
      if (winner == P) {
         wins++;
      } else {
         losses++;
      }
   }

   @Override
   protected void reportStats() {
      System.out.println("Had " + wins + " wins and " + losses + " losses.");
   }
}


text:
<?php

namespace FG\ASN1\Exception;

class ParserException extends \Exception
{
    private $errorMessage;
    private $offset;

    public function __construct($errorMessage, $offset)
    {
        $this->errorMessage = $errorMessage;
        $this->offset = $offset;
        parent::__construct("ASN.1 Parser Exception at offset {$this->offset}: {$this->errorMessage}");
    }

    public function getOffset()
    {
        return $this->offset;
    }
}


text:
import path = require('path');
import NeDB = require('nedb');
import service = require('feathers-nedb');
import hooks = require('./hooks');

module.exports = function(){
  const app = this;

  const db = new NeDB({
    filename: path.join(app.get('nedb'), 'battle-stats.db'),
    autoload: true,
  });

  let options = {
    Model: db,
    paginate: {
      default: 5,
      max: 25,
    },
  };

  // Initialize our service with any options it requires
  app.use('/battle-stats', service(options));

  // Get our initialize service to that we can bind hooks
  const statService = app.service('/battle-stats');

  // Set up our before hooks
  statService.before(hooks.before);

  // Set up our after hooks
  statService.after(hooks.after);
};


text:
namespace itunes {

ITunesFinder::~ITunesFinder() {}

// static
void ITunesFinder::FindITunesLibrary(const ITunesFinderCallback& callback) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  DCHECK(!callback.is_null());

  ITunesFinder* finder = NULL;
#if defined(OS_WIN)
  finder = new ITunesFinderWin(callback);
#elif defined(OS_MACOSX)
  finder = new ITunesFinderMac(callback);
#endif
  if (finder) {
    content::BrowserThread::PostTask(
        content::BrowserThread::FILE,
        FROM_HERE,
        base::Bind(&ITunesFinder::FindITunesLibraryOnFileThread,
                   base::Unretained(finder)));
  } else {
    callback.Run(std::string());
  }
}

ITunesFinder::ITunesFinder(const ITunesFinderCallback& callback)
    : callback_(callback) {
}

void ITunesFinder::PostResultToUIThread(const std::string& unique_id) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));
  // The use of base::Owned() below will cause this class to get deleted either
  // when FinishOnUIThread() finishes or if the PostTask() fails.
  content::BrowserThread::PostTask(
      content::BrowserThread::UI,
      FROM_HERE,
      base::Bind(&ITunesFinder::FinishOnUIThread,
                 base::Owned(this),
                 unique_id));
}

void ITunesFinder::FinishOnUIThread(const std::string& unique_id) const {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));

  std::string device_id;
  if (!unique_id.empty())
    device_id = StorageInfo::MakeDeviceId(StorageInfo::ITUNES, unique_id);
  callback_.Run(device_id);
}

}  // namespace itunes


text:
<?php

namespace Illuminate\Broadcasting\Broadcasters;

use Pusher\Pusher;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Broadcasting\BroadcastException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

class PusherBroadcaster extends Broadcaster
{
    /**
     * The Pusher SDK instance.
     *
     * @var \Pusher\Pusher
     */
    protected $pusher;

    /**
     * Create a new broadcaster instance.
     *
     * @param  \Pusher\Pusher  $pusher
     * @return void
     */
    public function __construct(Pusher $pusher)
    {
        $this->pusher = $pusher;
    }

    /**
     * Authenticate the incoming request for a given channel.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return mixed
     * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
     */
    public function auth($request)
    {
        if (Str::startsWith($request->channel_name, ['private-', 'presence-']) &&
            ! $request->user()) {
            throw new AccessDeniedHttpException;
        }

        $channelName = Str::startsWith($request->channel_name, 'private-')
                            ? Str::replaceFirst('private-', '', $request->channel_name)
                            : Str::replaceFirst('presence-', '', $request->channel_name);

        return parent::verifyUserCanAccessChannel(
            $request, $channelName
        );
    }

    /**
     * Return the valid authentication response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $result
     * @return mixed
     */
    public function validAuthenticationResponse($request, $result)
    {
        if (Str::startsWith($request->channel_name, 'private')) {
            return $this->decodePusherResponse(
                $request, $this->pusher->socket_auth($request->channel_name, $request->socket_id)
            );
        }

        return $this->decodePusherResponse(
            $request,
            $this->pusher->presence_auth(
                $request->channel_name, $request->socket_id,
                $request->user()->getAuthIdentifier(), $result
            )
        );
    }

    /**
     * Decode the given Pusher response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $response
     * @return array
     */
    protected function decodePusherResponse($request, $response)
    {
        if (! $request->input('callback', false)) {
            return json_decode($response, true);
        }

        return response()->json(json_decode($response, true))
                    ->withCallback($request->callback);
    }

    /**
     * Broadcast the given event.
     *
     * @param  array  $channels
     * @param  string  $event
     * @param  array  $payload
     * @return void
     */
    public function broadcast(array $channels, $event, array $payload = [])
    {
        $socket = Arr::pull($payload, 'socket');

        $response = $this->pusher->trigger(
            $this->formatChannels($channels), $event, $payload, $socket, true
        );

        if ((is_array($response) && $response['status'] >= 200 && $response['status'] <= 299)
            || $response === true) {
            return;
        }

        throw new BroadcastException(
            is_bool($response) ? 'Failed to connect to Pusher.' : $response['body']
        );
    }

    /**
     * Get the Pusher SDK instance.
     *
     * @return \Pusher\Pusher
     */
    public function getPusher()
    {
        return $this->pusher;
    }
}


text:
import RNTest from './react-native-testkit/'
import React from 'react'
import RNFetchBlob from 'react-native-fetch-blob'

import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Platform,
  Dimensions,
  Image,
} from 'react-native';

window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = RNFetchBlob.polyfill.Blob
window.fetch = new RNFetchBlob.polyfill.Fetch({
  auto : true,
  binaryContentTypes : ['image/', 'video/', 'audio/']
}).build()

const fs = RNFetchBlob.fs
const { Assert, Comparer, Info, prop } = RNTest
const describe = RNTest.config({
  group : '0.9.0',
  run : true,
  expand : false,
  timeout : 20000,
})
const { TEST_SERVER_URL, TEST_SERVER_URL_SSL, FILENAME, DROPBOX_TOKEN, styles } = prop()
const dirs = RNFetchBlob.fs.dirs

let prefix = ((Platform.OS === 'android') ? 'file://' : '')

describe('cache control header and range request test', (report, done) => {

  let image = RNTest.prop('image')
  let part = [
    `${fs.dirs.DocumentDir}/cache-control-test-part1.png`,
    `${fs.dirs.DocumentDir}/cache-control-test-part2.png`,
    `${fs.dirs.DocumentDir}/cache-control-test-part3.png`
  ]
  let tmp = null

  RNFetchBlob.fetch('POST', 'https://content.dropboxapi.com/2/files/upload', {
    Authorization : `Bearer ${DROPBOX_TOKEN}`,
    'Dropbox-API-Arg': '{\"path\": \"/rn-upload/'+FILENAME+'\",\"mode\": \"add\",\"autorename\": true,\"mute\": false}',
    'Content-Type' : 'application/octet-stream',
  }, image)
  .then((resp) => {
    resp = resp.json()
    report(
      <Assert key="confirm the file has been uploaded" expect={FILENAME} actual={resp.name}/>
    )
    return RNFetchBlob.config({
      path : part[0],
    })
    .fetch('GET', 'https://content.dropboxapi.com/1/files/auto/rn-upload/' + FILENAME, {
      Authorization : `Bearer ${DROPBOX_TOKEN}`,
      'Cache-Control' : 'no-store',
      'Range' : 'bytes=0-23000'
    })
  })
  .then((res) => {
    let size = Math.floor(res.info().headers['Content-Length'])
    report(<Assert key="part2 content length = 23001" expect={23001} actual={size}/>)
    return RNFetchBlob.config({
      path : part[2]
    })
    .fetch('GET', 'https://content.dropboxapi.com/1/files/auto/rn-upload/' + FILENAME, {
      Authorization : `Bearer ${DROPBOX_TOKEN}`,
      'Range' : 'bytes=23001-23975',
      'Cache-Control' : 'no-store'
    })
  })
  .then((res) => {
    let size = Math.floor(res.info().headers['Content-Length'])
    report(<Assert key="part3 content length = 975" expect={974} actual={size}/>)
    return fs.appendFile(part[0], part[2], 'uri')
  })
  .then((written) => {
    return fs.stat(part[0])
  })
  .then((stat) => {
    report(<Assert key="combined file size check" expect="23975" actual={stat.size}/>)
    done()
  })
})

describe('#73 unicode response BASE64 content test', (report, done) => {

  fetch(`${TEST_SERVER_URL}/unicode`, {
    method : 'GET'
  })
  .then((res) => {
    return res.json()
  })
  .then((data) => {
    report(<Assert key="data should correct" expect={'你好!'} actual={data.data}/>)
    done()
  })
})

describe('#73 unicode response content test', (report, done) => {
  let expect = '中文!檔案\\u00測試 ABCDE 測試'
  RNFetchBlob.config({ fileCache : true })
    .fetch('GET', `${TEST_SERVER_URL}/public/utf8-dummy`, {
      method : 'GET'
    })
    .then((res) => res.readFile('utf8'))
    .then((data) => {
      report(
        <Assert key="data should correct"
          expect={expect}
          actual={data}/>)
      done()
    })
})

describe = RNTest.config({
  group : '0.9.0',
  run : true,
  expand : true,
  timeout : 24000
})

describe('request should not retry after timed out', (report, done) => {

  let count = 0
  let task = RNFetchBlob
    .fetch('GET', `${TEST_SERVER_URL}/timeout408/${Date.now()}`)
  task.then((res) => {
    report(<Assert key="request should not success" expect={true} actual={false}/>)
  })
  .catch(() => {
    task.cancel()
    count ++
  })
  setTimeout(() => {
    report(<Assert key="request does not retry" expect={1} actual={count}/>)
    done()
  }, 12000)
})

describe = RNTest.config({
  group : '0.9.0',
  run : true,
  expand : true,
  timeout : 65000
})

describe('long live download or upload task won\'t timeout', (report, done) => {

  RNFetchBlob.config({timeout : 0})
  .fetch('GET', `${TEST_SERVER_URL}/long/`)
  .then((res) => {
    report(
      <Assert key="download not terminated" expect={true} actual={true}/>,
      <Info key={res.text()}/>)
    done()
  })

})


text:
@interface PodsDummy_Pods_HSLUpdateChecker : NSObject
{
}

@end


text:
<?php

declare(strict_types=1);

namespace PhpMob\CoreBundle\EventListener;

use PhpMob\CoreBundle\Context\SystemSettingContext;
use PhpMob\CoreBundle\Event\Emails;
use PhpMob\CoreBundle\Model\WebUserInterface;
use Sylius\Bundle\UserBundle\EventListener\MailerListener;
use Sylius\Component\Mailer\Sender\SenderInterface;
use Sylius\Component\Resource\Exception\UnexpectedTypeException;
use Symfony\Component\EventDispatcher\GenericEvent;
use Webmozart\Assert\Assert;

/**
 * @author Ishmael Doss <nukboon@gmail.com>
 */
final class UserMailerListener extends MailerListener
{
    /**
     * @var SystemSettingContext
     */
    private $systemSettingContext;

    /**
     * @param SenderInterface $emailSender
     * @param SystemSettingContext $systemSettingContext
     */
    public function __construct(SenderInterface $emailSender, SystemSettingContext $systemSettingContext)
    {
        parent::__construct($emailSender);

        $this->systemSettingContext = $systemSettingContext;
    }

    /**
     * @param GenericEvent $event
     *
     * @throws UnexpectedTypeException
     */
    public function sendUserRegistrationEmail(GenericEvent $event)
    {
        if ($this->systemSettingContext->get('security.user_verification')) {
            return;
        }

        $user = $event->getSubject();

        Assert::isInstanceOf($user, WebUserInterface::class);

        $this->emailSender->send(Emails::USER_REGISTRATION, [$user->getEmail()], ['user' => $user]);
    }
}


text:
#ifndef _IAS_QS_Workers_Proc_Logic_Proxy_H_
#define _IAS_QS_Workers_Proc_Logic_Proxy_H_

#include <commonlib/commonlib.h>

#include <org/invenireaude/qsystem/workers/logic/Proxy.h>

#include "LogicBase.h"
namespace IAS {
namespace QS {
namespace Workers {
namespace Proc {
namespace Logic {

/*************************************************************************/
/** The Proxy class.
 *
 */
class Proxy : public LogicBase {
public:

	virtual ~Proxy() throw();

protected:
	Proxy(const ::org::invenireaude::qsystem::workers::logic::Proxy* dmParameters,
			  WCM::WorkContextManager* pWorkContextManager);

	friend class Factory<Proxy>;

	virtual void computeDM(::org::invenireaude::qsystem::workers::Ext::ContextPtr& dmContext,
							DM::DataObjectPtr& dmData);

	virtual void computeRaw(::org::invenireaude::qsystem::workers::Ext::ContextPtr& dmContext,
								API::Message* pMessage);

};

/*************************************************************************/
}
}
}
}
}

#endif /* _IAS_QS_Workers_Proc_Logic_Proxy_H_ */


text:
use strict;
use warnings;

use Bio::EnsEMBL::Registry;
use Bio::EnsEMBL::Compara::Utils::SpeciesTree;

#
# This script creates a species tree for a given list of species using
# the NCBITaxon facilities of the Compara database
#

my $reg = 'Bio::EnsEMBL::Registry';

$reg->load_registry_from_db(
  -host=>'ensembldb.ensembl.org',
  -user=>'anonymous',
);

my $taxonDBA = $reg->get_adaptor("Multi", "compara", "NCBITaxon");

my @list_of_species = ("Homo sapiens","Mus musculus","Drosophila melanogaster","Caenorhabditis elegans");

my @taxon_ids = ();
foreach my $species_name (@list_of_species) {
  my $taxon = $taxonDBA->fetch_node_by_name($species_name);
  unless ($taxon) {
      warn "Cannot find '$species_name' in the NCBI taxonomy tables\n";
      next;
  }
  push @taxon_ids, $taxon->dbID;
}

my $root = Bio::EnsEMBL::Compara::Utils::SpeciesTree->create_species_tree(
    -COMPARA_DBA    => $reg->get_DBAdaptor("Multi", "compara"),
    -SPECIES_SET    => undef,
    -NO_PREVIOUS    => 1,
    -RETURN_NCBI_TREE       => 1,
    -EXTRATAXON_SEQUENCED   => \@taxon_ids,
);

print "MRCA is ", $root->name, "\t", $root->taxon_id, "\n";
$root->print_tree(10);


text:
<?php

namespace phpbb\db\migration\data\v310;

class softdelete_p1 extends \phpbb\db\migration\migration
{
	public function effectively_installed()
	{
		return $this->db_tools->sql_column_exists($this->table_prefix . 'posts', 'post_visibility');
	}

	static public function depends_on()
	{
		return array('\phpbb\db\migration\data\v310\dev');
	}

	public function update_schema()
	{
		return array(
			'add_columns'		=> array(
				$this->table_prefix . 'forums'		=> array(
					'forum_posts_approved'		=> array('UINT', 0),
					'forum_posts_unapproved'	=> array('UINT', 0),
					'forum_posts_softdeleted'	=> array('UINT', 0),
					'forum_topics_approved'		=> array('UINT', 0),
					'forum_topics_unapproved'	=> array('UINT', 0),
					'forum_topics_softdeleted'	=> array('UINT', 0),
				),
				$this->table_prefix . 'posts'		=> array(
					'post_visibility'		=> array('TINT:3', 0),
					'post_delete_time'		=> array('TIMESTAMP', 0),
					'post_delete_reason'	=> array('STEXT_UNI', ''),
					'post_delete_user'		=> array('UINT', 0),
				),
				$this->table_prefix . 'topics'		=> array(
					'topic_visibility'		=> array('TINT:3', 0),
					'topic_delete_time'		=> array('TIMESTAMP', 0),
					'topic_delete_reason'	=> array('STEXT_UNI', ''),
					'topic_delete_user'		=> array('UINT', 0),
					'topic_posts_approved'		=> array('UINT', 0),
					'topic_posts_unapproved'	=> array('UINT', 0),
					'topic_posts_softdeleted'	=> array('UINT', 0),
				),
			),
			'add_index'		=> array(
				$this->table_prefix . 'posts'		=> array(
					'post_visibility'		=> array('post_visibility'),
				),
				$this->table_prefix . 'topics'		=> array(
					'topic_visibility'		=> array('topic_visibility'),
					'forum_vis_last'		=> array('forum_id', 'topic_visibility', 'topic_last_post_id'),
				),
			),
		);
	}

	public function revert_schema()
	{
		return array(
			'drop_columns'		=> array(
				$this->table_prefix . 'forums'		=> array(
					'forum_posts_approved',
					'forum_posts_unapproved',
					'forum_posts_softdeleted',
					'forum_topics_approved',
					'forum_topics_unapproved',
					'forum_topics_softdeleted',
				),
				$this->table_prefix . 'posts'		=> array(
					'post_visibility',
					'post_delete_time',
					'post_delete_reason',
					'post_delete_user',
				),
				$this->table_prefix . 'topics'		=> array(
					'topic_visibility',
					'topic_delete_time',
					'topic_delete_reason',
					'topic_delete_user',
					'topic_posts_approved',
					'topic_posts_unapproved',
					'topic_posts_softdeleted',
				),
			),
			'drop_keys'		=> array(
				$this->table_prefix . 'posts'		=> array('post_visibility'),
				$this->table_prefix . 'topics'	=> array('topic_visibility', 'forum_vis_last'),
			),
		);
	}

	public function update_data()
	{
		return array(
			array('custom', array(array($this, 'update_post_visibility'))),
			array('custom', array(array($this, 'update_topic_visibility'))),
			array('custom', array(array($this, 'update_topics_post_counts'))),
			array('custom', array(array($this, 'update_forums_topic_and_post_counts'))),

			array('permission.add', array('f_softdelete', false)),
			array('permission.add', array('m_softdelete', false)),
		);
	}

	public function update_post_visibility()
	{
		$sql = 'UPDATE ' . $this->table_prefix . 'posts
			SET post_visibility = post_approved';
		$this->sql_query($sql);
	}

	public function update_topic_visibility()
	{
		$sql = 'UPDATE ' . $this->table_prefix . 'topics
			SET topic_visibility = topic_approved';
		$this->sql_query($sql);
	}

	public function update_topics_post_counts()
	{
		/*
		* Using sql_case here to avoid "BIGINT UNSIGNED value is out of range" errors.
		* As we update all topics in 2 queries, one broken topic would stop the conversion
		* for all topics and the surpressed error will cause the admin to not even notice it.
		*/
		$sql = 'UPDATE ' . $this->table_prefix . 'topics
			SET topic_posts_approved = topic_replies + 1,
				topic_posts_unapproved = ' . $this->db->sql_case('topic_replies_real > topic_replies', 'topic_replies_real - topic_replies', '0') . '
			WHERE topic_visibility = ' . ITEM_APPROVED;
		$this->sql_query($sql);

		$sql = 'UPDATE ' . $this->table_prefix . 'topics
			SET topic_posts_approved = 0,
				topic_posts_unapproved = (' . $this->db->sql_case('topic_replies_real > topic_replies', 'topic_replies_real - topic_replies', '0') . ') + 1
			WHERE topic_visibility = ' . ITEM_UNAPPROVED;
		$this->sql_query($sql);
	}

	public function update_forums_topic_and_post_counts($start)
	{
		$start = (int) $start;
		$limit = 10;
		$converted_forums = 0;

		if (!$start)
		{
			// Preserve the forum_posts value for link forums as it represents redirects.
			$sql = 'UPDATE ' . $this->table_prefix . 'forums
				SET forum_posts_approved = forum_posts
				WHERE forum_type = ' . FORUM_LINK;
			$this->db->sql_query($sql);
		}

		$sql = 'SELECT forum_id, topic_visibility, COUNT(topic_id) AS sum_topics, SUM(topic_posts_approved) AS sum_posts_approved, SUM(topic_posts_unapproved) AS sum_posts_unapproved
			FROM ' . $this->table_prefix . 'topics
			GROUP BY forum_id, topic_visibility
			ORDER BY forum_id, topic_visibility';
		$result = $this->db->sql_query_limit($sql, $limit, $start);

		$update_forums = array();
		while ($row = $this->db->sql_fetchrow($result))
		{
			$converted_forums++;

			$forum_id = (int) $row['forum_id'];
			if (!isset($update_forums[$forum_id]))
			{
				$update_forums[$forum_id] = array(
					'forum_posts_approved'		=> 0,
					'forum_posts_unapproved'	=> 0,
					'forum_topics_approved'		=> 0,
					'forum_topics_unapproved'	=> 0,
				);
			}

			$update_forums[$forum_id]['forum_posts_approved'] += (int) $row['sum_posts_approved'];
			$update_forums[$forum_id]['forum_posts_unapproved'] += (int) $row['sum_posts_unapproved'];

			$update_forums[$forum_id][(($row['topic_visibility'] == ITEM_APPROVED) ? 'forum_topics_approved' : 'forum_topics_unapproved')] += (int) $row['sum_topics'];
		}
		$this->db->sql_freeresult($result);

		foreach ($update_forums as $forum_id => $forum_data)
		{
			$sql = 'UPDATE ' . FORUMS_TABLE . '
				SET ' . $this->db->sql_build_array('UPDATE', $forum_data) . '
				WHERE forum_id = ' . $forum_id;
			$this->sql_query($sql);
		}

		if ($converted_forums < $limit)
		{
			// There are no more topics, we are done
			return;
		}

		// There are still more topics to query, return the next start value
		return $start + $limit;
	}
}


text:
if [[ $1 = 'start' ]]
then
  docker-compose up --build -d
  docker-compose exec app npm run seed
elif [[ $1 = 'stop' ]]
then
  docker-compose down
elif [[ $1 = 'test' ]]
then
  docker-compose up --build -d
  docker-compose exec app npm test
  docker-compose down
else
  echo "Valid commands: start|test|stop"
fi


text: <FunctionalComponent onComponentDidMount={ mounted } />


text:
'use strict';
const path = require('path'),
  db = require(path.resolve('./config/lib/sequelize')),
  response = require(path.resolve("./config/responses.js")),
  winston = require(path.resolve('./config/lib/winston')),
  crypto = require('crypto'),
  CryptoJS = require('crypto-js'),
  models = db.models;

//returns a random salt
function makesalt() {
  return crypto.randomBytes(16).toString('base64');
}

//returns encrypted value of the plaintext password, with the given salt
function encryptPassword(password, salt) {
  if (!password || !salt)
    return '';
  salt = new Buffer(salt, 'base64');
  return crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha1').toString('base64'); //at least 640000 times is suggested, will see later
}

//compares db password with the password that the client sends, by encryting it with the db salt
function authenticate(plainTextPassword, salt, dbPassword) {
  return encryptPassword(plainTextPassword, salt) === dbPassword;
}

//used by customer_app/changepassword for the ios application
function pass_decrypt(encryptedText, key) {
  var C = CryptoJS;
  encryptedText = encryptedText.replace(/(\r\n|\n|\r)/gm, "");
  //encryptedText = encryptedText.replace(/\\n|\\r|\n|\r/g, "");

  encryptedText = C.enc.Base64.parse(encryptedText);
  key = C.enc.Utf8.parse(key);
  var aes = C.algo.AES.createDecryptor(key, {
    mode: C.mode.CBC,
    padding: C.pad.Pkcs7,
    iv: key
  });
  var decrypted = aes.finalize(encryptedText);
  try {
    return C.enc.Utf8.stringify(decrypted);
  } catch (err) {
    return "error";
  }
};

function encryptPasswordAsync(password, salt, callback) {
  if (!password || !salt) {
    callback('');
    return;
  }

  salt = new Buffer(salt, 'base64');
  crypto.pbkdf2(password, salt, 10000, 64, 'sha1', function (err, derivedKey) {
    if (err) {
      callback('');
      return;
    }

    callback(derivedKey.toString('base64'))
  });
}

function authenticateAsync(password, salt, hashedPassword, callback) {
  encryptPasswordAsync(password, salt, function (hash) {
    if (hash === hashedPassword) {
      callback(true);
    } else {
      callback(false);
    }
  });
}

module.exports = {
  makesalt: makesalt,
  encryptPassword: encryptPassword,
  authenticate: authenticate,
  decryptPassword: pass_decrypt,
  encryptPasswordAsync: encryptPasswordAsync,
  authenticateAsync: authenticateAsync
}


text:
package com.rgi.geopackage.features.geometry.zm;

import com.rgi.geopackage.features.ByteOutputStream;
import com.rgi.geopackage.features.Contents;
import com.rgi.geopackage.features.GeometryType;
import org.junit.Test;

import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collection;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;

/**
 * @author Luke Lambert
 */
public class WkbPolygonZMTest
{
    /**
     * Test the constructor
     */
    @Test
    @SuppressWarnings("JUnitTestMethodWithNoAssertions")
    public void constructor()
    {
        new WkbPolygonZM(new LinearRingZM(new CoordinateZM(1.0, 0.0, 0.0, 0.0),
                                          new CoordinateZM(0.0, 1.0, 0.0, 0.0),
                                          new CoordinateZM(1.0, 1.0, 0.0, 0.0)),
                         new LinearRingZM(new CoordinateZM(0.5, 0.0, 0.0, 0.0),
                                          new CoordinateZM(0.0, 0.5, 0.0, 0.0),
                                          new CoordinateZM(0.5, 0.5, 0.0, 0.0)));
    }

    /**
     * Test the coordinate constructor
     */
    @Test
    @SuppressWarnings("JUnitTestMethodWithNoAssertions")
    public void coordinateConstructor()
    {
        new WkbPolygonZM(new LinearRingZM(new CoordinateZM(1.0, 0.0, 0.0, 0.0),
                                          new CoordinateZM(0.0, 1.0, 0.0, 0.0),
                                          new CoordinateZM(1.0, 1.0, 0.0, 0.0)),
                         Arrays.asList(new LinearRingZM(new CoordinateZM(0.5, 0.0, 0.0, 0.0),
                                                        new CoordinateZM(0.0, 0.5, 0.0, 0.0),
                                                        new CoordinateZM(0.5, 0.5, 0.0, 0.0))));
    }

    /**
     * Test the collection constructor for failure on a null coordinate
     */
    @Test(expected = IllegalArgumentException.class)
    public void constructorNullCollection()
    {
        new WkbPolygonZM(null);
    }

    /**
     * Test the collection constructor for failure on a null coordinate
     */
    @Test(expected = IllegalArgumentException.class)
    public void constructorNullCoordinate()
    {
        new WkbLineStringZM(Arrays.asList(new CoordinateZM(0.0, 0.0, 0.0, 0.0),
                                          new CoordinateZM(0.0, 0.0, 0.0, 0.0),
                                          null));
    }

    /**
     * Test equals
     */
    @Test
    public void testEquals()
    {
        final WkbPolygonZM polygon = new WkbPolygonZM(new LinearRingZM(new CoordinateZM(1.0, 0.0, 0.0, 0.0),
                                                                       new CoordinateZM(0.0, 1.0, 0.0, 0.0),
                                                                       new CoordinateZM(1.0, 1.0, 0.0, 0.0)),
                                                      new LinearRingZM(new CoordinateZM(0.5, 0.0, 0.0, 0.0),
                                                                       new CoordinateZM(0.0, 0.5, 0.0, 0.0),
                                                                       new CoordinateZM(0.5, 0.5, 0.0, 0.0)));

        //noinspection EqualsWithItself,SimplifiableJUnitAssertion
        assertTrue("Equals failed on self reference",
                   polygon.equals(polygon));
    }

    /**
     * Test equals with null
     */
    @Test
    @SuppressWarnings("ObjectEqualsNull")
    public void testEqualsWithNull()
    {
        final WkbPolygonZM polygon = new WkbPolygonZM(new LinearRingZM(new CoordinateZM(1.0, 0.0, 0.0, 0.0),
                                                                       new CoordinateZM(0.0, 1.0, 0.0, 0.0),
                                                                       new CoordinateZM(1.0, 1.0, 0.0, 0.0)),
                                                      new LinearRingZM(new CoordinateZM(0.5, 0.0, 0.0, 0.0),
                                                                       new CoordinateZM(0.0, 0.5, 0.0, 0.0),
                                                                       new CoordinateZM(0.5, 0.5, 0.0, 0.0)));

        //noinspection EqualsWithItself
        assertFalse("Equals should have failed on null comparison",
                    polygon.equals(null));
    }

    /**
     * Test equals with a different object type
     */
    @Test
    public void testEqualsWithDifferentObjectType()
    {
        final WkbPolygonZM polygon = new WkbPolygonZM(new LinearRingZM(new CoordinateZM(1.0, 0.0, 0.0, 0.0),
                                                                       new CoordinateZM(0.0, 1.0, 0.0, 0.0),
                                                                       new CoordinateZM(1.0, 1.0, 0.0, 0.0)),
                                                      new LinearRingZM(new CoordinateZM(0.5, 0.0, 0.0, 0.0),
                                                                       new CoordinateZM(0.0, 0.5, 0.0, 0.0),
                                                                       new CoordinateZM(0.5, 0.5, 0.0, 0.0)));

        //noinspection EqualsWithItself,UnnecessaryBoxing,EqualsBetweenInconvertibleTypes
        assertFalse("Equals should fail on a different object type",
                    polygon.equals(Integer.valueOf(0)));
    }

    /**
     * Test equals
     */
    @Test
    public void testEqualsTrue()
    {
        final WkbPolygonZM polygon1 = new WkbPolygonZM(new LinearRingZM(new CoordinateZM(1.0, 0.0, 0.0, 0.0),
                                                                        new CoordinateZM(0.0, 1.0, 0.0, 0.0),
                                                                        new CoordinateZM(1.0, 1.0, 0.0, 0.0)),
                                                       new LinearRingZM(new CoordinateZM(0.5, 0.0, 0.0, 0.0),
                                                                        new CoordinateZM(0.0, 0.5, 0.0, 0.0),
                                                                        new CoordinateZM(0.5, 0.5, 0.0, 0.0)));
        final WkbPolygonZM polygon2 = new WkbPolygonZM(new LinearRingZM(new CoordinateZM(1.0, 0.0, 0.0, 0.0),
                                                                        new CoordinateZM(0.0, 1.0, 0.0, 0.0),
                                                                        new CoordinateZM(1.0, 1.0, 0.0, 0.0)),
                                                       new LinearRingZM(new CoordinateZM(0.5, 0.0, 0.0, 0.0),
                                                                        new CoordinateZM(0.0, 0.5, 0.0, 0.0),
                                                                        new CoordinateZM(0.5, 0.5, 0.0, 0.0)));

        //noinspection SimplifiableJUnitAssertion
        assertTrue("Equals failed to return true",
                   polygon1.equals(polygon2));
    }

    /**
     * Test hashCode()
     */
    @Test
    public void testHashCode()
    {
        final WkbPolygonZM polygon = new WkbPolygonZM(new LinearRingZM(new CoordinateZM(1.0, 0.0, 0.0, 0.0),
                                                                       new CoordinateZM(0.0, 1.0, 0.0, 0.0),
                                                                       new CoordinateZM(1.0, 1.0, 0.0, 0.0)),
                                                      new LinearRingZM(new CoordinateZM(0.5, 0.0, 0.0, 0.0),
                                                                       new CoordinateZM(0.0, 0.5, 0.0, 0.0),
                                                                       new CoordinateZM(0.5, 0.5, 0.0, 0.0)));

        assertEquals("Hash code failed",
                     1915653119,
                     polygon.hashCode());
    }

    /**
     * Test isEmpty()
     */
    @Test
    public void testIsEmpty()
    {
        final WkbPolygonZM polygon = new WkbPolygonZM(new LinearRingZM(new CoordinateZM(1.0, 0.0, 0.0, 0.0),
                                                                       new CoordinateZM(0.0, 1.0, 0.0, 0.0),
                                                                       new CoordinateZM(1.0, 1.0, 0.0, 0.0)),
                                                      new LinearRingZM(new CoordinateZM(0.5, 0.0, 0.0, 0.0),
                                                                       new CoordinateZM(0.0, 0.5, 0.0, 0.0),
                                                                       new CoordinateZM(0.5, 0.5, 0.0, 0.0)));

        assertFalse("isEmpty failed",
                    polygon.isEmpty());

        final WkbPolygonZM emptyPolygon = new WkbPolygonZM(new LinearRingZM());

        assertTrue("isEmpty failed",
                   emptyPolygon.isEmpty());
    }

    /**
     * Test getContents()
     */
    @Test
    public void getContents()
    {
        final WkbPolygonZM polygon = new WkbPolygonZM(new LinearRingZM(new CoordinateZM(1.0, 0.0, 0.0, 0.0),
                                                                       new CoordinateZM(0.0, 1.0, 0.0, 0.0),
                                                                       new CoordinateZM(1.0, 1.0, 0.0, 0.0)),
                                                      new LinearRingZM(new CoordinateZM(0.5, 0.0, 0.0, 0.0),
                                                                       new CoordinateZM(0.0, 0.5, 0.0, 0.0),
                                                                       new CoordinateZM(0.5, 0.5, 0.0, 0.0)));

        assertSame("getContents failed",
                   Contents.NotEmpty,
                   polygon.getContents());

        final WkbPolygonZM emptyPolygon = new WkbPolygonZM(new LinearRingZM());

        assertSame("getContents failed",
                   Contents.Empty,
                   emptyPolygon.getContents());
    }

    /**
     * Test createEnvelopeZM()
     */
    @Test
    public void createEnvelopeZM()
    {
        final double x = 1.0;
        final double y = 1.0;
        final double z = 1.0;
        final double m = 1.0;

        final WkbPolygonZM polygon = new WkbPolygonZM(new LinearRingZM(new CoordinateZM(x, y, z, m),
                                                                       new CoordinateZM(x, y, z, m),
                                                                       new CoordinateZM(x, y, z, m)));

        final EnvelopeZM envelope = polygon.createEnvelopeZM();

        assertEquals("createEnvelope failed",
                     x,
                     envelope.getMinimumX(),
                     0.0);

        assertEquals("createEnvelope failed",
                     x,
                     envelope.getMaximumX(),
                     0.0);

        assertEquals("createEnvelope failed",
                     y,
                     envelope.getMinimumY(),
                     0.0);

        assertEquals("createEnvelope failed",
                     y,
                     envelope.getMaximumY(),
                     0.0);

        assertEquals("createEnvelope failed",
                     z,
                     envelope.getMinimumZ(),
                     0.0);

        assertEquals("createEnvelope failed",
                     z,
                     envelope.getMaximumZ(),
                     0.0);

        assertEquals("createEnvelope failed",
                     m,
                     envelope.getMinimumM(),
                     0.0);

        assertEquals("createEnvelope failed",
                     m,
                     envelope.getMaximumM(),
                     0.0);

        final EnvelopeZM emptyEnvelope = new WkbPolygonZM(new LinearRingZM()).createEnvelopeZM();

        assertTrue("createemptyEnvelope failed",
                   Double.isNaN(emptyEnvelope.getMinimumX()));

        assertTrue("createemptyEnvelope failed",
                   Double.isNaN(emptyEnvelope.getMaximumX()));

        assertTrue("createemptyEnvelope failed",
                   Double.isNaN(emptyEnvelope.getMinimumY()));

        assertTrue("createemptyEnvelope failed",
                   Double.isNaN(emptyEnvelope.getMaximumY()));

        assertTrue("createemptyEnvelope failed",
                   Double.isNaN(emptyEnvelope.getMinimumZ()));

        assertTrue("createemptyEnvelope failed",
                   Double.isNaN(emptyEnvelope.getMaximumZ()));

        assertTrue("createEnvelope failed",
                   Double.isNaN(emptyEnvelope.getMinimumM()));

        assertTrue("createEnvelope failed",
                   Double.isNaN(emptyEnvelope.getMaximumM()));
    }

    /**
     * Test createEnvelope()
     */
    @Test
    public void createEnvelope()
    {
        final double x = 1.0;
        final double y = 1.0;
        final double z = 1.0;
        final double m = 1.0;

        final WkbPolygonZM polygon = new WkbPolygonZM(new LinearRingZM(new CoordinateZM(x, y, z, m),
                                                                       new CoordinateZM(x, y, z, m),
                                                                       new CoordinateZM(x, y, z, m)));

        @SuppressWarnings("CastToConcreteClass")
        final EnvelopeZM envelope = (EnvelopeZM)polygon.createEnvelope();

        assertEquals("createEnvelope failed",
                     x,
                     envelope.getMinimumX(),
                     0.0);

        assertEquals("createEnvelope failed",
                     x,
                     envelope.getMaximumX(),
                     0.0);

        assertEquals("createEnvelope failed",
                     y,
                     envelope.getMinimumY(),
                     0.0);

        assertEquals("createEnvelope failed",
                     y,
                     envelope.getMaximumY(),
                     0.0);

        assertEquals("createEnvelope failed",
                     z,
                     envelope.getMinimumZ(),
                     0.0);

        assertEquals("createEnvelope failed",
                     z,
                     envelope.getMaximumZ(),
                     0.0);

        assertEquals("createEnvelope failed",
                     m,
                     envelope.getMinimumM(),
                     0.0);

        assertEquals("createEnvelope failed",
                     m,
                     envelope.getMaximumM(),
                     0.0);

        @SuppressWarnings("CastToConcreteClass")
        final EnvelopeZM emptyEnvelope = (EnvelopeZM)new WkbPolygonZM(new LinearRingZM()).createEnvelope();

        assertTrue("createemptyEnvelope failed",
                   Double.isNaN(emptyEnvelope.getMinimumX()));

        assertTrue("createemptyEnvelope failed",
                   Double.isNaN(emptyEnvelope.getMaximumX()));

        assertTrue("createemptyEnvelope failed",
                   Double.isNaN(emptyEnvelope.getMinimumY()));

        assertTrue("createemptyEnvelope failed",
                   Double.isNaN(emptyEnvelope.getMaximumY()));

        assertTrue("createemptyEnvelope failed",
                   Double.isNaN(emptyEnvelope.getMinimumZ()));

        assertTrue("createemptyEnvelope failed",
                   Double.isNaN(emptyEnvelope.getMaximumZ()));

        assertTrue("createEnvelope failed",
                   Double.isNaN(emptyEnvelope.getMinimumM()));

        assertTrue("createEnvelope failed",
                   Double.isNaN(emptyEnvelope.getMaximumM()));
    }

    /**
     * Test writeWellKnownBinary
     */
    @Test
    public void writeWellKnownText()
    {
        try(final ByteOutputStream output = new ByteOutputStream())
        {
            final WkbPolygonZM polygon = new WkbPolygonZM(new LinearRingZM(new CoordinateZM(1.0, 0.0, 0.0, 0.0),
                                                                           new CoordinateZM(0.0, 1.0, 0.0, 0.0),
                                                                           new CoordinateZM(1.0, 1.0, 0.0, 0.0)),
                                                          new LinearRingZM(new CoordinateZM(0.5, 0.0, 0.0, 0.0),
                                                                           new CoordinateZM(0.0, 0.5, 0.0, 0.0),
                                                                           new CoordinateZM(0.5, 0.5, 0.0, 0.0)));
            polygon.writeWellKnownBinary(output);

            final ByteBuffer byteBuffer = ByteBuffer.wrap(output.array());

            final WkbPolygonZM found = WkbPolygonZM.readWellKnownBinary(byteBuffer);

            assertEquals("writeWellKnownBinary failed",
                         polygon,
                         found);
        }
    }

    /**
     * Test getGeometryTypeName()
     */
    @Test
    public void getGeometryTypeName()
    {
        assertEquals("getGeometryTypeName() returned the wrong value",
                     GeometryType.Polygon.toString(),
                     new WkbPolygonZM(new LinearRingZM()).getGeometryTypeName());
    }

    /**
     * Test rings
     */
    @Test
    public void rings()
    {
        final LinearRingZM exteriorRing = new LinearRingZM(new CoordinateZM(1.0, 0.0, 0.0, 0.0),
                                                           new CoordinateZM(0.0, 1.0, 0.0, 0.0),
                                                           new CoordinateZM(1.0, 1.0, 0.0, 0.0));

        final Collection<LinearRingZM> interiorRing = Arrays.asList(new LinearRingZM(new CoordinateZM(0.5, 0.0, 0.0, 0.0),
                                                                                new CoordinateZM(0.0, 0.5, 0.0, 0.0),
                                                                                new CoordinateZM(0.5, 0.5, 0.0, 0.0)));

        final WkbPolygonZM polygon = new WkbPolygonZM(exteriorRing, interiorRing);

        assertEquals("getExteriorRing() returned the wrong value",
                     exteriorRing,
                     polygon.getExteriorRing());

        assertEquals("getInteriorRings() returned the wrong value",
                     interiorRing,
                     polygon.getInteriorRings());
    }

    /**
     * Test writeWellKnownBinary with no rings
     */
    @Test
    public void writeWellKnownTextNoRings()
    {
        try(final ByteOutputStream output = new ByteOutputStream())
        {
            final WkbPolygonZM polygon = new WkbPolygonZM(new LinearRingZM());
            polygon.writeWellKnownBinary(output);

            final ByteBuffer byteBuffer = ByteBuffer.wrap(output.array());

            final WkbPolygonZM found = WkbPolygonZM.readWellKnownBinary(byteBuffer);

            assertEquals("writeWellKnownBinary failed",
                         polygon,
                         found);
        }
    }
}