#include <bits/stdc++.h>
using namespace std;
int const p = 1e9 + 7, S = 65536;
int mod(int x) { return x >= p ? x - p : x; }
char s[505];
int f[505][1 << 16 | 5], cnt, A[1 << 16 | 5], B[1 << 16 | 5], c[17], d[17];
void init(int x, int c) {
  bool flag = 0;
  int t = 0;
  if (c >= 4) c -= 4, flag = 1;
  for (int i = 0; i < (1 << 4); i++)
    if (((i >> c) & 1) ^ flag) t |= 1 << i;
  f[x][t]++;
}
void fwtor(int *f, int op) {
  for (int len = 1; len < S; len <<= 1)
    for (int i = 0; i < S; i += (len << 1))
      for (int j = i; j < i + len; j++)
        if (op == 1)
          f[j | len] = mod(f[j | len] + f[j]);
        else
          f[j | len] = mod(f[j | len] - f[j] + p);
}
void fwtand(int *f, int op) {
  for (int len = 1; len < S; len <<= 1)
    for (int i = 0; i < S; i += (len << 1))
      for (int j = i; j < i + len; j++)
        if (op == 1)
          f[j] = mod(f[j | len] + f[j]);
        else
          f[j] = mod(f[j] - f[j | len] + p);
}
void con(int x, int l, int r, void fwt(int *, int)) {
  memcpy(A, f[l], sizeof(A)), memcpy(B, f[r], sizeof(B));
  fwt(A, 1), fwt(B, 1);
  for (int i = 0; i < S; i++) A[i] = 1ll * A[i] * B[i] % p;
  fwt(A, -1);
  for (int i = 0; i < S; i++) f[x][i] = mod(f[x][i] + A[i]);
}
int build(int l, int r) {
  int x = ++cnt;
  if (l == r) {
    if (s[l] == '?')
      for (int i = 0; i < 4; i++) init(x, i), init(x, i + 4);
    else if (isupper(s[l]))
      init(x, s[l] - 'A');
    else
      init(x, s[l] - 'a' + 4);
    return x;
  }
  int now = 0, mid = 0;
  for (int i = l; i <= r; i++) {
    if (s[i] == '(')
      now++;
    else if (s[i] == ')')
      now--;
    if (!now) {
      mid = i + 1;
      break;
    }
  }
  int ls = build(l + 1, mid - 2), rs = build(mid + 2, r - 1);
  if (s[mid] != '&') con(x, ls, rs, fwtor);
  if (s[mid] != '|') con(x, ls, rs, fwtand);
  return x;
}
int main() {
  scanf("%s", s + 1);
  int m = strlen(s + 1), root = build(1, m), res = 0, n, x;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    for (int j = 0; j < 4; j++) scanf("%d", &x), c[i] |= x << j;
    scanf("%d", &d[i]);
  }
  for (int i = 0; i < S; i++)
    if (f[root][i]) {
      bool flag = 0;
      for (int j = 1; j <= n; j++)
        if (((i >> c[j]) & 1) != d[j]) {
          flag = 1;
          break;
        }
      if (!flag) res = mod(res + f[root][i]);
    }
  cout << res;
  return 0;
}
