text:
	#define pk_hs_hash(dest, src) CC_SHA256((const void*) src, HANDSHAKE_SIZE, (void*) dest);
#else
	#define pk_hs_hash(dest, src) SHA256((const void*) src, HANDSHAKE_SIZE, (void*) dest);
#endif

#pragma mark Packet Transmission/Reception

ssize_t pk_send(int sockfd, pk_keepalive_t * pk, int flags) {
	ssize_t retv;

	if (!pk)
		return 0;

	hton_pk(pk);
	retv = send(sockfd, pk, pk->size, flags);
	ntoh_pk(pk);

	if (retv < 0) {
		perror("send");
	} else if (retv != pk->size) {
		fprintf(stderr, "%zd bytes of %d bytes sent\n", retv, pk->size);
		retv = -1;
	}

	return retv;
}

static void hton_addr(struct _pk_address * addr) {
	for (int i = 0; i < 4; i++)
		addr->data[i] = htonl(addr->data[i]);
}

void hton_pk(pk_keepalive_t * pk) {
	pk->netver = htonl(pk->netver);

	switch (pk->type) {
		case PK_ADVERTIZE:
			((pk_advertize_t *)pk)->port = htons(((pk_advertize_t *)pk)->port);
			((pk_advertize_t *)pk)->reserved = htonl(((pk_advertize_t *)pk)->reserved);
			break;
		case PK_SERVICE:
			hton_addr(&(((pk_service_t *)pk)->address));
			((pk_service_t *)pk)->port = htons(((pk_service_t *)pk)->port);
			((pk_service_t *)pk)->reserved = htonl(((pk_service_t *)pk)->reserved);
			break;
		default:
			break;
	}
}

ssize_t pk_recv(int sockfd, char buf[PACKET_SIZE_MAX], unsigned int timeout, int flags) {
	ssize_t bytes = 0, total = 0;
	pk_keepalive_t * pk = (pk_keepalive_t *)buf;

	buf[0] = 0;
	alarm(timeout);

	total += bytes = recv(sockfd, buf, 1, flags);

	if (bytes < 0)
		goto error;
	else if (bytes == 0) {
		fprintf(stderr, "Connection closed\n");
		goto fail;
	} else if (buf[0] != (char)PACKET_SIG) {
		fprintf(stderr, "Missing packet signature\n");
		goto fail;
	}

	total += bytes = recv(sockfd, buf + total, sizeof(pk_keepalive_t) - total, flags);

	if (bytes < 0)
		goto error;

	if (pk->size == total)
		goto done;
	else if (pk->size < total)
		goto failbytes;

	total += bytes = recv(sockfd, buf + total, pk->size - total, flags);

	if (bytes < 0)
		goto error;
	else if (total != pk->size)
		goto failbytes;

done:
	ntoh_pk(pk);
	if (pk->type == PK_ADVERTIZE || pk->type == PK_SERVICE) {
		struct _pk_string * str = (pk->type == PK_ADVERTIZE) ? &((pk_advertize_t *)pk)->name : &((pk_service_t *)pk)->name;

		if (str->length > 1 || (str->data[0] != '-' && str->data[0] != '+'))
			str->data[str->length - 1] = 0;
	}
exit:
	alarm(0);
	return total;

error:
	perror("recv");
	goto exit;

failbytes:
	fprintf(stderr, "%ld bytes received but packet size is %d bytes\n", bytes, pk->size);
fail:
	total = -1;
	goto exit;
}

static void ntoh_addr(struct _pk_address * addr) {
	for (int i = 0; i < 4; i++)
		addr->data[i] = ntohl(addr->data[i]);
}

void ntoh_pk(pk_keepalive_t * pk) {
	pk->netver = ntohl(pk->netver);

	switch (pk->type) {
		case PK_ADVERTIZE:
			((pk_advertize_t *)pk)->port = ntohs(((pk_advertize_t *)pk)->port);
			((pk_advertize_t *)pk)->reserved = ntohl(((pk_advertize_t *)pk)->reserved);
			break;
		case PK_SERVICE:
			ntoh_addr(&(((pk_service_t *)pk)->address));
			((pk_service_t *)pk)->port = ntohs(((pk_service_t *)pk)->port);
			((pk_service_t *)pk)->reserved = ntohl(((pk_service_t *)pk)->reserved);
			break;
		default:
			break;
	}
}

#pragma mark - Generic Network Functions

int sqlite3_bind_address(sqlite3_stmt * stmt, int index, struct sockaddr * sa) {
	return sqlite3_bind_blob(stmt, index, &sa->sa_data, sa->sa_family == AF_INET6 ? 16 : 4, SQLITE_TRANSIENT);
}

void * get_in_addr(struct sockaddr * sa) {
	if (sa->sa_family == AF_INET)
		return &(((struct sockaddr_in*)sa)->sin_addr);
	return &(((struct sockaddr_in6*)sa)->sin6_addr);
}

const char * get_port_service_name(int port, const char * proto) {
	struct servent * serv = getservbyport(htons(port), proto);
	return serv ? serv->s_name : NULL;
}

int listen_socket(const char * hostname, const char * servname, int backlog, int * sockfd) {
	int retv, yes;
	struct addrinfo hints, *servinfo, *p;

	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_PASSIVE;

	if ((retv = getaddrinfo(hostname, servname, &hints, &servinfo))) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(retv));
		return 1;
	}

	for (p = servinfo; p; p = p->ai_next) {
		char s[INET6_ADDRSTRLEN];
		inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s);
		printf("binding to %s\n", s);

		if ((*sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) < 0) {
			perror("server: socket");
			continue;
		}

		if (setsockopt(*sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) < 0) {
			perror("setsockopt");
			return 1;
		}

		if (bind(*sockfd, p->ai_addr, p->ai_addrlen) < 0) {
			close(*sockfd);
			perror("server: bind");
			continue;
		}

		break;
	}

	if (!p)  {
		fprintf(stderr, "server: failed to bind\n");
		return 2;
	}

	freeaddrinfo(servinfo);

	if (listen(*sockfd, backlog) == -1) {
		close(*sockfd);
		perror("listen");
		return 1;
	}

	return 0;
}

int connect_socket(const char * hostname, const char * servname, int * sockfd) {
	int retv;
	struct addrinfo hints, *servinfo, *p;

	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_PASSIVE;

	if ((retv = getaddrinfo(hostname, servname, &hints, &servinfo))) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(retv));
		return 1;
	}

	for (p = servinfo; p; p = p->ai_next) {
		char s[INET6_ADDRSTRLEN];
		inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s);
		printf("connecting to %s\n", s);

		if ((*sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) < 0) {
			perror("server: socket");
			continue;
		}

        if (connect(*sockfd, p->ai_addr, p->ai_addrlen) < 0) {
            close(*sockfd);
            perror("client: connect");
            continue;
        }

		break;
	}

	if (!p)  {
		fprintf(stderr, "client: failed to connect\n");
		return 2;
	}

	freeaddrinfo(servinfo);

	return 0;
}

#pragma mark - Packet Lifecycle

pk_keepalive_t * alloc_packet(unsigned long size) {
	if (size > PACKET_SIZE_MAX)
		return 0;

	pk_keepalive_t * pk = calloc(1, size);
	if (!pk) {
		perror("calloc");
		return pk;
	}

	pk->size = (uint8_t)size;

	return pk;
}

void init_packet(pk_keepalive_t * pk, pk_type_t type) {
	pk->signature = 0xB6;

	pk->version[0] = MAJOR_VERSION;
	pk->version[1] = MINOR_VERSION;
	pk->version[2] = REVISION;
	pk->version[3] = SUBREVISION;

	pk->netver = NET_VER;

	pk->type = type;
}

void free_packet(pk_keepalive_t * pk) {
	free(pk);
}

#pragma mark - Packet Helper Functions

static void pkcpy_string(struct _pk_string * dest, const char * src) {
	dest->length = (uint8_t)strlen(src) + 1;
	strcpy((char *)&dest->data, src);
}

static void pkcpy_address(struct _pk_address * dest, struct sockaddr * src) {
	dest->family = src->sa_family;

	for (int i = 0; i < 4 && i < src->sa_len; i++)
		dest->data[i] = src->sa_data[i];
}

#pragma mark - Packet Construction

pk_keepalive_t * make_pk_keepalive(pk_type_t type) {
	pk_keepalive_t * pk = alloc_packet(sizeof(pk_keepalive_t));
	if (!pk)
		return pk;

	init_packet(pk, type);

	return pk;
}

pk_handshake_t * make_pk_handshake(pk_handshake_t * recv) {
	pk_handshake_t * hs = (pk_handshake_t *)alloc_packet(sizeof(pk_handshake_t));
	if (!hs)
		return hs;

	init_packet((pk_keepalive_t *)hs, PK_HANDSHAKE);

	if (!recv) {
		hs->step = PK_HS_INITIAL;
		_random(&hs->data, HANDSHAKE_SIZE);
		pk_hs_hash((void *)&hs->hash, &hs->data);
	} else {
		switch (recv->step) {
			case PK_HS_INITIAL:
				hs->step = PK_HS_ACKNOWLEDGE;
				break;
			case PK_HS_ACKNOWLEDGE:
				hs->step = PK_HS_FINAL;
				break;
			default:
				free(hs);
				return NULL;
				break;
		}
		memcpy(&hs->data, &recv->hash, HANDSHAKE_SIZE);
		pk_hs_hash((void *)&hs->hash, &hs->data);
	}

	return hs;
}

pk_advertize_t * make_pk_advertize(unsigned short port, const char * name) {
	pk_advertize_t * ad = (pk_advertize_t *)alloc_packet(sizeof(pk_advertize_t) + strlen(name) + 1);
	if (!ad)
		return ad;

	init_pk_advertize(ad, port, name);

	return ad;
}

pk_service_t * make_pk_service(struct sockaddr * address, unsigned short port, const char * name) {
	pk_service_t * serv = (pk_service_t *)alloc_packet(sizeof(pk_advertize_t) + strlen(name) + 1);
	if (!serv)
		return serv;

	init_pk_service(serv, address, port, name);

	return serv;
}

void init_pk_advertize(pk_advertize_t * ad, unsigned short port, const char * name) {
	ad->_super.size = sizeof(pk_advertize_t) + strlen(name) + 1;

	init_packet((pk_keepalive_t *)ad, PK_ADVERTIZE);

	ad->port = port;
	if (name) pkcpy_string(&ad->name, name);
}

void init_pk_service(pk_service_t * serv, struct sockaddr * address, unsigned short port, const char * name) {
	serv->_super.size = sizeof(pk_service_t) + strlen(name) + 1;

	init_packet((pk_keepalive_t *)serv, PK_SERVICE);

	if (address) pkcpy_address(&serv->address, address);
	serv->port = port;
	if (name) pkcpy_string(&serv->name, name);
}

#pragma mark - Packet Checking

pk_error_code_t check_version(pk_keepalive_t * pk) {
	switch (pk->type) {
		case PK_BADSWVER:
			fprintf(stderr, "Server says incompatible software version (%d.%d-r%d.%d)", pk->version[0], pk->version[1], pk->version[2], pk->version[3]);
			return NET_ERR_SERVER_BAD_SOFTWARE_VERSION;
			break;
		case PK_BADNETVER:
			fprintf(stderr, "Server says incompatible network structure version (%d)", pk->netver);
			return NET_ERR_SERVER_BAD_NETWORK_VERSION;
			break;
		default:
			if (pk->version[0] != MAJOR_VERSION)
				return NET_ERR_BAD_MAJOR_VERSION;
			if (pk->version[1] != MINOR_VERSION)
				return NET_ERR_BAD_MINOR_VERSION;
			if (pk->version[2] != REVISION)
				return NET_ERR_BAD_REVISION;
			if (pk->version[3] != SUBREVISION)
				return NET_ERR_BAD_SUBREVISION;
			if (pk->netver != NET_VER)
				return NET_ERR_BAD_NETWORK_VERSION;
			break;
	}
	return SUCCESS;
}

pk_error_code_t check_handshake(pk_handshake_t * hs, pk_handshake_t * recv) {
	uint8_t check[HANDSHAKE_SIZE];

	if (hs) {
		if (memcmp(&hs->hash, &recv->data, HANDSHAKE_SIZE))
			return NET_ERR_HANDSHAKE_DATA_IS_NOT_HASH;
		if ((hs->step == PK_HS_INITIAL && recv->step != PK_HS_ACKNOWLEDGE) ||
			(hs->step == PK_HS_ACKNOWLEDGE && recv->step != PK_HS_FINAL))
			return NET_ERR_HANDSHAKE_BAD_SEQUENCE;
	} else if (recv->step != PK_HS_INITIAL)
		return NET_ERR_HANDSHAKE_BAD_SEQUENCE;

	pk_hs_hash(check, &recv->data);
	if (memcmp(&recv->hash, check, HANDSHAKE_SIZE))
		return NET_ERR_HANDSHAKE_INCORRECT_HASH;

	return 0;
}

#pragma mark - Handshaking

errcode send_handshake(int sockfd, int timeout) {
	errcode retv = 0;
	ssize_t bytes;
	char buf[256];
	pk_handshake_t * hs, * recvd = (pk_handshake_t *)buf;

	hs = make_pk_handshake(NULL);
	if ((retv = !hs))
		goto free;

	bytes = pk_send(sockfd, (pk_keepalive_t *)hs, 0);
	if ((retv = bytes < 0))
		goto free;

	bytes = pk_recv(sockfd, buf, timeout, 0);
	if ((retv = bytes < 0))
		goto free;

	retv = check_version((pk_keepalive_t *)recvd);
	if (retv)
		goto free;

	retv = check_handshake(hs, recvd);
	if (retv)
		goto free;

	free_packet((pk_keepalive_t *)hs);

	hs = make_pk_handshake(recvd);
	if ((retv = !hs))
		goto free;

	bytes = pk_send(sockfd, (pk_keepalive_t *)hs, 0);
	if ((retv = bytes < 0))
		goto free;

free:
	free_packet((pk_keepalive_t *)hs);
	return retv;
}

errcode recv_handshake(int sockfd, int timeout) {
	errcode retv = 0;
	ssize_t bytes;
	char buf[256];
	pk_handshake_t * hs = NULL, * recvd = (pk_handshake_t *)buf;

	bytes = pk_recv(sockfd, buf, timeout, 0);
	if ((retv = bytes < 0))
		goto free;

	retv = check_version((pk_keepalive_t *)recvd);
	if (retv)
		goto free;

	retv = check_handshake(hs, recvd);
	if (retv)
		goto free;

	hs = make_pk_handshake(recvd);
	if ((retv = !hs))
		goto free;

	bytes = pk_send(sockfd, (pk_keepalive_t *)hs, 0);
	if ((retv = bytes < 0))
		goto free;

	bytes = pk_recv(sockfd, buf, timeout, 0);
	if ((retv = bytes < 0))
		goto free;

	retv = check_version((pk_keepalive_t *)recvd);
	if (retv)
		goto free;

	retv = check_handshake(hs, recvd);
	if (retv)
		goto free;

free:
	free_packet((pk_keepalive_t *)hs);
	return retv;
}


text:
package com.mongodb.internal.bulk;

/**
 *
This class is not part of the public API and may be removed or changed at any time

 */
public class WriteRequestWithIndex {
    private final int index;
    private final WriteRequest writeRequest;

    public WriteRequestWithIndex(final WriteRequest writeRequest, final int index) {
        this.writeRequest = writeRequest;
        this.index = index;
    }

    public int getIndex() {
        return index;
    }

    public WriteRequest getWriteRequest() {
        return writeRequest;
    }

    public WriteRequest.Type getType() {
        return writeRequest.getType();
    }
}

redpajama_set_name: RedPajamaGithub


text:
import DIC, { Youtube } from './dic';
import InitService from './init.service';
import Subtitle, {
  SubtitleElement,
  SubtitleFrame,
  State,
  getCacheName,
  getCacheNames,
  buildCache,
  getSubtitleFromCache,
  addQueryStringParameterToUrl,
  getIframeSrc,
  createSubtitleElement,
  isStateChanged,
  renderClassName,
  renderText,
  renderSubtitle,
  getFrameRect
} from './subtitle';

test('getCacheName returns the correct cache name', () => {
  expect(getCacheName(39)).toStrictEqual(3);
  expect(getCacheName(39.9)).toStrictEqual(3);
  expect(getCacheName(40)).toStrictEqual(4);
  expect(getCacheName(0)).toStrictEqual(0);
});

test('getCacheNames returns the correct cache names', () => {
  expect(getCacheNames(10, 33)).toStrictEqual([1, 2, 3]);
  expect(getCacheNames(11, 12)).toStrictEqual([1]);
});

test('buildCache returns the correct cache', () => {
  const subtitles = [
    { start: 1.5, end: 4, text: 'fakeText1' },
    { start: 5, end: 9.8, text: 'fakeText2' },
    { start: 9.9, end: 12, text: 'fakeText3' },
  ];

  const expectedCache = {
    0: [
      { start: 1.5, end: 4, text: 'fakeText1' },
      { start: 5, end: 9.8, text: 'fakeText2' },
      { start: 9.9, end: 12, text: 'fakeText3' }
    ],
    1: [
      { start: 9.9, end: 12, text: 'fakeText3' }
    ]
  };

  expect(buildCache(subtitles)).toStrictEqual(expectedCache);
});

test('getSubtitleFromCache returns the correct subtitle', () => {
  const cache = {
    0: [
      { start: 1.5, end: 4, text: 'fakeText1' },
      { start: 5, end: 9.8, text: 'fakeText2' },
      { start: 9.9, end: 12, text: 'fakeText3' }
    ],
    1: [
      { start: 9.9, end: 12, text: 'fakeText3' }
    ]
  };

  expect(getSubtitleFromCache(10, null)).toStrictEqual(null);
  expect(getSubtitleFromCache(22, cache)).toStrictEqual(null);
  expect(getSubtitleFromCache(14, cache)).toStrictEqual(null);

  expect(getSubtitleFromCache(10, cache)).toStrictEqual({ start: 9.9, end: 12, text: 'fakeText3' });
});

test('addQueryStringParameterToUrl returns the correct url', () => {
  expect(addQueryStringParameterToUrl('http://example.com/', {})).toBe('http://example.com/');
  expect(addQueryStringParameterToUrl('http://example.com/', { fakeParameter: 'fakeValue' })).toBe('http://example.com/?fakeParameter=fakeValue');
  expect(addQueryStringParameterToUrl('http://example.com/?fakeParameter=prevValue', { fakeParameter: 'fakeValue' })).toBe('http://example.com/?fakeParameter=prevValue&fakeParameter=fakeValue');
  expect(addQueryStringParameterToUrl('http://example.com/#hashPart', { fakeParameter: 'fakeValue' })).toBe('http://example.com/?fakeParameter=fakeValue#hashPart');
});

test('getIframeSrc returns the correct src', () => {
  expect(getIframeSrc('https://www.youtube.com/embed/fGPPfZIvtCw')).toBe('https://www.youtube.com/embed/fGPPfZIvtCw?enablejsapi=1&html5=1&playsinline=1&fs=0');
  expect(getIframeSrc('https://www.youtube.com/embed/fGPPfZIvtCw?enablejsapi=0&html5=0&playsinline=0&fs=1')).toBe('https://www.youtube.com/embed/fGPPfZIvtCw?enablejsapi=0&html5=0&playsinline=0&fs=1&enablejsapi=1&html5=1&playsinline=1');
  expect(getIframeSrc('https://www.youtube.com/embed/fGPPfZIvtCw?enablejsapi=1&html5=1&playsinline=1&fs=0')).toBe('https://www.youtube.com/embed/fGPPfZIvtCw?enablejsapi=1&html5=1&playsinline=1&fs=0');
});

test('createSubtitleElement creates the correct subtitle element', () => {
  const insertHandler = jest.fn();
  const nextSibling = {} as ChildNode;
  const subtitle = {} as Subtitle;

  const parentNode: Partial<ParentNode & Node> = {
    insertBefore: insertHandler
  };

  const document = {
    createElement: (): HTMLElement => {
      return {} as HTMLElement;
    }
  } as Partial<Document>;

  DIC.setDocument(document as Document);

  const element = createSubtitleElement({
    parentNode: parentNode as ParentNode & Node,
    nextSibling
  } as SubtitleFrame, subtitle);

  expect(element.youtubeExternalSubtitle).toBe(subtitle);

  expect(insertHandler).toHaveBeenCalledWith(element, nextSibling);
});

test('isStateChanged returns the correct result', () => {
  expect(isStateChanged({ text: 'value' } as State, {} as State)).toBe(false);
  expect(isStateChanged({} as State, { text: 'value' } as State)).toBe(true);
  expect(isStateChanged({ text: 'value' } as State, { text: 'value' } as State)).toBe(false);
  expect(isStateChanged({ text: 'value' } as State, { text: 'value2' } as State)).toBe(true);
});

test('renderClassName returns the correct className', () => {
  expect(renderClassName(null)).toBe('youtube-external-subtitle');
  expect(renderClassName(false)).toBe('youtube-external-subtitle fullscreen-ignore');
  expect(renderClassName(true)).toBe('youtube-external-subtitle fullscreen');
});

test('renderText returns the correct text', () => {
  expect(renderText(null)).toBe('');
  expect(renderText('fake subtitle text')).toBe('fake subtitle text');
  expect(renderText('fake subtitle text\nwith new line')).toBe('fake subtitle text
with new line');
});

test('getFrameRect returns the correct frame rectangle', () => {
  const frame1 = {
    offsetWidth: 600, offsetHeight: 400,
    offsetLeft: 10, offsetTop: 100,
    scrollLeft: 5, scrollTop: 0,
    clientLeft: 0, clientTop: 10
  } as SubtitleFrame;

  expect(getFrameRect(frame1, false)).toEqual({
    height: 400, width: 600,
    x: 5, y: 110,
    bottomPadding: 60
  });

  expect(getFrameRect(frame1, true)).toEqual({
    height: 400, width: 600,
    x: 5, y: 110,
    bottomPadding: 60
  });

  const frame2 = {
    offsetWidth: 200, offsetHeight: 150,
    offsetLeft: 10, offsetTop: 100,
    scrollLeft: 5, scrollTop: 0,
    clientLeft: 0, clientTop: 10
  } as SubtitleFrame;

  expect(getFrameRect(frame2, false)).toEqual({
    height: 150, width: 200,
    x: 5, y: 110,
    bottomPadding: 20
  });

  expect(getFrameRect(frame2, true)).toEqual({
    height: 150, width: 200,
    x: 5, y: 110,
    bottomPadding: 60
  });
});

test('renderSubtitle displays the subtitles correctly', () => {
  const fakeElement = {
    style: {},
    parentNode: {
      removeChild: jest.fn()
    } as Partial<ParentNode & Node>,
    offsetWidth: 196,
    offsetHeight: 40
  } as SubtitleElement;

  renderSubtitle(fakeElement, null, true, null, true);

  expect(fakeElement.className).toBe('youtube-external-subtitle fullscreen');
  expect(fakeElement.innerHTML).toBe('');
  expect(fakeElement.style.display).toBe('');

  renderSubtitle(fakeElement, null, true, 'PO: Master Shifu?', true);

  expect(fakeElement.innerHTML).toBe('PO: Master Shifu?');
  expect(fakeElement.style.display).toBe('block');

  const fakePlayer = {
    getIframe: () => {
      return {
        offsetLeft: 88,
        scrollLeft: 0,
        clientLeft: 0,
        offsetTop: 174,
        scrollTop: 0,
        clientTop: 0,
        offsetWidth: 1140,
        offsetHeight: 400,
      } as SubtitleFrame;
    }
  };

  renderSubtitle(fakeElement, fakePlayer, true, 'PO: Master Shifu?', true);

  expect(fakeElement.style.display).toBe('block');
  expect(fakeElement.style.visibility).toBe('');
  expect(fakeElement.style.top).toBe('474px');
  expect(fakeElement.style.left).toBe('560px');
  expect(fakeElement.style.maxWidth).toBe('1120px');
  expect(fakeElement.style.fontSize).toBe('1.5384615384615385em');
});

const getSubtitleFrame = (src: string): SubtitleFrame => {
  const parentNode: Partial<ParentNode & Node> = {
    insertBefore: jest.fn()
  };

  return {
    src: src,
    parentNode: parentNode as ParentNode & Node
  } as SubtitleFrame;
};

const setDICServices = (
  fakeElement: HTMLElement,
  initServiceAddSubtitle: Function,
  initServiceRemoveSubtitle: Function,
  playerAddEventListener: Function,
  playerRemoveEventListener: Function
) => {
  const initService = {
    grantGlobalStyles: () => {},
    grantIframeApi: (cb) => {
      cb();
    }
  } as InitService;

  initService.addSubtitle = initServiceAddSubtitle === null ? () => {} : initServiceAddSubtitle as any;
  initService.removeSubtitle = initServiceRemoveSubtitle === null ? () => {} : initServiceRemoveSubtitle as any;

  DIC.setInitService(initService);

  const document = {
    createElement: (): HTMLElement => {
      return fakeElement === null
        ? {
            style: {}
          } as HTMLElement
        : fakeElement;
    }
  } as Partial<Document>;

  DIC.setDocument(document as Document);

  class FakePlayer {
    iframe: SubtitleFrame;
    addEventListener = playerAddEventListener === null
      ? () => {}
      : playerAddEventListener;
    removeEventListener = playerRemoveEventListener === null
      ? () => {}
      : playerRemoveEventListener;

    constructor(iframe: SubtitleFrame) {
      this.iframe = iframe;
    }

    getIframe(): SubtitleFrame {
      return this.iframe;
    }
  }

  DIC.setYT({
    Player: FakePlayer
  } as Youtube);
};

test('new Subtitle() returns a correct Subtitle instance', () => {
  const fakeElement = {
    style: {}
  } as HTMLElement;

  const fakePlayerAddEventListener = jest.fn();
  const fakeInitServiceAddSubtitle = jest.fn();

  setDICServices(fakeElement, fakeInitServiceAddSubtitle, null, fakePlayerAddEventListener, null);

  const subtitleFrame = getSubtitleFrame('https://www.youtube.com/embed/fGPPfZIvtCw');

  const subtitles = [
    {
      'start': 10,
      'end': 11,
      'text': 'PO: Master Shifu?'
    },
    {
      'start': 13,
      'end': 14,
      'text': 'Good time? Bad time?'
    }
  ];

  const fakeRenderMethod = jest.fn();

  const subtitle = new Subtitle(subtitleFrame, subtitles, fakeRenderMethod);

  expect(subtitle).toBeInstanceOf(Subtitle);
  expect(subtitleFrame.youtubeExternalSubtitle).toBe(subtitle);
  expect(subtitleFrame.src).toBe('https://www.youtube.com/embed/fGPPfZIvtCw?enablejsapi=1&html5=1&playsinline=1&fs=0');
  expect(subtitle['cache']).toEqual({
    1: [
      {
        'end': 11,
        'start': 10,
        'text': 'PO: Master Shifu?'
      },
      {
        'end': 14,
        'start': 13,
        'text': 'Good time? Bad time?'
      }
    ]
  });
  expect(subtitle['element']).toBe(fakeElement);
  expect(subtitle['renderMethod']).toBe(fakeRenderMethod);
  expect(fakeInitServiceAddSubtitle).toHaveBeenCalledTimes(1);
  expect(subtitle.getYTPlayer()).toBeTruthy();
  expect(subtitle.getYTPlayer().addEventListener).toHaveBeenCalledWith('onReady', subtitle['onPlayerReady']);
  expect(subtitle.getYTPlayer().addEventListener).toHaveBeenCalledWith('onStateChange', subtitle['onPlayerStateChange']);

  const subtitleFrame2 = getSubtitleFrame('https://www.youtube.com/embed/fGPPfZIvtCw');
  subtitleFrame2.youtubeExternalSubtitle = {} as Subtitle;

  expect(() => {
    new Subtitle(subtitleFrame2, subtitles);
  }).toThrow('YoutubeExternalSubtitle: subtitle is already added for this element');
  expect(fakeInitServiceAddSubtitle).toHaveBeenCalledTimes(1);

  const subtitleFrame3 = getSubtitleFrame('https://www.youtube.com/embed/fGPPfZIvtCw?enablejsapi=1&html5=1&playsinline=1&fs=0');

  const subtitle3 = new Subtitle(subtitleFrame3, subtitles);

  expect(subtitle3['renderMethod']).toBe(renderSubtitle);
  expect(subtitleFrame3.src).toBe('https://www.youtube.com/embed/fGPPfZIvtCw?enablejsapi=1&html5=1&playsinline=1&fs=0');

  const subtitleFrame4 = getSubtitleFrame('https://www.youtube.com/embed/fGPPfZIvtCw');

  const subtitle4 = new Subtitle(subtitleFrame4);

  expect(subtitle4['cache']).toEqual({});
});

test('load loads the subtitles properly', () => {
  setDICServices(null, null, null, null, null);

  const subtitleFrame = getSubtitleFrame('https://www.youtube.com/embed/fGPPfZIvtCw');

  const subtitle = new Subtitle(subtitleFrame, []);

  expect(subtitle['cache']).toEqual({});

  subtitle.load([
    {
      'start': 10,
      'end': 11,
      'text': 'PO: Master Shifu?'
    },
    {
      'start': 13,
      'end': 14,
      'text': 'Good time? Bad time?'
    }
  ]);

  expect(subtitle['cache']).toEqual({
    1: [
      {
        'end': 11,
        'start': 10,
        'text': 'PO: Master Shifu?'
      },
      {
        'end': 14,
        'start': 13,
        'text': 'Good time? Bad time?'
      }
    ]
  });
});

test('setIsFullscreenActive sets isFullscreenActive', () => {
  setDICServices(null, null, null, null, null);

  const subtitleFrame = getSubtitleFrame('https://www.youtube.com/embed/fGPPfZIvtCw');

  const subtitle = new Subtitle(subtitleFrame, []);

  expect(subtitle['state'].isFullscreenActive).toBe(null);

  subtitle.setIsFullscreenActive(true);

  expect(subtitle['state'].isFullscreenActive).toBe(true);

  subtitle.setIsFullscreenActive(false);

  expect(subtitle['state'].isFullscreenActive).toBe(false);
});

test('destroy removes the subtitle instance', () => {
  const fakeElement = {
    style: {},
    parentNode: {
      removeChild: jest.fn()
    } as Partial<ParentNode & Node>
  } as HTMLElement;

  const fakePlayerRemoveEventListener = jest.fn();
  const fakeInitServiceRemoveSubtitle = jest.fn();

  setDICServices(fakeElement, null, fakeInitServiceRemoveSubtitle, null, fakePlayerRemoveEventListener);

  const subtitleFrame = getSubtitleFrame('https://www.youtube.com/embed/fGPPfZIvtCw');

  const subtitle = new Subtitle(subtitleFrame, []);

  const fakeStopMethod = jest.fn();

  subtitle['stop'] = fakeStopMethod;

  subtitle.destroy();

  expect(fakeStopMethod).toHaveBeenCalled();
  expect(fakeElement.parentNode.removeChild).toHaveBeenCalledWith(fakeElement);
  expect(subtitleFrame.youtubeExternalSubtitle).toBe(null);
  expect(subtitle.getYTPlayer().removeEventListener).toHaveBeenCalledWith('onReady', subtitle['onPlayerReady']);
  expect(subtitle.getYTPlayer().removeEventListener).toHaveBeenCalledWith('onStateChange', subtitle['onPlayerStateChange']);
  expect(fakeInitServiceRemoveSubtitle).toHaveBeenCalled();
});

test('render calls the correct renderMethod', () => {
  const fakeElement = {
    style: {}
  } as HTMLElement;

  setDICServices(fakeElement, null, null, null, null);

  const subtitleFrame = getSubtitleFrame('https://www.youtube.com/embed/fGPPfZIvtCw');

  const fakeRenderMethod = jest.fn();

  const subtitle = new Subtitle(subtitleFrame, [], fakeRenderMethod);

  const fakePlayer = {
    getIframe: () => {
      return {
        offsetLeft: 88,
        scrollLeft: 0,
        clientLeft: 0,
        offsetTop: 174,
        scrollTop: 0,
        clientTop: 0,
        offsetWidth: 1140,
        offsetHeight: 400,
      } as SubtitleFrame;
    }
  };
  const fakeIsFullscreenActive = true;
  const fakeText = 'fakeText';
  const fakeControlsVisible = false;

  subtitle['player'] = fakePlayer;
  subtitle['state'].isFullscreenActive = fakeIsFullscreenActive;
  subtitle['state'].text = fakeText;
  subtitle['state'].controlsVisible = fakeControlsVisible;

  fakeRenderMethod.mockClear();

  subtitle.render();

  expect(fakeRenderMethod).toHaveBeenCalledWith(fakeElement, fakePlayer, fakeIsFullscreenActive, fakeText, fakeControlsVisible);
});

test('isInContainer returns the correct result', () => {
  const fakeElement = {
    style: {},
    contains(other: Node | null): boolean {
      return false;
    }
  } as HTMLElement;

  setDICServices(fakeElement, null, null, null, null);

  const subtitleFrame = getSubtitleFrame('https://www.youtube.com/embed/fGPPfZIvtCw');

  const subtitle = new Subtitle(subtitleFrame, []);

  const notParentContainer = { contains: () => { return false; } } as Partial<Element>;
  const parentContainer = { contains: () => { return true; } } as Partial<Element>;

  expect(subtitle.isInContainer(notParentContainer as Element)).toBe(false);
  expect(subtitle.isInContainer(parentContainer as Element)).toBe(true);
  expect(subtitle.isInContainer(fakeElement)).toBe(true);
});

test('getYTPlayer returns the player', () => {
  setDICServices(null, null, null, null, null);

  const subtitleFrame = getSubtitleFrame('https://www.youtube.com/embed/fGPPfZIvtCw');

  const subtitle = new Subtitle(subtitleFrame, []);

  const fakePlayer = {};

  subtitle['player'] = fakePlayer;

  expect(subtitle.getYTPlayer()).toBe(fakePlayer);
});

test('setState sets the state correctly', () => {
  setDICServices(null, null, null, null, null);

  const subtitleFrame = getSubtitleFrame('https://www.youtube.com/embed/fGPPfZIvtCw');

  const subtitle = new Subtitle(subtitleFrame, []);

  const fakeRender = jest.fn();

  subtitle.render = fakeRender;

  subtitle['state'].text = 'initialText';

  subtitle['setState']({ text: 'initialText' });

  expect(subtitle['state'].text).toBe('initialText');
  expect(fakeRender).not.toHaveBeenCalled();

  subtitle['setState']({ text: 'fakeText' });

  expect(subtitle['state'].text).toBe('fakeText');
  expect(fakeRender).toHaveBeenCalled();
});

test('start starts the subtitle correctly', () => {
  setDICServices(null, null, null, null, null);

  const subtitleFrame = getSubtitleFrame('https://www.youtube.com/embed/fGPPfZIvtCw');

  const subtitle = new Subtitle(subtitleFrame, []);

  const fakeStop = jest.fn();
  const fakeOnTimeChange = jest.fn();
  const fakeSetInterval = jest.fn();
  const fakeSetTimeout = jest.fn();

  subtitle['stop'] = fakeStop;
  subtitle['onTimeChange'] = fakeOnTimeChange;

  const window = {
    setInterval: fakeSetInterval,
    setTimeout: fakeSetTimeout
  } as Partial<Window>;

  DIC.setWindow(window as Window);

  subtitle['start']();

  expect(fakeStop).toHaveBeenCalled();
  expect(fakeSetInterval).toHaveBeenCalledWith(subtitle['onTimeChange'], 500);
  expect(fakeSetTimeout).toHaveBeenCalledWith(subtitle['onControlsHide'], 3000);
  expect(fakeOnTimeChange).toHaveBeenCalled();
});

test('stop stops the subtitle correctly', () => {
  setDICServices(null, null, null, null, null);

  const subtitleFrame = getSubtitleFrame('https://www.youtube.com/embed/fGPPfZIvtCw');

  const subtitle = new Subtitle(subtitleFrame, []);

  const fakeSetState = jest.fn();
  const fakeClearInterval = jest.fn();
  const fakeClearTimeout = jest.fn();

  subtitle['setState'] = fakeSetState;

  const window = {
    clearInterval: fakeClearInterval,
    clearTimeout: fakeClearTimeout
  } as Partial<Window>;

  DIC.setWindow(window as Window);

  subtitle['stop']();

  expect(fakeClearInterval).toHaveBeenCalledWith(subtitle['timeChangeInterval']);
  expect(fakeClearTimeout).toHaveBeenCalledWith(subtitle['controlsHideTimeout']);
  expect(fakeSetState).toHaveBeenCalledWith({ controlsVisible: true });
});

test('getCurrentVideoId returns the correct video id', () => {
  setDICServices(null, null, null, null, null);

  const subtitleFrame = getSubtitleFrame('https://www.youtube.com/embed/fGPPfZIvtCw');

  const subtitle = new Subtitle(subtitleFrame, []);

  subtitle['player'] = {
    getVideoData: () => {
      return {
        video_id: 'fakeVideoId',
      };
    }
  };

  expect(subtitle['getCurrentVideoId']()).toBe('fakeVideoId');
});

test('onTimeChange sets the correct text', () => {
  setDICServices(null, null, null, null, null);

  const subtitleFrame = getSubtitleFrame('https://www.youtube.com/embed/fGPPfZIvtCw');

  const subtitle = new Subtitle(subtitleFrame, []);

  subtitle['cache'] = {
    1: [
      {
        'end': 11,
        'start': 10,
        'text': 'PO: Master Shifu?'
      },
      {
        'end': 14,
        'start': 13,
        'text': 'Good time? Bad time?'
      }
    ]
  };

  subtitle['player'] = {
    getIframe: () => {
      return subtitleFrame;
    },
    getCurrentTime: () => {
      return 1.12;
    }
  };

  subtitle['onTimeChange']();

  expect(subtitle['state'].text).toBe(null);

  subtitle['player'] = {
    getIframe: () => {
      return subtitleFrame;
    },
    getCurrentTime: () => {
      return 10.12;
    }
  };

  subtitle['onTimeChange']();

  expect(subtitle['state'].text).toBe('PO: Master Shifu?');
});

test('onPlayerReady sets the correct video id', () => {
  setDICServices(null, null, null, null, null);

  const subtitleFrame = getSubtitleFrame('https://www.youtube.com/embed/fGPPfZIvtCw');

  const subtitle = new Subtitle(subtitleFrame, []);

  subtitle['getCurrentVideoId'] = () => 'fakeVideoId';

  subtitle['onPlayerReady']();

  expect(subtitle['videoId']).toBe('fakeVideoId');
});

test('onControlsHide sets controlsVisible correctly', () => {
  setDICServices(null, null, null, null, null);

  const subtitleFrame = getSubtitleFrame('https://www.youtube.com/embed/fGPPfZIvtCw');

  const subtitle = new Subtitle(subtitleFrame, []);

  subtitle['state'].controlsVisible = true;

  subtitle['onControlsHide']();

  expect(subtitle['state'].controlsVisible).toBe(false);
});

test('onPlayerStateChange handles the change correctly', () => {
  setDICServices(null, null, null, null, null);

  const subtitleFrame = getSubtitleFrame('https://www.youtube.com/embed/fGPPfZIvtCw');

  const subtitle = new Subtitle(subtitleFrame, []);

  const fakeStart = jest.fn();
  const fakeStop = jest.fn();
  const fakeSetState = jest.fn();

  subtitle['start'] = fakeStart;
  subtitle['stop'] = fakeStop;
  subtitle['setState'] = fakeSetState;
  subtitle['getCurrentVideoId'] = () => 'fakeVideoId';

  subtitle['videoId'] = 'differentVideoId';

  const fakeYT = {
    PlayerState: {
      PLAYING: 1,
      PAUSED: 2,
      ENDED: 3
    }
  };
  fakeYT.PlayerState['FAKE_EVENT'] = 4;

  DIC.setYT(fakeYT as Youtube);

  subtitle['onPlayerStateChange']({ data: fakeYT.PlayerState.PLAYING });
  subtitle['onPlayerStateChange']({ data: fakeYT.PlayerState.PAUSED });
  subtitle['onPlayerStateChange']({ data: fakeYT.PlayerState.ENDED });

  expect(fakeStart).not.toHaveBeenCalled();
  expect(fakeStop).not.toHaveBeenCalled();
  expect(fakeSetState).not.toHaveBeenCalled();

  subtitle['videoId'] = 'fakeVideoId';

  subtitle['onPlayerStateChange']({ data: fakeYT.PlayerState['FAKE_EVENT'] });

  expect(fakeStart).not.toHaveBeenCalled();
  expect(fakeStop).not.toHaveBeenCalled();
  expect(fakeSetState).not.toHaveBeenCalled();

  subtitle['onPlayerStateChange']({ data: fakeYT.PlayerState.PLAYING });

  expect(fakeStart).toHaveBeenCalledTimes(1);
  expect(fakeStop).not.toHaveBeenCalled();
  expect(fakeSetState).not.toHaveBeenCalled();

  subtitle['onPlayerStateChange']({ data: fakeYT.PlayerState.PAUSED });

  expect(fakeStart).toHaveBeenCalledTimes(1);
  expect(fakeStop).toHaveBeenCalledTimes(1);
  expect(fakeSetState).not.toHaveBeenCalled();

  subtitle['onPlayerStateChange']({ data: fakeYT.PlayerState.ENDED });

  expect(fakeStart).toHaveBeenCalledTimes(1);
  expect(fakeStop).toHaveBeenCalledTimes(2);
  expect(fakeSetState).toHaveBeenCalledWith({ text: null });
});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Login screen</title>
    <link href="<?php echo base_url().LOGIN;?>css/bootstrap.min.css" rel="stylesheet">
    <link href="<?php echo base_url().LOGIN;?>css/custom.css" rel="stylesheet">

<?php echo form_open("auth/check_login"); ?>

Hi, logging in?

                <form class="form" role="form">

                        Username
                        <input id="username" type="text" name="username" class="form-control material-input" autocomplete="off">

                        Password
                        <input id="password" type="password" name="password" class="form-control material-input" autocomplete="off">

                </form>

        <button id="flow-button" class="btn btn-custom btn-block" type="submit">Sign in</button>

<?php echo form_close(); ?>


text:
"""
Twilio SMS platform for notify component.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.twilio_sms/
"""
import logging

import voluptuous as vol

from homeassistant.components.twilio import DATA_TWILIO
import homeassistant.helpers.config_validation as cv
from homeassistant.components.notify import (
    ATTR_TARGET, PLATFORM_SCHEMA, BaseNotificationService)

_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ["twilio"]

CONF_FROM_NUMBER = "from_number"

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_FROM_NUMBER):
        vol.All(cv.string, vol.Match(r"^\+?[1-9]\d{1,14}$")),
})

def get_service(hass, config, discovery_info=None):
    """Get the Twilio SMS notification service."""
    return TwilioSMSNotificationService(
        hass.data[DATA_TWILIO], config[CONF_FROM_NUMBER])

class TwilioSMSNotificationService(BaseNotificationService):
    """Implement the notification service for the Twilio SMS service."""

    def __init__(self, twilio_client, from_number):
        """Initialize the service."""
        self.client = twilio_client
        self.from_number = from_number

    def send_message(self, message="", **kwargs):
        """Send SMS to specified target user cell."""
        targets = kwargs.get(ATTR_TARGET)

        if not targets:
            _LOGGER.info("At least 1 target is required")
            return

        for target in targets:
            self.client.messages.create(
                to=target, body=message, from_=self.from_number)


text:
{% extends "period_archives.html" %}
{% block archive_header %}

{{ category }} {{ period | reverse | join(' ') }}

{% endblock %}


text:
#ifndef __TEMBOOGPIO__
#define __TEMBOOGPIO__

#include "TembooWebSocketRequestHandles.h"

#if defined(__cplusplus)
extern "C" {
#endif

typedef struct TembooGPIOConfig{
    uint8_t* channel;
    int pin;
    int currentValue;
    int mode;
} TembooGPIOConfig;

void tembooGPIOBegin(void* sensorConfig);
uint8_t* tembooGPIOGetSensorChannel(void* sensorConfig);
int tembooGPIOGetSensorPin(void* sensorConfig);

void tembooDigitalGPIOInit(TembooGPIOConfig* sensorConfig, TembooSensor* tembooSensor, int pin, int defaultValue, int mode);
int  tembooDigitalRead(void* sensorConfig);
void tembooDigitalWrite(void* sensorConfig, int val);

void tembooAnalogGPIOInit(TembooGPIOConfig* sensorConfig, TembooSensor* tembooSensor, int pin, int defaultValue, int mode);
int  tembooAnalogRead(void* sensorConfig);
void tembooAnalogWrite(void* sensorConfig, int val);

#if defined(__cplusplus)
}
#endif

#endif /* defined(__TEMBOOGPIO__) */


text:
//
//  TableDefine.m
//  BeLuv
//
//  Created by 平塚俊輔 on 11/07/28.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "TableDefine.h"

@implementation TableDefine
@synthesize encode;
@synthesize inputmust;
@synthesize inputedit;
@synthesize inputoption;
@synthesize columnAry;

- (id)init
{
    if(self = [super init]){
        /* initialization code */
		encode = [[NSMutableDictionary alloc] initWithCapacity:0];
		inputmust = [[NSMutableDictionary alloc] initWithCapacity:0];
        inputedit = [[NSMutableDictionary alloc] initWithCapacity:0];
    }
    return self;
}

#pragma mark エンコード系
-(void)initEncode{

}

#pragma mark 必須入力系
-(void)initInput{

}

#pragma mark 更新系
-(void)initEdit{

}

@end


text:
/**
 * Normalize the response from "allGatsbyApiCall"
 * @param {Array} array Response from GraphQL
 * @returns {Array} Normalized Array
 */

const normalizeGatsbyApiCall = array =>
  array.map(entry => {
    const codeLocation =
      entry.nodes.length > 1
        ? entry.nodes.map(l => {
            return {
              file: l.file,
              start: { line: l.codeLocation.start.line },
              end: { line: l.codeLocation.end.line },
            }
          })
        : {
            file: entry.nodes[0].file,
            start: { line: entry.nodes[0].codeLocation.start.line },
            end: { line: entry.nodes[0].codeLocation.end.line },
          }

    return { name: entry.name, codeLocation }
  })

export default normalizeGatsbyApiCall


text:
package org.mozilla.javascript.tests;

import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;

import junit.framework.Assert;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.mozilla.javascript.drivers.ShellTest;
import org.mozilla.javascript.drivers.StandardTests;
import org.mozilla.javascript.drivers.TestUtils;
import org.mozilla.javascript.tools.shell.ShellContextFactory;

/**
 * This JUnit suite runs the Mozilla test suite (in mozilla.org CVS
 * at /mozilla/js/tests).
 *
 * Not all tests in the suite are run. Since the mozilla.org tests are
 * designed and maintained for the SpiderMonkey engine, tests in the
 * suite may not pass due to feature set differences and known bugs.
 * To make sure that this unit test is stable in the midst of changes
 * to the mozilla.org suite, we maintain a list of passing tests in
 * files opt-1.tests, opt0.tests, and opt9.tests. This class also
 * implements the ability to run skipped tests, see if any pass, and
 * print out a script to modify the *.tests files.
 * (This approach doesn't handle breaking changes to existing passing
 * tests, but in practice that has been very rare.)
 * @author Norris Boyd
 * @author Attila Szegedi
 */
@RunWith(Parameterized.class)
public class MozillaSuiteTest {
    private final File jsFile;
    private final int optimizationLevel;

    static final int[] OPT_LEVELS = { -1, 0, 9 };

    public MozillaSuiteTest(File jsFile, int optimizationLevel) {
        this.jsFile = jsFile;
        this.optimizationLevel = optimizationLevel;
    }

    public static File getTestDir() throws IOException {
        File testDir = null;
        if (System.getProperty("mozilla.js.tests") != null) {
            testDir = new File(System.getProperty("mozilla.js.tests"));
        } else {
            URL url = StandardTests.class.getResource(".");
            String path = url.getFile();
            int jsIndex = path.lastIndexOf("/js");
            if (jsIndex == -1) {
                throw new IllegalStateException("You aren't running the tests "+
                    "from within the standard mozilla/js directory structure");
            }
            path = path.substring(0, jsIndex + 3).replace('/', File.separatorChar);
            path = path.replace("%20", " ");
            testDir = new File(path, "tests");
        }
        if (!testDir.isDirectory()) {
            throw new FileNotFoundException(testDir + " is not a directory");
        }
        return testDir;
    }

    public static String getTestFilename(int optimizationLevel) {
        return "opt" + optimizationLevel + ".tests";
    }

    public static File[] getTestFiles(int optimizationLevel) throws IOException {
        File testDir = getTestDir();
        String[] tests = TestUtils.loadTestsFromResource(
            "/" + getTestFilename(optimizationLevel), null);
        Arrays.sort(tests);
        File[] files = new File[tests.length];
        for (int i=0; i < files.length; i++) {
            files[i] = new File(testDir, tests[i]);
        }
        return files;
    }

    public static String loadFile(File f) throws IOException {
        int length = (int) f.length(); // don't worry about very long files
        char[] buf = new char[length];
        new FileReader(f).read(buf, 0, length);
        return new String(buf);
    }

    @Parameters
    public static Collection<Object[]> mozillaSuiteValues() throws IOException {
        List<Object[]> result = new ArrayList<Object[]>();
        int[] optLevels = OPT_LEVELS;
        for (int i=0; i < optLevels.length; i++) {
            File[] tests = getTestFiles(optLevels[i]);
            for (File f : tests) {
                result.add(new Object[] { f, optLevels[i] });
            }
        }
        return result;
    }

    // move "@Parameters" to this method to test a single Mozilla test
    public static Collection<Object[]> singleDoctest() throws IOException {
        final String SINGLE_TEST_FILE = "e4x/Expressions/11.1.1.js";
        final int SINGLE_TEST_OPTIMIZATION_LEVEL = -1;
        List<Object[]> result = new ArrayList<Object[]>();
        File f = new File(getTestDir(), SINGLE_TEST_FILE);
        result.add(new Object[] { f, SINGLE_TEST_OPTIMIZATION_LEVEL });
        return result;
    }

    private static class ShellTestParameters extends ShellTest.Parameters {
        @Override
        public int getTimeoutMilliseconds() {
            if (System.getProperty("mozilla.js.tests.timeout") != null) {
                return Integer.parseInt(System.getProperty(
                    "mozilla.js.tests.timeout"));
            }
            return 10000;
        }
    }

    private static class JunitStatus extends ShellTest.Status {
        File file;

        @Override
        public final void running(File jsFile) {
            // remember file in case we fail
            file = jsFile;
        }

        @Override
        public final void failed(String s) {
            // Include test source in message, this is the only way
            // to locate the test in a Parameterized JUnit test
            String msg = "In \"" + file + "\":" +
                         System.getProperty("line.separator") + s;
            System.out.println(msg);
            Assert.fail(msg);
        }

        @Override
        public final void exitCodesWere(int expected, int actual) {
            Assert.assertEquals("Unexpected exit code", expected, actual);
        }

        @Override
        public final void outputWas(String s) {
            // Do nothing; we don't want to see the output when running JUnit
            // tests.
        }

        @Override
        public final void threw(Throwable t) {
            Assert.fail(ShellTest.getStackTrace(t));
        }

        @Override
        public final void timedOut() {
            failed("Timed out.");
        }
    }

    @Test
    public void runMozillaTest() throws Exception {
        //System.out.println("Test \"" + jsFile + "\" running under optimization level " + optimizationLevel);
        final ShellContextFactory shellContextFactory =
            new ShellContextFactory();
        shellContextFactory.setOptimizationLevel(optimizationLevel);
        ShellTestParameters params = new ShellTestParameters();
        JunitStatus status = new JunitStatus();
        ShellTest.run(shellContextFactory, jsFile, params, status);
    }

    /**
     * The main class will run all the test files that are *not* covered in
     * the *.tests files, and print out a list of all the tests that pass.
     */
    public static void main(String[] args) throws IOException {
        PrintStream out = new PrintStream("fix-tests-files.sh");
        try {
            for (int i=0; i < OPT_LEVELS.length; i++) {
                int optLevel = OPT_LEVELS[i];
                File testDir = getTestDir();
                File[] allTests =
                    TestUtils.recursiveListFiles(testDir,
                        new FileFilter() {
                            public boolean accept(File pathname)
                            {
                                return ShellTest.DIRECTORY_FILTER.accept(pathname) ||
                                       ShellTest.TEST_FILTER.accept(pathname);
                            }
                    });
                HashSet<File> diff = new HashSet<File>(Arrays.asList(allTests));
                File testFiles[] = getTestFiles(optLevel);
                diff.removeAll(Arrays.asList(testFiles));
                ArrayList<String> skippedPassed = new ArrayList<String>();
                int absolutePathLength = testDir.getAbsolutePath().length() + 1;
                for (File testFile: diff) {
                    try {
                        (new MozillaSuiteTest(testFile, optLevel)).runMozillaTest();
                        // strip off testDir
                        String canonicalized =
                            testFile.getAbsolutePath().substring(absolutePathLength);
                        canonicalized = canonicalized.replace('\\', '/');
                        skippedPassed.add(canonicalized);
                    } catch (Throwable t) {
                        // failed, so skip
                    }
                }
                // "skippedPassed" now contains all the tests that are currently
                // skipped but now pass. Print out shell commands to update the
                // appropriate *.tests file.
                if (skippedPassed.size() > 0) {
                    out.println("cat >> " + getTestFilename(optLevel) + " <<EOF");
                    String[] sorted = skippedPassed.toArray(new String[0]);
                    Arrays.sort(sorted);
                    for (int j=0; j < sorted.length; j++) {
                        out.println(sorted[j]);
                    }
                    out.println("EOF");
                }
            }
            System.out.println("Done.");
        } finally {
            out.close();
        }
    }
}


text:
	<meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/sb-admin.css" rel="stylesheet">

    <link href="css/plugins/morris.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

	<?php
    require 'access/dbaccess.php';
	$id = 3;
	include("header.php");

    $row = $db->query("SELECT * FROM manage_category");

	?>

                            Add Course

                                  Dashboard

                                 Manage Courses

                                 Add Course

<?php
            if((isset($_GET['status'])) && ($_GET['status'] == "success")){
                ?>

                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                            Nice! The Course was added Successfully.

                <?php
            }else if((isset($_GET['status'])) && ($_GET['status'] == "failure")){
                ?>

                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                            Oops! Something went Wrong.

                <?php
            }

            ?>
        <form action="add_courses.php" method="post" enctype="multipart/form-data">
        <input type="hidden" name="type" value="add" />
        <input type="hidden" name="cid" value="<?= $row1['course_id'] ?>" />

            NOTE: Fields marked with * are mandatory.

Course Title:*

                        <input type="text" name="name" class="form-control" required />

Category:*

                        <select class="form-control" name="category" required>
                            <option value="">-- Select --</option>
                        <?php
                            while ($row1 = $row->fetch(PDO::FETCH_ASSOC)) {
                                ?>
                                <option value="<?= $row1['category_id'] ?>"><?= $row1['category_name'] ?></option>
                                <?php
                            }
                        ?>
                        </select>

Duration:*

                        <input type="text" name="duration" class="form-control" required />

Fees:*

                        <input type="text" name="fees" class="form-control" required />

Re-Exam Fees:*

                        <input type="text" name="re-exam" class="form-control" required />

Upload Image:

                        <input type="file" name="Uploadfiles" id="Uploadfiles" />

Institute:*

                        <select class="form-control" name="institute" required>
                            <option value="">-- Select --</option>
                        <?php
                        $inst = $db->query("SELECT * FROM manage_institute");
                            while ($row1 = $inst->fetch(PDO::FETCH_ASSOC)) {
                                ?>
                                <option value="<?= $row1['institute_id'] ?>"><?= $row1['institute_name'] ?></option>
                                <?php
                            }
                        ?>
                        </select>

Short Description:*

                        <textarea type="text" name="short_desc" class="form-control"></textarea>

Course Description:*

            <textarea name="description" class="form-control ckeditor" rows="15" placeholder="Begin from here..." required></textarea>

        <button type="submit" class="btn btn-primary"> Save</button>
        <input type="button" class="btn btn-danger" value="Reset" onclick="reset()" />

    </form>

    <?php include("footer.php"); ?>


text:
int socket_fd;
struct sockaddr_in servaddr;

static void setupConnection(char *hostname)
{
    socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(11539);
    servaddr.sin_addr.s_addr = inet_addr(hostname);
    connect(socket_fd, (const sockaddr*)&servaddr, sizeof(servaddr));
}

int main(int argc, char **argv)
{
	if (argc < 2) {
		return -1;
	}

	setupConnection(argv[1]);

	setupLepton();

	for (;;) {
        uint8_t *frame = nextFrame();
        if (!checkFrame()) {
            continue;
        }
        cv::Mat img = convertData(frame);
        // cv::Mat processed = img.clone();
        float deltax, deltay;
        cv::Mat processed = findPerson(img, deltax, deltay);

        if (deltay == 0.0) {
            printf("stop\n"); fflush(stdout);
        } else if (deltax == 0.0) {
            printf("forward\n"); fflush(stdout);
        } else if (deltax > 0.0) {
            printf("right\n"); fflush(stdout);
        } else {
            printf("left\n"); fflush(stdout);
        }

        // fprintf(stderr, "deltax = %f, deltay = %f\n", deltax, deltay);
        // cv::Mat processed(SCAN_LINES, SCAN_COLUMNS, CV_8UC3, cv::Scalar(255,0,0));
        // fprintf(stderr, "isContinuous = %d\n", processed.isContinuous());
        write(socket_fd, processed.data, SCAN_LINES * SCAN_COLUMNS * 3);
	}
}


text:
package edu.ncsu.dlf.model;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.pdmodel.common.PDPageLabels;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationTextMarkup;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationText;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationRubberStamp;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationMarkup;

import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.rendering.ImageType;

import javax.imageio.ImageIO;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.io.InputStream;
import java.awt.image.BufferedImage;

import edu.ncsu.dlf.utils.ImageUtils;

import edu.ncsu.dlf.model.PdfComment.Tag;

  /**
   * The class is used to represent a PDF document in the system.
   * Converts raw PDF data to a PDF representation in Apache PDFBox (https://pdfbox.apache.org/)
   * and then retrieves PDF annotations as a list of PdfComments objects.
   * @author Team19
   */
public class Pdf {

  //Document object from the Apache PDFBox library
  private PDDocument document = null;
  private PDFRenderer renderer;

  private BufferedImage pageImage;
  private BufferedImage commentBoxImage;

  private static final float SCALE_UP_FACTOR = 2.0f;
  private static final int DEFAULT_SIZE = 72;

  private static final PDColor ORANGE = new PDColor(
        new float[] { 0.9921568627f, 0.5333333333f, 0.1803921568f },
        PDDeviceRGB.INSTANCE
    );

    private static final PDColor GREEN = new PDColor(
        new float[] { 0, 1, 0 },
        PDDeviceRGB.INSTANCE
    );

    private static final PDColor YELLOW = new PDColor(
        new float[] { 1, 1, 0 },
        PDDeviceRGB.INSTANCE
    );

  /**
   * Create a new PDF object with the raw PDF file data and a stream of the comment box image.
   * @param fileStream raw PDF file data
   * @param commentBoxImageStream image of a comment box
   */
  public Pdf(InputStream fileStream, InputStream commentBoxImageStream) throws IOException {
    //https://pdfbox.apache.org/2.0/getting-started.html
    System.setProperty("sun.java2d.cmm", "sun.java2d.cmm.kcms.KcmsServiceProvider");

    document = PDDocument.load(fileStream);
    renderer = new PDFRenderer(document);

    commentBoxImage = ImageIO.read(commentBoxImageStream);
  }

  /**
   * Iterates through the PDF document and makes each annotation into a PdfComment object
   * @return A list of PDFComment objects which map to annotations from the document
   */
  public List<PdfComment> getPDFComments() throws IOException {
	  if(document == null) {
          throw new NullPointerException("PDF Document has not been instantiated.");
	  }

	  List<PdfComment> comments = new ArrayList<>();
      PDPageTree pages = document.getDocumentCatalog().getPages();

      String[] pageLabels = new PDPageLabels(document).getLabelsByPageIndices();

    for(PDPage page: pages) {
      pageImage = null;
      int pageIndex = pages.indexOf(page);
      List<PDAnnotation> originalAnnotations = page.getAnnotations();

      page.setAnnotations(nonBlockingAnnotations(page.getAnnotations()));
      int size = Math.round(DEFAULT_SIZE * SCALE_UP_FACTOR);

      for(PDAnnotation annotation: originalAnnotations) {
        if(pageImage == null) {
          pageImage = renderer.renderImageWithDPI(pageIndex, size, ImageType.RGB);
        }

        PdfComment pdfComment = turnAnnotationIntoPDFComment(annotation);
        if (pdfComment != null) {
            pdfComment.setPageNumber(pageLabels[pageIndex]);
            comments.add(pdfComment);
        }
      }

      page.setAnnotations(originalAnnotations);
    }

	  return comments;
  }

  /**
   * Filters out annotations that PDFBox draws poorly so they don't blot the text out and
   * make the images hard to see.  This includes hightlight textMarkups and Popups
   * @return A list of annotations that are not text markup or popup
   */
  private List<PDAnnotation> nonBlockingAnnotations(List<PDAnnotation> annotations) {

      List<PDAnnotation> annotationsThatAreNotTextMarkupOrPopup = new ArrayList<>();
      for(PDAnnotation annotation: annotations) {
          if (annotation instanceof PDAnnotationTextMarkup) {
              if (!PDAnnotationTextMarkup.SUB_TYPE_HIGHLIGHT.equals(annotation.getSubtype())) {
                  annotationsThatAreNotTextMarkupOrPopup.add(annotation);
              }
          }
          else if (annotation.getClass() == PDAnnotationMarkup.class || annotation.getClass() == PDAnnotationRubberStamp.class) {
              annotationsThatAreNotTextMarkupOrPopup.add(annotation);
          }
      }

      return annotationsThatAreNotTextMarkupOrPopup;
  }

  /**
   * Turns a PDAnnotation object into a PdfComment object
   * @param anno represents a PDF annotation
   * @return A PdfComment object (with an image) thats maps to the annotation
   */
  private PdfComment turnAnnotationIntoPDFComment(PDAnnotation anno) {
      PdfComment pdfComment = null;

      if (anno instanceof PDAnnotationTextMarkup) {
          PDAnnotationTextMarkup comment = (PDAnnotationTextMarkup) anno;
          String writtenComment = comment.getContents();
          if (writtenComment == null || writtenComment.isEmpty()) {
              writtenComment = "[blank]";
          }
          if (PDAnnotationTextMarkup.SUB_TYPE_STRIKEOUT.equals(comment.getSubtype())) {
              writtenComment = "delete this";
          }
          pdfComment = new PdfComment(writtenComment);

          if (PDAnnotationTextMarkup.SUB_TYPE_HIGHLIGHT.equals(comment.getSubtype())) {
              pdfComment.setImage(ImageUtils.makeHighlightedSubImage(pageImage, comment.getQuadPoints()));
          } else {
              pdfComment.setImage(ImageUtils.makePlainSubImage(pageImage, comment.getRectangle()));
          }
      }
      else if (anno instanceof PDAnnotationText) {
          String writtenComment = anno.getContents();
          if (writtenComment == null || writtenComment.isEmpty()) {
              writtenComment = "[blank]";
          }
          pdfComment = new PdfComment(writtenComment);

          pdfComment.setImage(ImageUtils.makePopupSubImage(pageImage, anno.getRectangle(), commentBoxImage));
      }
      else if (anno.getContents() != null || anno.getAppearance() != null) {
          String writtenComment = anno.getContents();
          if (writtenComment == null || writtenComment.isEmpty()) {
              writtenComment = "[blank]";
          }
          pdfComment = new PdfComment(writtenComment);

          pdfComment.setImage(ImageUtils.makePlainSubImage(pageImage, anno.getRectangle()));

      }
      return pdfComment;
  }

  /**
   * Updates a list of PdfComment objects to have colors and links to issues
   * @param comments list of PdfComment objects
   * @param repo the GitHub repository the issues will be added to
   */
  public void updateCommentsWithColorsAndLinks(List<PdfComment> comments, Repo repo) {
    PDPageTree pages = document.getDocumentCatalog().getPages();
        int commentOn = 0;
        for(PDPage page : pages) {
            try {
                List<PDAnnotation> newList = new ArrayList<PDAnnotation>();
                List<PDAnnotation> annotations = page.getAnnotations();
                for(int i=0; i<annotations.size(); i++) {
                    PDAnnotation anno = annotations.get(i);

                    if (anno instanceof PDAnnotationTextMarkup) {
                        PdfComment userComment = comments.get(commentOn);
                        commentOn++;
                        String newMessage = userComment.getMessageWithLink(repo);
                        PDAnnotationTextMarkup newComment = makeNewAnnotation((PDAnnotationTextMarkup) anno, userComment, newMessage);

                        newList.add(newComment);
                    } else {
                        newList.add(anno);
                    }
                }
                page.setAnnotations(newList);
            } catch(IOException e) {
                e.printStackTrace();
            } finally {
                //page.clear();

                //Can't find a substitute for this, is it necessary?
                //page.updateLastModified();
            }
        }
    }

    /**
     * Makes a brand new text annotation that is almost exactly like the one passed in.
     * this is the only way I could get the annotations to actually change color.
     * @param comment original PDAnnotation object
     * @param userComment PdfComment object of original PDAnnotation object
     * @param messageWithLink comment message with link to issue in GitHub
     * @return PDAnnotationTextMarkup representing the original annotation with
     * new colors and an issue link.
     */
    private PDAnnotationTextMarkup makeNewAnnotation(PDAnnotationTextMarkup comment, PdfComment userComment, String messageWithLink) {
        PDAnnotationTextMarkup newComment = new PDAnnotationTextMarkup(PDAnnotationTextMarkup.SUB_TYPE_HIGHLIGHT);
        List<Tag> tags = userComment.getTags();
        if (tags.contains(Tag.CONSIDER_FIX) || tags.contains(Tag.POSITIVE)) {
            newComment.setColor(GREEN);
        } else if (tags.contains(Tag.MUST_FIX)) {
            newComment.setColor(ORANGE);
        } else {
            newComment.setColor(YELLOW);
        }
        newComment.setContents(messageWithLink);

        newComment.setRectangle(comment.getRectangle());   //both rectangle and quadpoints are needed... don't know why
        newComment.setQuadPoints(comment.getQuadPoints());
        newComment.setSubject(comment.getSubject());
        newComment.setTitlePopup(comment.getTitlePopup());    //author name
        return newComment;
    }

    /**
     * @return PDDocument object created from the raw PDF data
     */
    public PDDocument getDocument() {
        return document;
    }

    /**
     * Closes the PDDocument object
     */
    public void close() throws IOException {
	    document.close();
	}

  }


text:
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block title %}Cleveland Tech Survey - Password Reset{% endblock %}

{% block page_content %}

Reset Your Password

    {{ wtf.quick_form(form) }}

{% endblock %}


text:
art::RootBranchInfo::RootBranchInfo(TBranch *branch)
  :
  branch_(branch),
  branchName_(branch?branch_->GetName():"")
{}


text:
/*******************************
 * [store.js]
 * Set up the store here.
 *
 * Notes:
 * The store.js file holds the code to facilitate the store of the library.
 * The object 'store' resides in the view.js file but is generated and manipulated with code based here.
 * The actual data that is referenced in the state is stored in the local storage cache.
 * Data in localStorage is accessed through rhaboo.
 ******************************/

/**
* Dependencies
*/
import Rhaboo from './vendor/rhaboo/arr.js';

/**
 * Object
 */
class storeProto {

}

let exposed = new class extends storeProto {
	constructor() {
		super();
		this.state = {};
	}

	init(store) {
		console.log('Initialising the store...');
		console.log('Store before init: ', store);

		//Define
		store.state.lso = Rhaboo.persistent('overlayMagician__store');
		console.log('Store state after Rhaboo definition: ', store.state);
			//Does it automatically link the right store that already existed or does it just make a new one?
			//I should probably do a key search in the local storage instead...
			//Then link the state to this key instead and if not found, only then do new rhaboo persistent like above
			//rhaboo does this automatically already! Reset cache is always a last resort.

		//Check if previous data exists
		if (store.state.lso.images) {
			console.log('Store already exists...');
			console.log('Store: ', store);
			//create(store);

			//var imgList = globalStore.overlayMagician__store.overlayMagician__settings.imgList;

		}else {
			console.log('Gotta create the store...');
			this.create(store);
		}
	}

	create(store) {
		console.log('Incoming store');
		console.log(store);
		console.log('Creating store');
		store.state.lso = Rhaboo.persistent('overlayMagician__store');

		//this.state.write('images', {
		store.state.lso.write('images', {
			cached : [
				//example
				/*
					{
						base64 : base64,
						id : id,
						dimensions : {
							x : x,
							y : y
						},
					},
				*/
			],
			active : [
				//copy of the active image as it resides in the cached array above.
			]
		});
	}

	show(store) {
		//return the store
		console.log('Displaying the store state:');
		console.log(store);
		console.log(store.state);
	}

	write(store, message) {
		console.log('I have received the following value to save to the store:');
		console.log(message);
		//Write to the store, but should be immutable I think.
		//Though...I am holding massive base64 files here. Data will accumelate too quickly.
		store.state.message = message;

		console.log(store.state);
	};
};

/**
 * Export
 */
module.exports = exposed;


text:
<?php

declare(strict_types=1);

namespace WsdlToPhp\PackageGenerator\ConfigurationReader;

final class ServiceReservedMethod extends AbstractReservedWord
{
    public static function getDefaultConfigurationPath(): string
    {
        return __DIR__.'/../resources/config/service_reserved_keywords.yml';
    }
}


text:
package com.gearservice.service;

import com.gearservice.model.cheque.Cheque;
import com.gearservice.model.cheque.Diagnostic;
import com.gearservice.model.request.RequestPreferences;
import com.gearservice.repositories.jpa.*;
import com.gearservice.repositories.mongo.PhotoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

import javax.persistence.EntityNotFoundException;
import java.time.OffsetDateTime;
import java.util.List;

/**
 * Class ChequeService is service, that handle ChequeController
 * Use @Autowired for connect to necessary repositories and entity manager
 *
 * @version 1.1
 * @author Dmitry
 * @since 21.01.2016
 */

@Service
public class ChequeService {

    private final ChequeRepository chequeRepository;
    private final DiagnosticRepository diagnosticRepository;
    private final NoteRepository noteRepository;
    private final PhotoRepository photoRepository;
    private final UserRepository userRepository;
    private final PaymentRepository paymentRepository;

    @Autowired
    public ChequeService(ChequeRepository chequeRepository, DiagnosticRepository diagnosticRepository, NoteRepository noteRepository, PhotoRepository photoRepository, UserRepository userRepository, PaymentRepository paymentRepository) {
        this.chequeRepository = chequeRepository;
        this.diagnosticRepository = diagnosticRepository;
        this.noteRepository = noteRepository;
        this.photoRepository = photoRepository;
        this.userRepository = userRepository;
        this.paymentRepository = paymentRepository;
    }

    /**
     * Method synchronizeCheque save cheque to DB and return it to frontend
     * @param cheque is data for Cheque.class, that was create on client-side
     * @return Cheque, that added
     */
    @Modifying
    @Transactional
    public Cheque synchronizeCheque(@RequestBody Cheque cheque) {
        var ID = cheque.getId();

        if(cheque.getBalance().getCheque() == null)
            cheque.getBalance().setCheque(cheque);

        chequeRepository.save(cheque);

        if(ID == null)
            return chequeRepository.findFirstByOrderByIdDesc();
        else
            return chequeRepository.findById(ID).orElseThrow(EntityNotFoundException::new);
    }

    /**
     * Method getCheque get cheque from DB by id
     * @param chequeID is ID of cheque in database, that client-side wants
     * @return Cheque, that client-side was request
     */
    @Transactional(readOnly = true)
    public Cheque getCheque(@PathVariable Long chequeID) {
        return chequeRepository.findById(chequeID).orElseThrow(EntityNotFoundException::new);
    }

    /**
     * Method deleteCheque remove cheque from DB by id
     * @param chequeID is ID of cheque in database, that client-side wants to delete
     */
    @Modifying
    @Transactional
    public void deleteCheque(@PathVariable Long chequeID) {
        chequeRepository.deleteById(chequeID);
        photoRepository.deleteByChequeId(chequeID.toString());
    }

    /**
     * Method attentionCheques return list of cheque,
     * that wasn't returned to client and wasn't close and hasn't diagnostic comment
     * Use for engineers
     * @return list of cheque filtered by special rules
     */
    @Transactional(readOnly = true)
    public List<Cheque> attentionCheques() {
        return chequeRepository.findByReturnedToClientStatusFalseAndReadyStatusFalseAndDiagnosticsIsNull();
    }

    /**
     * Method attentionChequesByDelay return list of cheque, that has delay in diagnostic
     * Use for engineers
     * @return list of cheque, that has delay in diagnostic
     */
    @Transactional(readOnly = true)
    public List<Cheque> attentionChequesByDelay() {
        return chequeRepository.findWithDelay(OffsetDateTime.now().minusDays(7).toString());
    }

    /**
     * Method getMinChequesList return list of cheque by request without some field for size optimization
     * @param request by which should be returned list of cheques
     * @return list of cheque by request without some field for size optimization
     */
    @Transactional(readOnly = true)
    public Page<Cheque> getMinChequesList(RequestPreferences request, Pageable pageable) {

        return chequeRepository.findByRequest(
                request.getId(),
                request.getIntroducedFrom(),
                request.getIntroducedTo(),
                request.getReturnedToClientFrom(),
                request.getReturnedToClientTo(),
                request.getCustomerName(),
                request.getProductName(),
                request.getModel(),
                request.getSerialNumber(),
                request.getRepresentativeName(),
                request.getPhoneNumber(),
                request.getSecretary(),
                request.getEngineer(),
                request.getWarrantyStatus(),
                request.getReadyStatus(),
                request.getReturnedToClientStatus(),
                request.getPaidStatus(),
                request.getWithoutRepair(),
                pageable
        ).map(source -> {
            Boolean emptyDiagnostics = source.getDiagnostics().isEmpty();
            Boolean hasDelay = !emptyDiagnostics && source.getDiagnostics().stream()
                    .map(Diagnostic::getDate)
                    .max(OffsetDateTime::compareTo)
                    .filter(date -> date.isBefore(OffsetDateTime.now().minusDays(30)))
                    .isPresent();

            if(emptyDiagnostics)
                source.withRecencyStatus(true);

            if(!source.isReadyStatus() && hasDelay)
                source.withDelayStatus(true);

            source.setDiagnostics(null);
            return source;
        });
    }

//    /**
//     * Method readFromExcelToDB read from excel files to DB
//     * @throws Exception
//     */
//    public void readFromExcelToDB() throws Exception {
//
//        FileInputStream excel = new FileInputStream(new File("read.xlsx"));
//
//        XSSFWorkbook wb = new XSSFWorkbook(excel);
//        XSSFSheet sheet = wb.getSheetAt(0);
//
//        Iterator<Row> rowIterator = sheet.rowIterator();
//
//        rowIterator.next();
//
//        List<User> users = userRepository.findAll();
//        Map<String, User> userMap =
//                users.stream().collect(toMap(User::getFullname, user -> user));
//
//        while(rowIterator.hasNext()) {
//
//            Row row = rowIterator.next();
//
//            Iterator<Cell> cellIterator = row.cellIterator();
//
//            Cheque cheque = new Cheque();
//            cheque.setRepairPeriod(99);
//
//            Balance balance = new Balance();
//            balance.setPaidStatus(false);
//
//            Diagnostic diagnosticCheque = new Diagnostic();
//            Note noteCheque = new Note();
//            Note phoneNote = new Note();
//
//            long chequeID = (long) cellIterator.next().getNumericCellValue();
//            cheque.setId(chequeID);
//            System.out.println("chequeID: " + chequeID);
//
//            String customerName = cellIterator.next().getStringCellValue();
//            cheque.setCustomerName(customerName);
//            System.out.println("customerName: " + customerName);
//
//            OffsetDateTime receiptDate = getOffsetDateTime(cellIterator.next().getDateCellValue());
//            cheque.setReceiptDate(receiptDate);
//            System.out.println("receiptDate: " + receiptDate);
//
//            boolean warrantyStatus = cellIterator.next().getStringCellValue().trim().equals("Гарантия");
//            cheque.setWarrantyStatus(warrantyStatus);
//            System.out.println("warrantyStatus: " + warrantyStatus);
//
//            String productName = cellIterator.next().getStringCellValue().trim();
//            cheque.setProductName(productName);
//            System.out.println("productName: " + productName);
//
//            String modelName = cellIterator.next().getStringCellValue().trim();
//            cheque.setModelName(modelName);
//            System.out.println("modelName: " + modelName);
//
//            Cell serialNumber = cellIterator.next();
//            if (serialNumber.getCellType() == Cell.CELL_TYPE_STRING) {
//                cheque.setSerialNumber(serialNumber.getStringCellValue().trim());
//            } else if (serialNumber.getCellType() == Cell.CELL_TYPE_NUMERIC) {
//                cheque.setSerialNumber(String.valueOf(serialNumber.getNumericCellValue()));
//            }
//            System.out.println("serialNumber: " + serialNumber);
//
//            String defect = cellIterator.next().getStringCellValue().trim();
//            cheque.setDefect(defect);
//            System.out.println("defect: " + defect);
//
//            Cell specialNotes = cellIterator.next();
//            if (specialNotes.getCellType() == Cell.CELL_TYPE_STRING) {
//                cheque.setSpecialNotes(specialNotes.getStringCellValue().trim());
//            } else if (specialNotes.getCellType() == Cell.CELL_TYPE_NUMERIC) {
//                cheque.setSpecialNotes(String.valueOf(specialNotes.getNumericCellValue()));
//            }
//
//            cellIterator.next();
//
//            String representativeName = cellIterator.next().getStringCellValue().trim();
//            cheque.setRepresentativeName(representativeName);
//            System.out.println("representativeName: " + representativeName);
//
//            String[] phoneNumber = cellIterator.next().getStringCellValue().trim().split(" ", 1);
//            cheque.setPhoneNumber(phoneNumber[0]);
//            if (phoneNumber.length > 1) {
//                phoneNote.setText("Дополнительные номера телефонов: " +
//                        Stream.of(phoneNumber).filter(pn -> !pn.equals(phoneNumber[0])).collect(joining(", ")));
//            }
//            System.out.println("phoneNumber: " + phoneNumber);
//
//            String address = cellIterator.next().getStringCellValue().trim();
//            cheque.setAddress(address);
//            System.out.println("address: " + address);
//
//            String secretary = cellIterator.next().getStringCellValue().trim();
//            User userSecretary = userMap.get(secretary);
//            System.out.println("secretary: " + secretary);
//
//            String engineer = cellIterator.next().getStringCellValue().trim();
//            User userEngineer = userMap.get(engineer);
//            System.out.println("engineer: " + engineer);
//
//            OffsetDateTime warrantyDate = getOffsetDateTime(cellIterator.next().getDateCellValue());
//            cheque.setWarrantyDate(warrantyDate);
//            System.out.println("warrantyDate: " + warrantyDate);
//
//            int estimatedCost = (int) cellIterator.next().getNumericCellValue();
//            balance.setEstimatedCost(estimatedCost);
//            System.out.println("estimatedCost: " + estimatedCost);
//
//            String diagnostic = cellIterator.next().getStringCellValue().trim();
//            if(diagnostic.length() > 2) {
//                diagnosticCheque.setText(diagnostic);
//                diagnosticCheque.setDate(receiptDate);
//                diagnosticCheque.setUser(userEngineer);
//            }
//            System.out.println("diagnostic: " + diagnostic);
//
//            String ready = cellIterator.next().getStringCellValue().trim();
//            boolean readyStatus = false;
//            if (ready.equals("Готов") || ready.equals("Акт в т\'с") || ready.equals("Без ремонта"))
//                readyStatus = true;
//            cheque.setReadyStatus(readyStatus);
//            System.out.println("readyStatus: " + readyStatus);
//
//            Cell cell = cellIterator.next();
//            if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
//                OffsetDateTime readyDate = getOffsetDateTime(cell.getDateCellValue());
//                cheque.setReadyDate(readyDate);
//                System.out.println("readyDate: " + readyDate);
//            } else {
//                System.out.println("ERROR: " + cell.getStringCellValue());
//            }
//
//            String notes = cellIterator.next().getStringCellValue().trim();
//            if(notes.length() > 2) {
//                noteCheque.setText(notes);
//                noteCheque.setDate(receiptDate);
//                noteCheque.setUser(userSecretary);
//            }
//            System.out.println("notes: " + notes);
//
//            boolean paidStatus = cellIterator.next().getStringCellValue().trim().equals("Да");
//            balance.setPaidStatus(paidStatus);
//
//            boolean returnedToClientStatus = cellIterator.next().getStringCellValue().trim().equals("Да");
//            cheque.setReturnedToClientStatus(returnedToClientStatus);
//            System.out.println("returnedToClientStatus: " + returnedToClientStatus);
//
//            OffsetDateTime returnedToClientDate = getOffsetDateTime(cellIterator.next().getDateCellValue());
//            cheque.setReturnedToClientDate(returnedToClientDate);
//            System.out.println("returnedToClientDate: " + returnedToClientDate);
//
//            System.out.println();
//            System.out.println();
//
//            cheque.setBalance(balance);
//            balance.setCheque(cheque);
//
//            cheque.setEngineer(userEngineer);
//            cheque.setSecretary(userSecretary);
//
//            chequeRepository.save(cheque);
//
//            if (notes.length() > 2) {
//                noteCheque.setCheque(cheque);
//                noteRepository.save(noteCheque);
//            }
//
//            if (phoneNumber.length > 1) {
//                phoneNote.setCheque(cheque);
//                noteRepository.save(phoneNote);
//            }
//
//            if (diagnostic.length() > 2) {
//                diagnosticCheque.setCheque(cheque);
//                diagnosticRepository.save(diagnosticCheque);
//            }
//
//        }
//        excel.close();
//    }
//
//    /**
//     * Method getOffsetDateTime
//     * @param date that should be converted
//     * @return converted OffsetDateTime of null
//     */
//    private static OffsetDateTime getOffsetDateTime(Date date) {
//        if (date != null)
//            return OffsetDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());
//        else
//            return null;
//    }
//
//    private static String getString(Cell cell) {
//        if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
//            return cell.getStringCellValue().trim();
//        } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
//            return String.valueOf(cell.getNumericCellValue()).trim();
//        }
//        return null;
//    }
//
//    public static String getCell(Cell cell) {
//
//        switch (cell.getCellType()) {
//            case Cell.CELL_TYPE_NUMERIC:
//                System.out.print(cell.getNumericCellValue() + "\t\t");
//                break;
//            case Cell.CELL_TYPE_STRING:
//                System.out.print(cell.getStringCellValue() + "\t\t");
//                break;
//        }
//
//        return null;
//    }

}