#include <bits/stdc++.h>
using namespace std;
const int mo = 1e9 + 7;
void ntr(int &x) { x = x >= mo ? x - mo : (x < 0 ? x + mo : x); }
void inc(int &x, int y) { x += y, ntr(x); }
char s[550];
int n, cnt, T[550], pr[20][300], dp[180][1 << 16], lnum = 0, ls[180], rs[180],
                                                   tmp[1 << 16];
void fwt(int *a, int p, int q) {
  for (int i = (1 << n - 1); i >= 1; i >>= 1)
    for (int j = 0; j < (1 << n); j += i << 1)
      for (int k = 0; k <= i - 1; k++) {
        int x = a[j + k], y = a[j + k + i];
        a[j + k] = x + y * p, a[j + k + i] = x * q + y;
        ntr(a[j + k]), ntr(a[j + k + i]);
      }
}
void ifwt(int *a, int p, int q) {
  for (int i = 1; i < (1 << n); i <<= 1)
    for (int j = 0; j < (1 << n); j += i << 1)
      for (int k = 0; k <= i - 1; k++) {
        int x = a[j + k], y = a[j + k + i];
        a[j + k] = x - y * p, a[j + k + i] = y - x * q;
        ntr(a[j + k]), ntr(a[j + k + i]);
      }
}
void build(int &x, int l, int r) {
  x = ++cnt;
  if (l == r) {
    T[x] = s[l];
    ++lnum;
    return;
  }
  int t = 0, k;
  for (int i = l; i <= r; i++) {
    if (s[i] == '(')
      ++t;
    else if (s[i] == ')')
      --t;
    else if (t == 0) {
      k = i;
      break;
    }
  }
  T[x] = s[k];
  build(ls[x], l + 1, k - 2);
  build(rs[x], k + 2, r - 1);
}
void solve(int x) {
  if (!ls[x] && !rs[x]) {
    if (T[x] != '?') {
      int t = 0;
      for (int i = 1; i <= n; i++) t = t * 2 + pr[i][T[x]];
      dp[x][t] = 1;
    } else {
      for (int i = 'a'; i <= 'd'; i++) {
        int t = 0;
        for (int j = 1; j <= n; j++) t = t * 2 + pr[j][i];
        dp[x][t]++;
      }
      for (int i = 'A'; i <= 'D'; i++) {
        int t = 0;
        for (int j = 1; j <= n; j++) t = t * 2 + pr[j][i];
        dp[x][t]++;
      }
    }
    return;
  }
  solve(ls[x]), solve(rs[x]);
  if (T[x] != '?') {
    int y = (T[x] == '&'), z = (T[x] == '|');
    fwt(dp[ls[x]], y, z), fwt(dp[rs[x]], y, z);
    for (int i = 0; i <= (1 << n) - 1; i++)
      dp[x][i] = 1ll * dp[ls[x]][i] * dp[rs[x]][i] % mo;
    ifwt(dp[x], y, z);
  } else {
    int y = ls[x], z = rs[x];
    fwt(dp[y], 0, 1), fwt(dp[z], 0, 1);
    for (int i = 0; i <= (1 << n) - 1; i++)
      dp[x][i] = 1ll * dp[y][i] * dp[z][i] % mo;
    ifwt(dp[y], 0, 1), fwt(dp[y], 1, 0);
    ifwt(dp[z], 0, 1), fwt(dp[z], 1, 0);
    for (int i = 0; i <= (1 << n) - 1; i++)
      tmp[i] = 1ll * dp[y][i] * dp[z][i] % mo;
    ifwt(dp[x], 0, 1), ifwt(tmp, 1, 0);
    for (int i = 0; i <= (1 << n) - 1; i++) inc(dp[x][i], tmp[i]);
  }
}
int main() {
  scanf("%s%d", s, &n);
  int all = 0, rt;
  for (int i = 1; i <= n; i++) {
    for (int j = 'A'; j <= 'D'; j++) scanf("%d", &pr[i][j]);
    for (int j = 'a'; j <= 'd'; j++) pr[i][j] = pr[i][j - 'a' + 'A'] ^ 1;
    int x;
    scanf("%d", &x);
    all = all * 2 + x;
  }
  build(rt, 0, strlen(s) - 1);
  solve(rt);
  return printf("%d\n", dp[rt][all]), 0;
}
