#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
int add(int x, int y) { return x + y < mod ? x + y : x + y - mod; }
void ade(int& x, int y) {
  x += y;
  if (x >= mod) x -= mod;
}
char ch[550];
int n;
int m;
int cv[22][11];
int f[505][80080];
int ls[505], rs[505];
int tot;
int get(int p, int x) {
  if (p < 4)
    return cv[x][p];
  else
    return cv[x][p - 4] ^ 1;
}
int lim;
void FWT_and(int* a, int sym) {
  int a1, a2;
  for (int mid = 1, R; mid < lim; mid <<= 1) {
    R = mid << 1;
    for (int j = 0; j < lim; j += R)
      for (int k = 0; k < mid; ++k) {
        a1 = a[j + k];
        a2 = a[j + mid + k];
        a[j + k] = (a1 + sym * a2) % mod;
        (a[j + k] += mod) %= mod;
      }
  }
}
void FWT_or(int* a, int sym) {
  int a1, a2;
  for (int mid = 1, R; mid < lim; mid <<= 1) {
    R = mid << 1;
    for (int j = 0; j < lim; j += R)
      for (int k = 0; k < mid; ++k) {
        a1 = a[j + k];
        a2 = a[j + mid + k];
        a[j + mid + k] = (a2 + sym * a1) % mod;
        (a[j + mid + k] += mod) %= mod;
      }
  }
}
int gc(char c) { return (c <= 'D') ? c - 'A' : c - 'a' + 4; }
int a[100100], b[100100];
int f_and[100100];
void get_and(int x, int y) {
  for (int i = 0; i < lim; ++i) a[i] = f[x][i], b[i] = f[y][i];
  FWT_and(a, 1);
  FWT_and(b, 1);
  for (int i = 0; i < lim; ++i) f_and[i] = 1ll * a[i] * b[i] % mod;
  FWT_and(f_and, -1);
}
int f_or[100100];
void get_or(int x, int y) {
  for (int i = 0; i < lim; ++i) a[i] = f[x][i], b[i] = f[y][i];
  FWT_or(a, 1);
  FWT_or(b, 1);
  for (int i = 0; i < lim; ++i) f_or[i] = 1ll * a[i] * b[i] % mod;
  FWT_or(f_or, -1);
}
void solve(int& x, int l, int r) {
  x = ++tot;
  if (l == r) {
    if (ch[l] != '?') {
      int c = gc(ch[l]);
      int s = 0;
      for (int i = 0; i < m; ++i) s |= (get(c, i) << i);
      f[x][s] = 1;
      return;
    }
    for (int i = 0, s; i <= 7; ++i) {
      s = 0;
      for (int j = 0; j < m; ++j) s |= (get(i, j) << j);
      f[x][s]++;
    }
    return;
  }
  int s = 0, mid;
  for (int i = l;; ++i) {
    if (ch[i] == '(')
      s++;
    else if (ch[i] == ')')
      s--;
    if (!s) {
      mid = i;
      break;
    }
  }
  solve(ls[x], l + 1, mid - 1);
  solve(rs[x], mid + 3, r - 1);
  get_and(ls[x], rs[x]);
  get_or(ls[x], rs[x]);
  for (int i = 0; i < lim; ++i) {
    if (ch[mid + 1] != '&') ade(f[x][i], f_or[i]);
    if (ch[mid + 1] != '|') ade(f[x][i], f_and[i]);
  }
  return;
}
int main() {
  scanf("%s", ch + 1);
  n = strlen(ch + 1);
  scanf("%d", &m);
  lim = 1 << m;
  int u = 0;
  for (int i = 0; i < m; ++i) {
    for (int j = 0; j < 5; ++j) scanf("%d", &cv[i][j]);
    u |= (cv[i][4] << i);
  }
  int rt;
  solve(rt, 1, n);
  printf("%d\n", f[1][u]);
  return 0;
}
