Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. 

The boy has found an online judge with tasks divided by topics they cover. He has picked $p^{k_i}$ problems from $i$-th category ($p$ is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced.

Formally, given $n$ numbers $p^{k_i}$, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo $10^{9}+7$.


-----Input-----

Input consists of multiple test cases. The first line contains one integer $t$ $(1 \leq t \leq 10^5)$ — the number of test cases. Each test case is described as follows:

The first line contains two integers $n$ and $p$ $(1 \leq n, p \leq 10^6)$. The second line contains $n$ integers $k_i$ $(0 \leq k_i \leq 10^6)$.

The sum of $n$ over all test cases doesn't exceed $10^6$.


-----Output-----

Output one integer — the reminder of division the answer by $1\,000\,000\,007$.


-----Example-----
Input
4
5 2
2 3 4 4 3
3 1
2 10 1000
4 5
0 1 1 100
1 8
89

Output
4
1
146981438
747093407



-----Note-----

You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to $2$, but there is also a distribution where the difference is $10^9 + 8$, then the answer is $2$, not $1$.

In the first test case of the example, there're the following numbers: $4$, $8$, $16$, $16$, and $8$. We can divide them into such two sets: ${4, 8, 16}$ and ${8, 16}$. Then the difference between the sums of numbers in sets would be $4$.

Difficulty: HARD

Solutions:
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for j in range(int(input())):
	(n, p) = map(int, input().split())
	vals = list(map(int, input().split()))
	vals.sort()
	if p == 1:
		if n % 2 == 0:
			print(0)
		else:
			print(1)
	else:
		mod = 10 ** 9 + 7
		powers = {0: 1}
		last = 0
		for s in range(n):
			if not vals[s] in powers:
				powers[vals[s]] = pow(p, vals[s], mod)
		a0 = 0
		a1 = 0
		broke = False
		ind = 0
		cv = 0
		find = 0
		num = 0
		for s in range(n - 1, -1, -1):
			if find == 0:
				if cv % 2 == 0:
					a0 += powers[vals[s]]
				else:
					a1 += powers[vals[s]]
				cv += 1
				find = 1
				num = vals[s]
			else:
				if vals[s] == num:
					find -= 1
				else:
					diff = num - vals[s]
					num = vals[s]
					while diff > 0:
						find *= p
						diff -= 1
						if find > s:
							broke = True
							ind = s
							break
					if broke == True:
						break
					find -= 1
				if cv % 2 == 0:
					a0 += powers[vals[s]]
				else:
					a1 += powers[vals[s]]
			a0 = a0 % mod
			a1 = a1 % mod
		if broke == True:
			if cv % 2 == 0:
				for s in range(ind + 1):
					a0 += powers[vals[s]]
					a0 = a0 % mod
				print((a1 - a0) % mod)
			else:
				for s in range(ind + 1):
					a1 += powers[vals[s]]
					a1 = a1 % mod
				print((a0 - a1) % mod)
		elif cv % 2 == 0:
			print((a1 - a0) % mod)
		else:
			print((a0 - a1) % mod)


import sys
input = sys.stdin.readline
mod = 1000000007
t = int(input())
for tests in range(t):
	(n, p) = list(map(int, input().split()))
	K = sorted(map(int, input().split()), reverse=True)
	if p == 1:
		if n % 2 == 0:
			print(0)
		else:
			print(1)
		continue
	ANS = [0, 0]
	flag = 0
	for i in range(n):
		k = K[i]
		if ANS[0] == 0:
			ANS = [1, k]
		elif ANS[1] == k:
			ANS[0] -= 1
		else:
			while ANS[1] > k:
				ANS[0] *= p
				ANS[1] -= 1
				if ANS[0] > 10 ** 7:
					flag = 1
					lastind = i
					break
			if flag == 1:
				A = ANS[0] * pow(p, ANS[1], mod) % mod
				for j in range(lastind, n):
					A = (A - pow(p, K[j], mod)) % mod
				print(A)
				break
			else:
				ANS[0] -= 1
	if flag == 0:
		print(ANS[0] * pow(p, ANS[1], mod) % mod)


from sys import stdin, gettrace, stdout
from collections import defaultdict
if gettrace():
	inputi = input
else:

	def input():
		return next(stdin)[:-1]

	def inputi():
		return stdin.buffer.readline()

def modInt(mod):

	class ModInt:

		def __init__(self, value):
			self.value = value % mod

		def __int__(self):
			return self.value

		def __eq__(self, other):
			return self.value == other.value

		def __hash__(self):
			return hash(self.value)

		def __add__(self, other):
			return ModInt(self.value + int(other))

		def __sub__(self, other):
			return ModInt(self.value - int(other))

		def __mul__(self, other):
			return ModInt(self.value * int(other))

		def __floordiv__(self, other):
			return ModInt(self.value // int(other))

		def __truediv__(self, other):
			return ModInt(self.value * pow(int(other), mod - 2, mod))

		def __pow__(self, exp):
			return pow(self.value, int(exp), mod)

		def __str__(self):
			return str(self.value)
	return ModInt
MOD = 1000000007

def main():
	ModInt = modInt(MOD)

	def solve():
		(n, p) = map(int, inputi().split())
		kk = [int(a) for a in inputi().split()]
		if p == 1:
			print(n % 2)
			return
		kk.sort(reverse=True)
		res = ModInt(0)
		mp = ModInt(p)
		v = 0
		lk = kk[0] + 1
		mxe = 0
		mxp = 1
		while mxp < n:
			mxp *= p
			mxe += 1
		i = len(kk)
		for i in range(len(kk)):
			k = kk[i]
			if lk > k:
				v *= p ** min(lk - k, mxe)
				if v > n:
					for k in kk[i:]:
						res -= mp ** k
					break
				lk = k
			if v == 0:
				res += mp ** k
				v = 1
			else:
				res -= mp ** k
				if v <= n:
					v -= 1
		print(res)
	q = int(inputi())
	for _ in range(q):
		solve()
main()


from sys import stdin, stdout
import math
from collections import defaultdict

def main():
	MOD7 = 1000000007
	t = int(stdin.readline())
	pw = [0] * 21
	for w in range(20, -1, -1):
		pw[w] = int(math.pow(2, w))
	for ks in range(t):
		(n, p) = list(map(int, stdin.readline().split()))
		arr = list(map(int, stdin.readline().split()))
		if p == 1:
			if n % 2 == 0:
				stdout.write('0\n')
			else:
				stdout.write('1\n')
			continue
		arr.sort(reverse=True)
		left = -1
		i = 0
		val = [0] * 21
		tmp = p
		val[0] = p
		slot = defaultdict(int)
		for x in range(1, 21):
			tmp = tmp * tmp % MOD7
			val[x] = tmp
		while i < n:
			x = arr[i]
			if left == -1:
				left = x
			else:
				slot[x] += 1
				tmp = x
				if x == left:
					left = -1
					slot.pop(x)
				else:
					while slot[tmp] % p == 0:
						slot[tmp + 1] += 1
						slot.pop(tmp)
						tmp += 1
					if tmp == left:
						left = -1
						slot.pop(tmp)
			i += 1
		if left == -1:
			stdout.write('0\n')
			continue
		res = 1
		for w in range(20, -1, -1):
			pww = pw[w]
			if pww <= left:
				left -= pww
				res = res * val[w] % MOD7
			if left == 0:
				break
		for (x, c) in slot.items():
			tp = 1
			for w in range(20, -1, -1):
				pww = pw[w]
				if pww <= x:
					x -= pww
					tp = tp * val[w] % MOD7
				if x == 0:
					break
			res = (res - tp * c) % MOD7
		stdout.write(str(res) + '\n')
main()


import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default='z', func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] <= key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
for ik in range(int(input())):
	(n, k) = map(int, input().split())
	l = list(map(int, input().split()))
	l.sort()
	ans1 = pow(k, l[-1], mod1)
	ans = pow(k, l[-1], 1000000007)
	ans2 = pow(k, l[-1], 17)
	for i in range(n - 2, -1, -1):
		if ans == 0 and ans1 == 0 and (ans2 == 0):
			ans = pow(k, l[i], 1000000007)
			ans1 = pow(k, l[i], mod1)
			ans2 = pow(k, l[i], 17)
		else:
			ans -= pow(k, l[i], 1000000007)
			ans %= 10 ** 9 + 7
			ans2 -= pow(k, l[i], 17)
			ans2 %= 17
			ans1 -= pow(k, l[i], mod1)
			ans1 %= mod1
	print(ans)


import os
import sys
from io import BytesIO, IOBase

def main():
	mod = 10 ** 9 + 7

	def po(a, n):
		ans = 1
		while n:
			if n & 1:
				ans = ans * a % mod
			a = a * a % mod
			n //= 2
		return ans
	for _ in range(int(input())):
		(n, p) = map(int, input().split())
		a = [int(x) for x in input().split()]
		if p == 1:
			print(n % 2)
			continue
		a.sort(reverse=True)
		from collections import defaultdict
		d = defaultdict(int)
		for x in a:
			if len(d) == 0:
				d[x] += 1
			else:
				d[x] -= 1
				while len(d) and d[x] % p == 0:
					if d[x] == 0:
						del d[x]
						break
					d[x + 1] += d[x] // p
					del d[x]
					x += 1
		ans = 0
		for x in d.items():
			ans += x[1] * po(p, x[0]) % mod
		print(ans % mod)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
input = sys.stdin.buffer.readline
mod = 10 ** 9 + 7
for _ in range(int(input())):
	(n, p) = map(int, input().split())
	limit = 0
	temp = 1
	if p == 1:
		k = list(map(int, input().split()))
		print(n % 2)
		continue
	while 10 ** 7 >= temp * p:
		limit += 1
		temp *= p
	k = list(map(int, input().split()))
	k.sort()
	ans = 0
	for i in range(n):
		ans = (ans + pow(p, k[i], mod)) % mod
	net = [[k[i], 1] for i in range(n)]
	for i in range(n - 1):
		kurai = net[i][0]
		kurai2 = net[i + 1][0]
		sa = kurai2 - kurai
		if limit >= sa:
			q = net[i][1] // p ** sa
			net[i][1] %= p ** sa
			net[i + 1][1] += q
	new = []
	while net:
		if not new:
			new.append(net[-1])
			net.pop()
		elif new[-1][0] == net[-1][0]:
			net.pop()
		else:
			new.append(net[-1])
			net.pop()
	net = new[::-1]
	id = len(net) - 1
	check = []
	for i in range(n - 1, -1, -1):
		kurai = k[i]
		if kurai != net[id][0]:
			kurai1 = net[id - 1][0]
			kurai2 = net[id][0]
			sa = kurai2 - kurai1
			if sa > limit:
				net[id - 1][1] += 10 ** 7 * (net[id][1] != 0)
			else:
				net[id - 1][1] += min(10 ** 7, net[id][1] * pow(p, sa))
			id -= 1
		if net[id][1] > 1:
			ans = (ans - 2 * pow(p, kurai, mod)) % mod
			net[id][1] -= 2
			check.append(kurai)
	print(ans)


import sys
input = lambda : sys.stdin.readline().rstrip()
T = int(input())
P = 10 ** 9 + 7
for _ in range(T):
	(N, b) = list(map(int, input().split()))
	A = sorted([int(a) for a in input().split()])
	if b == 1:
		print(N % 2)
		continue
	a = A.pop()
	pre = a
	s = 1
	ans = pow(b, a, P)
	while A:
		a = A.pop()
		s *= b ** min(pre - a, 30)
		if s >= len(A) + 5:
			ans -= pow(b, a, P)
			if ans < 0:
				ans += P
			while A:
				a = A.pop()
				ans -= pow(b, a, P)
				if ans < 0:
					ans += P
			print(ans)
			break
		if s:
			s -= 1
			ans -= pow(b, a, P)
			if ans < 0:
				ans += P
			pre = a
		else:
			s = 1
			ans = -ans
			if ans < 0:
				ans += P
			ans += pow(b, a, P)
			if ans >= P:
				ans -= P
			pre = a
	else:
		print(ans)


import sys
input = sys.stdin.readline
MOD = 10 ** 9 + 7
t = int(input())
for _ in range(t):
	(n, p) = map(int, input().split())
	k = [int(item) for item in input().split()]
	if p == 1:
		print(n % 2)
		continue
	k.sort(reverse=True)
	initialized = False
	right = dict()
	for val in k:
		if not initialized:
			left_index = val
			initialized = True
			continue
		if val in right:
			right[val] += 1
		else:
			right[val] = 1
		while right[val] == p:
			right[val] = 0
			if val + 1 in right:
				right[val + 1] += 1
			else:
				right[val + 1] = 1
			val += 1
		if val == left_index:
			initialized = False
			left_index = 0
			right = dict()
	if not initialized:
		print(0)
	else:
		ans = pow(p, left_index, MOD)
		for (key, val) in right.items():
			ans -= pow(p, key, MOD) * val
			ans %= MOD
		print(ans)


import sys
input = sys.stdin.readline
m = 1000000007
for T in range(int(input())):
	(n, p) = list(map(int, input().split()))
	arr = list(map(int, input().split()))
	if p == 1:
		if n & 1:
			print(1)
		else:
			print(0)
		continue
	if n == 1:
		print(pow(p, arr[0], m))
		continue
	arr.sort(reverse=True)
	curr = 0
	c = -1
	for i in range(n):
		if c == -1:
			req = 1
			curr = i
			c = arr[i]
			prev = arr[i]
		else:
			d = prev - arr[i]
			if d > 20:
				break
			req *= p ** d
			prev = arr[i]
			req -= 1
			if req > n:
				break
			if req == 0:
				c = -1
	if c != -1:
		ans = pow(p, c, m)
		for i in range(curr + 1, n):
			ans -= pow(p, arr[i], m)
		print(ans % m)
	else:
		print(0)


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class SegmentTree:

	def __init__(self, data, default=-10 ** 6, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree1:

	def __init__(self, data, default=10 ** 6, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
MOD = 10 ** 9 + 7

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod = 10 ** 9 + 7
omod = 998244353
prime = [True for i in range(50001)]
pp = []

def SieveOfEratosthenes(n=50000):
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	for i in range(50001):
		if prime[i]:
			pp.append(i)
t = int(input())
for i in range(t):
	(n, p) = map(int, input().split())
	power = [int(i) for i in input().split()]
	if p == 1:
		print(n % 2)
	else:
		power.sort(reverse=True)
		ans = [0, 0]
		ok = True
		for i in range(n):
			k = power[i]
			if ans[0] == 0:
				ans = [1, k]
			elif ans[1] == k:
				ans[0] -= 1
			else:
				while ans[1] > k:
					ans[1] -= 1
					ans[0] *= p
					if ans[0] >= n - i + 1:
						ok = False
						ind = i
						break
				if ok == False:
					output = ans[0] * pow(p, ans[1], mod) % mod
					for j in range(ind, n):
						output = (output - pow(p, power[j], mod)) % mod
					print(output)
					break
				else:
					ans[0] -= 1
		if ok:
			print(ans[0] * pow(p, ans[1], mod) % mod)


from math import log2

def main():
	t = int(input())
	allAns = []
	MOD = 10 ** 9 + 7
	for _ in range(t):
		(n, p) = readIntArr()
		a = readIntArr()
		if p == 1:
			if n % 2 == 1:
				ans = 1
			else:
				ans = 0
		else:
			a.sort(reverse=True)
			totalMOD = 0
			totalExact = 0
			prevPow = a[0]
			i = 0
			while i < n:
				x = a[i]
				if totalExact != 0 and log2(totalExact) + (prevPow - x) * log2(p) > log2(n):
					while i < n:
						x = a[i]
						totalMOD -= pow(p, x, MOD)
						totalMOD = (totalMOD + MOD) % MOD
						i += 1
				else:
					if totalExact > 0:
						totalExact *= p ** (prevPow - x)
					prevPow = x
					if totalExact == 0:
						totalMOD += pow(p, x, MOD)
						totalMOD %= MOD
						totalExact += 1
					else:
						totalMOD -= pow(p, x, MOD)
						totalMOD = (totalMOD + MOD) % MOD
						totalExact -= 1
				i += 1
			ans = totalMOD
		allAns.append(ans)
	multiLineArrayPrint(allAns)
	return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]
main()


import sys
input = sys.stdin.readline
for f in range(int(input())):
	(n, p) = map(int, input().split())
	k = list(map(int, input().split()))
	mod = 1000000007
	k.sort(reverse=True)
	left = -1
	right = {}
	for x in k:
		if left == -1:
			left = x
		else:
			if x == left or p == 1:
				left = -1
				right = {}
				continue
			if x in right:
				right[x] += 1
			else:
				right[x] = 1
			if right[x] == p:
				i = x
				done = True
				while i < left and done:
					if right[i] == p:
						right[i] = 0
						if i + 1 in right:
							right[i + 1] += 1
						else:
							right[i + 1] = 1
						i += 1
					else:
						done = False
				if i == left:
					left = -1
					right = {}
	sol = 0
	if left >= 0:
		sol = pow(p, left, mod)
		for x in right:
			sol -= right[x] * pow(p, x, mod)
			sol %= mod
	print(sol)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def print_list(l):
	print(' '.join(map(str, l)))
M = 1000000007
m = 1000000003
for _ in range(N()):
	(n, p) = RL()
	a = RLL()
	a.sort(reverse=True)
	s = 0
	ss = 0
	for i in a:
		t = pow(p, i, M)
		tt = pow(p, i, m)
		if s == 0 and ss == 0:
			s += t
			ss += tt
		else:
			s -= t
			ss -= tt
		s %= M
		ss %= m
	print(s)


import sys
input = sys.stdin.readline
MOD = 10 ** 9 + 7
t = int(input())
for _ in range(t):
	(n, p) = list(map(int, input().split()))
	l = list(map(int, input().split()))
	if p == 1:
		print(n % 2)
	else:
		l.sort(reverse=True)
		curr = l[0]
		out = 0
		real = True
		for v in l:
			if v < curr:
				diff = curr - v
				if 10 ** (7 / diff) < p and out > 0:
					real = False
				out *= pow(p, diff, MOD)
				if out > 10 ** 7:
					real = False
				out %= MOD
				curr = v
			if out > 0 or not real:
				out -= 1
			else:
				out += 1
			out %= MOD
		out *= pow(p, curr, MOD)
		print(out % MOD)


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def fastExponentiation(a, b, N):
	ans = 1
	bDiv2 = b
	aPow2 = a
	while bDiv2 > 0:
		if bDiv2 % 2 != 0:
			ans *= aPow2
			ans %= N
		bDiv2 //= 2
		aPow2 = aPow2 * aPow2
		aPow2 %= N
	return ans
MOD = 1000000007
t = int(input())
for _ in range(t):
	(n, p) = map(int, input().split())
	k = list(map(int, input().split()))
	k.sort(reverse=True)
	estDiff = 0
	curDiff = 0
	curIndex = 0
	lastK = -1
	currentK = -1
	allMinus = False
	if p == 1:
		print(n % 2)
		continue
	while True:
		if curIndex >= n:
			break
		currentK = k[curIndex]
		if estDiff >= 1 and (lastK - currentK >= 20 or estDiff * pow(p, lastK - currentK) >= n):
			allMinus = True
			break
		else:
			multiplier = fastExponentiation(p, lastK - currentK, MOD)
			cnt = 0
			while curIndex < n and currentK == k[curIndex]:
				cnt += 1
				curIndex += 1
			if cnt >= estDiff * multiplier:
				if (cnt + estDiff * multiplier) % 2 == 0:
					estDiff = 0
					curDiff = 0
				else:
					estDiff = 1
					curDiff = fastExponentiation(p, currentK, MOD)
					curDiff %= MOD
			else:
				estDiff = estDiff * multiplier - cnt
				curDiff -= cnt * fastExponentiation(p, currentK, MOD)
				curDiff %= MOD
		lastK = currentK
	if allMinus:
		for elem in k[curIndex:]:
			curDiff -= fastExponentiation(p, elem, MOD)
			curDiff %= MOD
	print(curDiff % MOD)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, p) = map(int, input().split())
	s = list(map(int, input().split()))
	s.sort(reverse=True)
	if p == 1:
		print(n % 2)
		continue
	c = -1
	ci = 0
	for (i, si) in enumerate(s):
		if c == -1:
			c = si
			ls = si
			f = 1
			ci = i
		else:
			d = ls - si
			if d > 20:
				break
			elif d:
				f *= p ** d
			ls = si
			f -= 1
			if f > n:
				break
			if f == 0:
				c = -1
	if c != -1:
		ans = pow(p, c, 1000000007)
		for si in s[ci + 1:]:
			ans -= pow(p, si, 1000000007)
		ans %= 1000000007
		ans += 1000000007
	else:
		ans = 0
	print(ans % 1000000007)


import sys
input = sys.stdin.buffer.readline

def print(val):
	sys.stdout.write(str(val) + '\n')

def prog():
	for _ in range(int(input())):
		(n, p) = map(int, input().split())
		vals = list(map(int, input().split()))
		if p == 1:
			print(n % 2)
		else:
			vals.sort(reverse=True)
			curr_power = 0
			last = vals[0]
			too_large = False
			for a in range(n):
				k = vals[a]
				if k < last and curr_power > 0:
					for i in range(1, last - k + 1):
						curr_power *= p
						if curr_power > n - a:
							too_large = True
							break
					if too_large:
						curr_power %= 1000000007
						curr_power = curr_power * pow(p, last - i, 1000000007)
						mod_diff = curr_power % 1000000007
						for b in range(a, n):
							k = vals[b]
							mod_diff = (mod_diff - pow(p, k, 1000000007)) % 1000000007
						print(mod_diff)
						break
					elif curr_power > 0:
						curr_power -= 1
					else:
						curr_power += 1
				elif curr_power > 0:
					curr_power -= 1
				else:
					curr_power += 1
				last = k
			if not too_large:
				print(curr_power * pow(p, last, 1000000007) % 1000000007)
prog()