Пример #1
0
 forceinline bool 
 same(const Item& i, const Item& j) {
   return same(i.bin(),j.bin()) && (i.size() == j.size());
 }
Пример #2
0
bool equalAsStr(bool v1, const StringData *v2) {
  return same(toString(v1), v2);
}
Пример #3
0
bool f_is_callable(CVarRef v, bool syntax /* = false */,
                   VRefParam name /* = null */) {
  if (v.isString()) {
    if (name.isReferenced()) name = v;
    if (syntax) return true;

    String str = v.toString();
    int c = str.find("::");
    if (c != 0 && c != String::npos && c + 2 < str.size()) {
      String classname = str.substr(0, c);
      String methodname = str.substr(c + 2);
      return f_class_exists(classname) &&
        ClassInfo::HasAccess(classname, methodname, true, false);
    }
    return f_function_exists(str);
  }

  if (v.is(KindOfArray)) {
    Array arr = v.toArray();
    if (arr.size() == 2 && arr.exists(0LL) && arr.exists(1LL)) {
      Variant v0 = arr.rvalAt(0LL);
      Variant v1 = arr.rvalAt(1LL);
      Object obj;
      bool staticCall = false;
      if (v0.is(KindOfObject)) {
        obj = v0.toObject();
        v0 = obj->o_getClassName();
      } else if (v0.isString()) {
        if (!f_class_exists(v0.toString())) {
          return false;
        }
        staticCall = true;
      }
      if (v1.isString()) {
        String str = v1.toString();
        int c = str.find("::");
        if (c != 0 && c != String::npos && c + 2 < str.size()) {
          String name1 = v0.toString();
          String name2 = str.substr(0, c);
          ASSERT(name1.get() && name2.get());
          if (name1->isame(name2.get()) ||
              ClassInfo::IsSubClass(name1, name2, false)) {
            staticCall = true;
            v0 = name2;
            v1 = str.substr(c + 2);
          }
        }
      }
      if (v0.isString() && v1.isString()) {
        if (name.isReferenced()) {
          name = v0.toString() + "::" + v1.toString();
        }
        if (same(v0, s_self) || same(v0, s_parent)) {
          throw NotImplementedException("augmenting class scope info");
        }
        return ClassInfo::HasAccess(v0, v1, staticCall, !obj.isNull());
      }
    }
  }

  if (v.isObject()) {
    ObjectData *d = v.objectForCall();
    if (name.isReferenced()) {
      name = d->o_getClassName() + "::__invoke";
    }
    void *extra;
    const CallInfo *cit = d->t___invokeCallInfoHelper(extra);
    return cit != NULL;
  }

  if (name.isReferenced()) {
    name = v.toString();
  }
  return false;
}
Пример #4
0
bool String::same(litstr v2) const {
  return same(String(v2));
}
Пример #5
0
static int create_accessor( grib_section* p, grib_action* act,grib_loader *h)
{
	int i,id;
	grib_action_alias* self = (grib_action_alias*)act;
	grib_accessor *x=NULL ;
	grib_accessor *y=NULL ;

	/*if alias and target have the same name add only the namespace */
	if (self->target && !strcmp(act->name,self->target) && act->name_space!=NULL) {
		x = grib_find_accessor_fast(p->h,self->target);
		if(x == NULL)
		{
			grib_context_log(p->h->context,GRIB_LOG_WARNING,"alias %s: cannot find %s",
							 act->name,self->target);
			return GRIB_SUCCESS;
		}

		if (x->name_space==NULL) 
			x->name_space=act->name_space;
		
		i = 0;
		while(i < MAX_ACCESSOR_NAMES) {
			if(x->all_names[i] != NULL && !strcmp(x->all_names[i],act->name) ) {
				if (x->all_name_spaces[i]==NULL) {
					x->all_name_spaces[i] =  act->name_space;
					return GRIB_SUCCESS;
				} else if (!strcmp(x->all_name_spaces[i],act->name_space) ) {
					return GRIB_SUCCESS;
				}
			}
			i++;
		}
		i=0;
		while(i < MAX_ACCESSOR_NAMES) {
			if (x->all_names[i]==NULL) {
				x->all_names[i]=act->name;
				x->all_name_spaces[i] =  act->name_space;
				return GRIB_SUCCESS;
			}
			i++;
		}
		grib_context_log(p->h->context,GRIB_LOG_FATAL,
						 "unable to alias %s : increase MAX_ACCESSOR_NAMES",act->name);

		return GRIB_INTERNAL_ERROR;
	}

	/* if(self->target == NULL || (act->flags & GRIB_ACCESSOR_FLAG_OVERRIDE)) */
	y = grib_find_accessor_fast(p->h,act->name);

	/* delete old alias if already defined */
	if ( y != NULL )
	{
		i=0;
		while ( i < MAX_ACCESSOR_NAMES && y->all_names[i] )
		{
			if ( same ( y->all_names[i],act->name ) && same ( y->all_name_spaces[i],act->name_space ) )
			{

				grib_context_log ( p->h->context,GRIB_LOG_DEBUG,"alias %s.%s already defined for %s. Deleting old alias",
								   act->name_space,act->name,y->name );
				/* printf("[%s %s]\n",y->all_names[i], y->all_name_spaces[i]); */

				while ( i < MAX_ACCESSOR_NAMES-1 )
				{
					y->all_names[i]       = y->all_names[i+1];
					y->all_name_spaces[i] = y->all_name_spaces[i+1];
					i++;
				}

				y->all_names[MAX_ACCESSOR_NAMES-1]       =  NULL;
				y->all_name_spaces[MAX_ACCESSOR_NAMES-1] =  NULL;

				break;
			}
			i++;
		}

		if ( self->target == NULL )
			return GRIB_SUCCESS;
	}

    if (!self->target) return GRIB_SUCCESS;
    
	x = grib_find_accessor_fast(p->h,self->target);
	if(x == NULL)
	{
		grib_context_log(p->h->context,GRIB_LOG_WARNING,"alias %s: cannot find %s",
				act->name,self->target);
		return GRIB_SUCCESS;
	}

	if (x->parent->h->use_trie) {
		id=grib_hash_keys_get_id(x->parent->h->context->keys,act->name);

		if (x->parent->h->accessors[id] != x) {
			/*x->same=x->parent->h->accessors[id];*/
			x->parent->h->accessors[id]=x;
		}
	}


	i = 0;
	while(i < MAX_ACCESSOR_NAMES) {
		if(x->all_names[i] == NULL)
		{
			x->all_names[i]       =  act->name;
			x->all_name_spaces[i] =  act->name_space;
			return GRIB_SUCCESS;
		}
		i++;
	}

	for(i = 0 ; i < MAX_ACCESSOR_NAMES; i++)
		grib_context_log(p->h->context,GRIB_LOG_ERROR,"alias %s= ( %s already bound to %s )",
				act->name,self->target,x->all_names[i]);

	return GRIB_SUCCESS;
}
Пример #6
0
BOOST_AUTO_TEST_CASE_TEMPLATE
( test_neighbor_upper_bound, Tp, quad_sets )
{
  typedef quadrance<typename Tp::container_type, int, quad_diff> metric_type;
  typedef typename metric_type::distance_type distance_type;
  typedef neighbor_iterator<typename Tp::container_type, metric_type>
    neighbor_iterator_type;
  // Prove that you can find lower bound with N nodes, down to 1 node
  {
    Tp fix(100, randomize(-20, 20));
    metric_type metric;
    quad target;
    while (!fix.container.empty())
      {
        randomize(-22, 22)(target, 0, 0);
        // Find min and max dist first
        distance_type min_dist;
        distance_type max_dist;
        typename Tp::container_type::iterator it = fix.container.begin();
        min_dist = max_dist
          = metric.distance_to_key(fix.container.rank()(), *it, target);
        ++it;
        for (; it != fix.container.end(); ++it)
          {
            distance_type tmp
              = metric.distance_to_key(fix.container.rank()(), *it, target);
            if (tmp < min_dist) min_dist = tmp;
            if (tmp > max_dist) max_dist = tmp;
          }
        distance_type avg_dist = (min_dist + max_dist) / 2;
        // use this knowledge to test the upper bound
        neighbor_iterator_type i
          = neighbor_upper_bound(fix.container, metric, target, min_dist);
        BOOST_CHECK(i != neighbor_begin(fix.container, metric, target));
        if (i != neighbor_end(fix.container, metric, target))
          { BOOST_CHECK_LT(min_dist, distance(i)); }
        BOOST_CHECK_EQUAL(min_dist, distance(--i));
        i = neighbor_upper_bound(fix.container, metric, target, max_dist);
        BOOST_CHECK(i == neighbor_end(fix.container, metric, target));
        i = neighbor_upper_bound(fix.container, metric, target, avg_dist);
        if (i != neighbor_end(fix.container, metric, target))
          { BOOST_CHECK_GT(distance(i), avg_dist); }
        if (i == neighbor_end(fix.container, metric, target))
          { BOOST_CHECK_LE(distance(--i), avg_dist); }
        fix.container.erase(i);
      }
  }
  // Prove that you can find the upper bound when node and target are same
  {
    Tp fix(100, same());
    metric_type metric;
    quad target;
    same()(target, 0, 100);
    // All points and targets are the same.
    while (!fix.container.empty())
      {
        neighbor_iterator_type i
          = neighbor_upper_bound(fix.container, metric, target, 1);
        BOOST_CHECK(i == neighbor_end(fix.container, metric, target));
        i = neighbor_upper_bound(fix.container, metric, target, 0);
        BOOST_CHECK(i == neighbor_end(fix.container, metric, target));
        fix.container.erase(--i);
      }
  }
  // Prove that you can find the upper bound in an unbalanced tree
  {
    Tp fix(100, increase());
    metric_type metric;
    quad target;
    while (!fix.container.empty())
      {
        randomize(0, 100)(target, 0, 0);
        // Find min and max dist first
        distance_type min_dist;
        distance_type max_dist;
        typename Tp::container_type::iterator it = fix.container.begin();
        min_dist = max_dist
          = metric.distance_to_key(fix.container.rank()(), *it, target);
        ++it;
        for (; it != fix.container.end(); ++it)
          {
            distance_type tmp
              = metric.distance_to_key(fix.container.rank()(), *it, target);
            if (tmp < min_dist) min_dist = tmp;
            if (tmp > max_dist) max_dist = tmp;
          }
        distance_type avg_dist = (min_dist + max_dist) / 2;
        // Use this knowledge to test the upper bound
        neighbor_iterator_type i
          = neighbor_upper_bound(fix.container, metric, target, min_dist);
        BOOST_CHECK(i != neighbor_begin(fix.container, metric, target));
        if (i != neighbor_end(fix.container, metric, target))
          { BOOST_CHECK_LT(min_dist, distance(i)); }
        BOOST_CHECK_EQUAL(min_dist, distance(--i));
        i = neighbor_upper_bound(fix.container, metric, target, max_dist);
        BOOST_CHECK(i == neighbor_end(fix.container, metric, target));
        i = neighbor_upper_bound(fix.container, metric, target, avg_dist);
        if (i != neighbor_end(fix.container, metric, target))
          { BOOST_CHECK_GT(distance(i), avg_dist); }
        if (i == neighbor_end(fix.container, metric, target))
          { BOOST_CHECK_LE(distance(--i), avg_dist); }
        fix.container.erase(i);
      }
  }
  // Prove that you can find the upper bound in an unbalanced tree
  {
    Tp fix(100, decrease());
    metric_type metric;
    quad target;
    while (!fix.container.empty())
      {
        randomize(0, 100)(target, 0, 0);
        // Find min and max dist first
        distance_type min_dist;
        distance_type max_dist;
        typename Tp::container_type::iterator it = fix.container.begin();
        min_dist = max_dist
          = metric.distance_to_key(fix.container.rank()(), *it, target);
        ++it;
        for (; it != fix.container.end(); ++it)
          {
            distance_type tmp
              = metric.distance_to_key(fix.container.rank()(), *it, target);
            if (tmp < min_dist) min_dist = tmp;
            if (tmp > max_dist) max_dist = tmp;
          }
        distance_type avg_dist = (min_dist + max_dist) / 2;
        // Use this knowledge to test the upper bound
        neighbor_iterator_type i
          = neighbor_upper_bound(fix.container, metric, target, min_dist);
        BOOST_CHECK(i != neighbor_begin(fix.container, metric, target));
        if (i != neighbor_end(fix.container, metric, target))
          { BOOST_CHECK_LT(min_dist, distance(i)); }
        BOOST_CHECK_EQUAL(min_dist, distance(--i));
        i = neighbor_upper_bound(fix.container, metric, target, max_dist);
        BOOST_CHECK(i == neighbor_end(fix.container, metric, target));
        i = neighbor_upper_bound(fix.container, metric, target, avg_dist);
        if (i != neighbor_end(fix.container, metric, target))
          { BOOST_CHECK_GT(distance(i), avg_dist); }
        if (i == neighbor_end(fix.container, metric, target))
          { BOOST_CHECK_LE(distance(--i), avg_dist); }
        fix.container.erase(i);
      }
  }
}
constexpr bool sameTemporary(const int &n) { return same(n, n); }
Пример #8
0
 forceinline bool
 before(const ScaleView<Val,UnsVal>& x, const ScaleView<Val,UnsVal>& y) {
   return before(x.base(),y.base())
     || (same(x.base(),y.base()) && (x.scale() < y.scale()));
 }
Пример #9
0
bool DisjointSets::same(const vector<int>& v) {
  for (int i : All(v))
    if (!same(v[i], v[0]))
      return false;
  return true;
}
Пример #10
0
void SnapshotLoader::load(ConcurrentTableSharedStore& s) {
  // This could share code with apc_load_impl_compressed, but that function
  // should go away together with the shared object format.
  {
    std::vector<KeyValuePair> ints(read32());
    for (auto& item : ints) {
      item.key = readString().begin();
      s.constructPrime(read64(), item);
    }
    s.prime(ints);
  }
  {
    std::vector<KeyValuePair> chars(read32());
    for (auto& item : chars) {
      item.key = readString().begin();
      switch (static_cast<SnapshotBuilder::CharBasedType>(read<char>())) {
        case SnapshotBuilder::kSnapFalse:
          s.constructPrime(false, item);
          break;
        case SnapshotBuilder::kSnapTrue:
          s.constructPrime(true, item);
          break;
        case SnapshotBuilder::kSnapNull:
          s.constructPrime(uninit_null(), item);
          break;
        default:
          assert(false);
          break;
      }
    }
    s.prime(chars);
  }
  auto numStringBased = read32();
  CHECK(numStringBased == SnapshotBuilder::kNumStringBased);
  for (int i = 0; i < numStringBased; ++i) {
    auto type = static_cast<SnapshotBuilder::StringBasedType>(i);
    std::vector<KeyValuePair> items(read32());
    for (auto& item : items) {
      item.key = readString().begin();
      auto data = readString();
      String value(data.begin(), data.size(), CopyString);
      switch (type) {
        case SnapshotBuilder::kSnapString:
          s.constructPrime(value, item, false);
          break;
        case SnapshotBuilder::kSnapObject:
          s.constructPrime(value, item, true);
          break;
        case SnapshotBuilder::kSnapThrift: {
          Variant success;
          Variant v = HHVM_FN(fb_unserialize)(value, ref(success));
          if (same(success, false)) {
            throw Exception("bad apc archive, fb_unserialize failed");
          }
          s.constructPrime(v, item);
          break;
        }
        case SnapshotBuilder::kSnapOther: {
          Variant v = unserialize_from_string(value);
          if (same(v, false)) {
            throw Exception("bad apc archive, unserialize_from_string failed");
          }
          s.constructPrime(v, item);
          break;
        }
        default:
          assert(false);
          break;
      }
    }
    s.prime(items);
  }
  {
    const char* disk = m_begin + header().diskOffset;
    std::vector<KeyValuePair> items(read32());
    for (auto& item : items) {
      item.key = readString().begin();
      item.sSize = read32();
      item.sAddr = const_cast<char*>(disk);
      disk += abs(item.sSize) + 1;  // \0
    }
    assert(disk == m_begin + m_size);
    s.prime(items);
  }
  // TODO(9755912): Use 'madvise' to indicate we are done with Index now,
  // or better+harder: avoid copying the keys and guard against freeing them.
  assert(m_cur == m_begin + header().diskOffset);
}
Пример #11
0
 forceinline bool
 same(const ScaleView<Val,UnsVal>& x, const ScaleView<Val,UnsVal>& y) {
   return same(x.base(),y.base()) && (x.scale() == y.scale());
 }
Пример #12
0
 forceinline BoolTest
 bool_test(const NegBoolView& b0, const NegBoolView& b1) {
   return same(b0,b1) ? BT_SAME : BT_NONE;
 }
Пример #13
0
 forceinline BoolTest
 bool_test(const NegBoolView& b0, const BoolView& b1) {
   return same(b0.base(),b1) ? BT_COMP : BT_NONE;
 }
Пример #14
0
 forceinline bool
 before(const Item& i, const Item& j) {
   return before(i.bin(),j.bin())
     || (same(i.bin(),j.bin()) && (i.size() == j.size()));
 }
Пример #15
0
char *
phonetic( char *Word )
{
	char           *n, *n_start, *n_end;	/* pointers to string */
	char           *metaph_end;	/* pointers to metaph */
	char            ntrans[40];	/* word with uppercase letters */
	int             KSflag;	/* state flag for X -> KS */
	char		buf[MAXPHONEMELEN + 2];
	char		*Metaph;

	/*
	 * Copy Word to internal buffer, dropping non-alphabetic characters
	 * and converting to upper case
	 */

	for (n = ntrans + 4, n_end = ntrans + 35; !iswordbreak( *Word ) &&
	    n < n_end; Word++) {
		if (isalpha((unsigned char)*Word))
			*n++ = TOUPPER((unsigned char)*Word);
	}
	Metaph = buf;
	*Metaph = '\0';
	if (n == ntrans + 4) {
		return( ch_strdup( buf ) );		/* Return if null */
	}
	n_end = n;		/* Set n_end to end of string */

	/* ntrans[0] will always be == 0 */
	ntrans[0] = '\0';
	ntrans[1] = '\0';
	ntrans[2] = '\0';
	ntrans[3] = '\0';
	*n++ = 0;
	*n++ = 0;
	*n++ = 0;
	*n = 0;			/* Pad with nulls */
	n = ntrans + 4;		/* Assign pointer to start */

	/* Check for PN, KN, GN, AE, WR, WH, and X at start */
	switch (*n) {
	case 'P':
	case 'K':
	case 'G':
		/* 'PN', 'KN', 'GN' becomes 'N' */
		if (*(n + 1) == 'N')
			*n++ = 0;
		break;
	case 'A':
		/* 'AE' becomes 'E' */
		if (*(n + 1) == 'E')
			*n++ = 0;
		break;
	case 'W':
		/* 'WR' becomes 'R', and 'WH' to 'H' */
		if (*(n + 1) == 'R')
			*n++ = 0;
		else if (*(n + 1) == 'H') {
			*(n + 1) = *n;
			*n++ = 0;
		}
		break;
	case 'X':
		/* 'X' becomes 'S' */
		*n = 'S';
		break;
	}

	/*
	 * Now, loop step through string, stopping at end of string or when
	 * the computed 'metaph' is MAXPHONEMELEN characters long
	 */

	KSflag = 0;		/* state flag for KS translation */
	for (metaph_end = Metaph + MAXPHONEMELEN, n_start = n;
	     n <= n_end && Metaph < metaph_end; n++) {
		if (KSflag) {
			KSflag = 0;
			*Metaph++ = 'S';
		} else {
			/* Drop duplicates except for CC */
			if (*(n - 1) == *n && *n != 'C')
				continue;
			/* Check for F J L M N R or first letter vowel */
			if (same(*n) || (n == n_start && vowel(*n)))
				*Metaph++ = *n;
			else
				switch (*n) {
				case 'B':

					/*
					 * B unless in -MB
					 */
					if (n == (n_end - 1) && *(n - 1) != 'M')
						*Metaph++ = *n;
					break;
				case 'C':

					/*
					 * X if in -CIA-, -CH- else S if in
					 * -CI-, -CE-, -CY- else dropped if
					 * in -SCI-, -SCE-, -SCY- else K
					 */
					if (*(n - 1) != 'S' || !frontv(*(n + 1))) {
						if (*(n + 1) == 'I' && *(n + 2) == 'A')
							*Metaph++ = 'X';
						else if (frontv(*(n + 1)))
							*Metaph++ = 'S';
						else if (*(n + 1) == 'H')
							*Metaph++ = ((n == n_start && !vowel(*(n + 2)))
							 || *(n - 1) == 'S')
							    ? (char) 'K' : (char) 'X';
						else
							*Metaph++ = 'K';
					}
					break;
				case 'D':

					/*
					 * J if in DGE or DGI or DGY else T
					 */
					*Metaph++ = (*(n + 1) == 'G' && frontv(*(n + 2)))
					    ? (char) 'J' : (char) 'T';
					break;
				case 'G':

					/*
					 * F if in -GH and not B--GH, D--GH,
					 * -H--GH, -H---GH else dropped if
					 * -GNED, -GN, -DGE-, -DGI-, -DGY-
					 * else J if in -GE-, -GI-, -GY- and
					 * not GG else K
					 */
					if ((*(n + 1) != 'J' || vowel(*(n + 2))) &&
					    (*(n + 1) != 'N' || ((n + 1) < n_end &&
								 (*(n + 2) != 'E' || *(n + 3) != 'D'))) &&
					    (*(n - 1) != 'D' || !frontv(*(n + 1))))
						*Metaph++ = (frontv(*(n + 1)) &&
							     *(n + 2) != 'G') ? (char) 'G' : (char) 'K';
					else if (*(n + 1) == 'H' && !noghf(*(n - 3)) &&
						 *(n - 4) != 'H')
						*Metaph++ = 'F';
					break;
				case 'H':

					/*
					 * H if before a vowel and not after
					 * C, G, P, S, T else dropped
					 */
					if (!varson(*(n - 1)) && (!vowel(*(n - 1)) ||
							   vowel(*(n + 1))))
						*Metaph++ = 'H';
					break;
				case 'K':

					/*
					 * dropped if after C else K
					 */
					if (*(n - 1) != 'C')
						*Metaph++ = 'K';
					break;
				case 'P':

					/*
					 * F if before H, else P
					 */
					*Metaph++ = *(n + 1) == 'H' ?
					    (char) 'F' : (char) 'P';
					break;
				case 'Q':

					/*
					 * K
					 */
					*Metaph++ = 'K';
					break;
				case 'S':

					/*
					 * X in -SH-, -SIO- or -SIA- else S
					 */
					*Metaph++ = (*(n + 1) == 'H' ||
						     (*(n + 1) == 'I' && (*(n + 2) == 'O' ||
							  *(n + 2) == 'A')))
					    ? (char) 'X' : (char) 'S';
					break;
				case 'T':

					/*
					 * X in -TIA- or -TIO- else 0 (zero)
					 * before H else dropped if in -TCH-
					 * else T
					 */
					if (*(n + 1) == 'I' && (*(n + 2) == 'O' ||
							   *(n + 2) == 'A'))
						*Metaph++ = 'X';
					else if (*(n + 1) == 'H')
						*Metaph++ = '0';
					else if (*(n + 1) != 'C' || *(n + 2) != 'H')
						*Metaph++ = 'T';
					break;
				case 'V':

					/*
					 * F
					 */
					*Metaph++ = 'F';
					break;
				case 'W':

					/*
					 * W after a vowel, else dropped
					 */
				case 'Y':

					/*
					 * Y unless followed by a vowel
					 */
					if (vowel(*(n + 1)))
						*Metaph++ = *n;
					break;
				case 'X':

					/*
					 * KS
					 */
					if (n == n_start)
						*Metaph++ = 'S';
					else {
						*Metaph++ = 'K';	/* Insert K, then S */
						KSflag = 1;
					}
					break;
				case 'Z':

					/*
					 * S
					 */
					*Metaph++ = 'S';
					break;
				}
		}
	}

	*Metaph = 0;		/* Null terminate */
	return( ch_strdup( buf ) );
}
Пример #16
0
main(){
	int i,j,k,l,t,r,rr;
	for(i=k=0;i<24;i++){
		k*=D;
		k+=ini[i];
		k%=M;
	}
	for(i=0;i<24;i++)hash[k][i]=ini[i];
	tr[k]=-1;
	back[k]=-1;
	bfs[0]=k;
	tim[k]=0;
	for(i=0,j=1;tim[bfs[i]]<8;i++){
		if(exam[bfs[i]]!=3)
			step(i,j,l,10,1,0,0);
		if(exam[bfs[i]]!=4)
			step(i,j,l,2,2,12,0);
		if(exam[bfs[i]]!=1)
			step(i,j,l,2,3,0,0);
		if(exam[bfs[i]]!=2)
			step(i,j,l,10,4,12,0);
	}
	scanf("%d",&t);
	while(t--){
		for(i=k=0;i<24;i++){
			scanf("%d",&a[i]);
			k*=D;
			k+=a[i];
			k%=M;
		}
		while(tr[k]==-1){
			if(same(k,a)==1)break;
			k++;
			if(k==M)k=0;
		}
		if(tr[k]==-1){
			if(tim[k]==0)puts("PUZZLE ALREADY SOLVED");
			else{
				print1(k);
				puts("");
			}
		}
		else{
			tt++;
			for(i=0;i<24;i++)hash[k][i]=a[i];
			bfs[0]=k;
			exam[k]=0;
			tim[k]=0;
			back[k]=-1;
			tr[k]=tt;
			for(i=0,j=1;tim[bfs[i]]<8;i++){
				if(exam[bfs[i]]!=3 && (r=step(i,j,l,10,1,0,1))>0)
					break;
				if(exam[bfs[i]]!=4 && (r=step(i,j,l,2,2,12,1))>0)
					break;
				if(exam[bfs[i]]!=1 && (r=step(i,j,l,2,3,0,1))>0)
					break;
				if(exam[bfs[i]]!=2 && (r=step(i,j,l,10,4,12,1))>0)
					break;
			}
			if(tim[bfs[i]]>=8)puts("NO SOLUTION WAS FOUND IN 16 STEPS");
			else{
				print2(bfs[i]);
				printf("%d",r);
				print1(l);
				puts("");
			}
		}
	}
}
Пример #17
0
bool TestExtMb::test_mb_list_encodings() {
  VERIFY(!same(f_array_search("UTF-8", f_mb_list_encodings()), false));
  return Count(true);
}
Пример #18
0
bool PDOSqliteStatement::paramHook(PDOBoundParam *param,
                                   PDOParamEvent event_type) {
  switch (event_type) {
  case PDO_PARAM_EVT_EXEC_PRE:
    if (executed && !m_done) {
      sqlite3_reset(m_stmt);
      m_done = 1;
    }

    if (param->is_param) {
      if (param->paramno == -1) {
        param->paramno = sqlite3_bind_parameter_index(m_stmt,
                                                      param->name.c_str()) - 1;
      }

      switch (PDO_PARAM_TYPE(param->param_type)) {
      case PDO_PARAM_STMT:
        return false;

      case PDO_PARAM_NULL:
        if (sqlite3_bind_null(m_stmt, param->paramno + 1) == SQLITE_OK) {
          return true;
        }
        handleError(__FILE__, __LINE__);
        return false;

      case PDO_PARAM_INT:
      case PDO_PARAM_BOOL:
        if (param->parameter.isNull()) {
          if (sqlite3_bind_null(m_stmt, param->paramno + 1) == SQLITE_OK) {
            return true;
          }
        } else {
          if (SQLITE_OK == sqlite3_bind_int(m_stmt, param->paramno + 1,
                                            param->parameter.toInt64())) {
            return true;
          }
        }
        handleError(__FILE__, __LINE__);
        return false;

      case PDO_PARAM_LOB:
        if (param->parameter.isResource()) {
          Variant buf = f_stream_get_contents(param->parameter);
          if (!same(buf, false)) {
            param->parameter = buf;
          } else {
            pdo_raise_impl_error(dbh, this, "HY105",
                                 "Expected a stream resource");
            return false;
          }
        } else if (param->parameter.isNull()) {
          if (sqlite3_bind_null(m_stmt, param->paramno + 1) == SQLITE_OK) {
            return true;
          }
          handleError(__FILE__, __LINE__);
          return false;
        }

        {
          String sparam = param->parameter.toString();
          if (SQLITE_OK == sqlite3_bind_blob(m_stmt, param->paramno + 1,
                                             sparam.data(), sparam.size(),
                                             SQLITE_STATIC)) {
            return true;
          }
        }
        handleError(__FILE__, __LINE__);
        return false;

      case PDO_PARAM_STR:
      default:
        if (param->parameter.isNull()) {
          if (sqlite3_bind_null(m_stmt, param->paramno + 1) == SQLITE_OK) {
            return true;
          }
        } else {
          String sparam = param->parameter.toString();
          if (SQLITE_OK == sqlite3_bind_text(m_stmt, param->paramno + 1,
                                             sparam.data(), sparam.size(),
                                             SQLITE_STATIC)) {
            return true;
          }
        }
        handleError(__FILE__, __LINE__);
        return false;
      }
    }
    break;

  default:;
  }
  return true;
}
Пример #19
0
BOOST_AUTO_TEST_CASE_TEMPLATE
( test_neighbor_decrement, Tp, int2_maps )
{
  // Prove that you can iterate N nodes, down to 1 node
  {
    Tp fix(100, randomize(-20, 20));
    int2 target;
    typedef typename neighbor_iterator<typename Tp::container_type>
      ::distance_type distance_type;
    while (!fix.container.empty())
      {
        randomize(-22, 22)(target, 0, 0);
        size_t countdown = fix.container.size();
        std::reverse_iterator<neighbor_iterator<typename Tp::container_type> >
          iter(--neighbor_end(fix.container, target)),
          end(neighbor_begin(fix.container, target));
        distance_type max_dist = distance(iter.base());
        for(; --countdown != 0 && iter != end; ++iter)
          {
            distance_type tmp = distance(iter.base());
            BOOST_CHECK_LE(tmp, max_dist);
            max_dist = tmp;
          }
        BOOST_CHECK_EQUAL(countdown, 0u);
        BOOST_CHECK(iter == end);
        fix.container.erase(fix.container.begin());
      }
  }
  // Prove that you can iterate a very unbalanced tree
  {
    Tp fix(40, increase());
    int2 target;
    typedef typename neighbor_iterator<typename Tp::container_type>
      ::distance_type distance_type;
    while (!fix.container.empty())
      {
        randomize(0, 40)(target, 0, 0);
        size_t countdown = fix.container.size();
        std::reverse_iterator<neighbor_iterator<typename Tp::container_type> >
          iter(--neighbor_end(fix.container, target)),
          end(neighbor_begin(fix.container, target));
        distance_type max_dist = distance(iter.base());
        for(; --countdown != 0 && iter != end; ++iter)
          {
            distance_type tmp = distance(iter.base());
            BOOST_CHECK_LE(tmp, max_dist);
            max_dist = tmp;
          }
        BOOST_CHECK_EQUAL(countdown, 0u);
        BOOST_CHECK(iter == end);
        fix.container.erase(fix.container.begin());
      }
  }
  // Prove that you can iterate an opposite unbalanced tree
  {
    Tp fix(40, decrease());
    int2 target;
    typedef typename neighbor_iterator<typename Tp::container_type>
      ::distance_type distance_type;
    while (!fix.container.empty())
      {
        randomize(0, 40)(target, 0, 0);
        size_t countdown = fix.container.size();
        std::reverse_iterator<neighbor_iterator<typename Tp::container_type> >
          iter(--neighbor_end(fix.container, target)),
          end(neighbor_begin(fix.container, target));
        distance_type max_dist = distance(iter.base());
        for(; --countdown != 0 && iter != end; ++iter)
          {
            distance_type tmp = distance(iter.base());
            BOOST_CHECK_LE(tmp, max_dist);
            max_dist = tmp;
          }
        BOOST_CHECK_EQUAL(countdown, 0u);
        BOOST_CHECK(iter == end);
        fix.container.erase(fix.container.begin());
      }
  }
  // Prove that you can iterate equivalent nodes
  {
    int2 target;
    same()(target, 0, 100);
    Tp fix(100, same());
    std::reverse_iterator<neighbor_iterator<typename Tp::container_type> >
      iter(neighbor_end(fix.container, target)),
      end(neighbor_begin(fix.container, target));
    size_t count = 1;
    ++iter;
    for(; iter != end && count < fix.container.size(); ++iter, ++count)
      {
        BOOST_CHECK_CLOSE(distance(iter.base()), 0.0, 0.000000001);
      }
    BOOST_CHECK(iter == end);
    BOOST_CHECK_EQUAL(count, fix.container.size());
  }
}
Пример #20
0
bool TestExtMysql::test_mysql_pconnect() {
  Variant conn = f_mysql_pconnect(TEST_HOSTNAME, TEST_USERNAME, TEST_PASSWORD);
  VERIFY(!same(conn, false));
  return Count(true);
}
Пример #21
0
static EjsAny *invokeUriOperator(Ejs *ejs, EjsUri *lhs, int opcode,  EjsUri *rhs, void *data)
{
    EjsAny      *result;

    if (rhs == 0 || TYPE(lhs) != TYPE(rhs)) {
        if ((result = coerceUriOperands(ejs, lhs, opcode, rhs)) != 0) {
            return result;
        }
    }

    /*  Types now match, both Uris
     */
    switch (opcode) {
    case EJS_OP_COMPARE_STRICTLY_EQ:
    case EJS_OP_COMPARE_EQ:
        if (lhs == rhs || (lhs->uri == rhs->uri)) {
            return ESV(true);
        }
        return ejsCreateBoolean(ejs,  same(ejs, lhs->uri, rhs->uri, 1));

    case EJS_OP_COMPARE_NE:
    case EJS_OP_COMPARE_STRICTLY_NE:
        return ejsCreateBoolean(ejs,  !same(ejs, lhs->uri, rhs->uri, 1));

    /*  NOTE: these only compare the paths */
    case EJS_OP_COMPARE_LT:
        return ejsCreateBoolean(ejs,  scmp(lhs->uri->path, rhs->uri->path) < 0);

    case EJS_OP_COMPARE_LE:
        return ejsCreateBoolean(ejs,  scmp(lhs->uri->path, rhs->uri->path) <= 0);

    case EJS_OP_COMPARE_GT:
        return ejsCreateBoolean(ejs,  scmp(lhs->uri->path, rhs->uri->path) > 0);

    case EJS_OP_COMPARE_GE:
        return ejsCreateBoolean(ejs,  scmp(lhs->uri->path, rhs->uri->path) >= 0);

    /*  
        Unary operators
     */
    case EJS_OP_COMPARE_NOT_ZERO:
        return ((lhs->uri->path) ? ESV(true): ESV(false));

    case EJS_OP_COMPARE_ZERO:
        return ((lhs->uri->path == 0) ? ESV(true): ESV(false));


    case EJS_OP_COMPARE_UNDEFINED:
    case EJS_OP_COMPARE_NULL:
    case EJS_OP_COMPARE_FALSE:
    case EJS_OP_COMPARE_TRUE:
        return ESV(false);

    /*  
        Binary operators
     */
    case EJS_OP_ADD:
        return uri_join(ejs, lhs, 1, (EjsObj**) (void*) &rhs);

    default:
        ejsThrowTypeError(ejs, "Opcode %d not implemented for type %@", opcode, TYPE(lhs)->qname.name);
        return 0;
    }
    assert(0);
}
Пример #22
0
void ProvidedTests() {

  std::cout << "Begin ProvidedTests..." << std::endl;

  // The test data (stored in STL lists)
  std::list<std::string> songs;
  songs.push_back("hound dog");
  songs.push_back("poker face");
  songs.push_back("brown eyed girl");
  songs.push_back("let it be");
  songs.push_back("walk like an egyptian");
  songs.push_back("man in the mirror");
  songs.push_back("stairway to heaven");
  songs.push_back("dancing in the street");
  songs.push_back("every breath you take");
  songs.push_back("hotel california");
  // the same data, sorted!
  std::list<std::string> sorted_songs(songs);
  sorted_songs.sort();


  // create an empty multi-linked list and fill it with the test data
  MultiLL<std::string> my_list;
  for (std::list<std::string>::iterator itr = songs.begin(); itr != songs.end(); itr++) {
    my_list.add(*itr);
  }
  assert (songs.size() == my_list.size());



  // -------------------
  // iterator tests

  // test the chronological iterator (forwards)
  std::cout << "chronological order" << std::endl;
  std::list<std::string> chrono_order;
  MultiLL<std::string>::iterator itr = my_list.begin_chronological();
  while (itr != my_list.end_chronological()) {
    std::cout << "  " << *itr << std::endl;
    chrono_order.push_back(*itr);
    itr++;
  }
  std::cout << std::endl;
  assert (same(songs,chrono_order));


  // test the sorted order iterator (forwards)
  std::cout << "sorted order" << std::endl;
  std::list<std::string> sorted_order;
  itr = my_list.begin_sorted();
  while (itr != my_list.end_sorted()) {
    std::cout << "  " << *itr << std::endl;
    sorted_order.push_back(*itr);
    itr++;
  }
  std::cout << std::endl;
  assert (same(sorted_songs,sorted_order));


  // test the random order iterator
  std::cout << "random order" << std::endl;
  std::list<std::string> random_order;
  itr = my_list.begin_random();
  for (unsigned int i = 0; i < my_list.size(); i++,itr++) {
    std::cout << "  " << *itr << std::endl;
    random_order.push_back(*itr);
  }
  std::cout << std::endl;
  // loop through the elements a second time (the order should be the same!)
  std::list<std::string>::iterator itr2 = random_order.begin();
  for (unsigned int i = 0; i < my_list.size(); i++,itr++,itr2++) {
    // verify that the elements repeat the order
    assert (*itr == *itr2);
  }
  std::list<std::string> random_order_check(random_order);
  random_order_check.sort();
  // verify that all of the elements appeared in the initial loop
  assert (same(sorted_songs,random_order_check));



  // test the re-randomization by creating a new random iterator
  std::cout << "random order 2" << std::endl;
  std::list<std::string> random_order2;
  itr = my_list.begin_random();
  for (unsigned int i = 0; i < my_list.size(); i++,itr++) {
    std::cout << "  " << *itr << std::endl;
    random_order2.push_back(*itr);
  }
  std::cout << std::endl;
  // with over 3 million different possible permutations of 10
  // elements, it is highly unlikely they will be the same!
  assert (!same(random_order,random_order2));


  
  // -------------------
  // erase tests

  // erase the first element inserted
  itr = my_list.begin_chronological();
  assert (*itr == "hound dog");
  itr = my_list.erase(itr);
  assert (*itr == "poker face");
  assert (my_list.size() == 9);
  std::cout << "erased: hound dog" << std::endl;

  // erase the second to last element in sorted order
  itr = my_list.begin_sorted();
  for (int i = 0; i < 7; i++) { itr++; }
  assert (*itr == "stairway to heaven");
  itr = my_list.erase(itr);
  assert (*itr == "walk like an egyptian");
  assert (my_list.size() == 8);  
  std::cout << "erased: stairway to heaven" << std::endl;

  // erase the third element in the random order
  itr = my_list.begin_random();
  itr++;
  itr++;
  std::string tmp = *itr;
  // note that the return value of erase with a random iterator is undefined
  my_list.erase(itr);
  std::cout << "erased: " << tmp << std::endl;
  assert (my_list.size() == 7);
  assert (!my_list.empty());

  my_list.clear();
  assert (my_list.empty());
  assert (my_list.size() == 0);
  std::cout << "cleared the whole list!" << std::endl << std::endl;

  std::cout << "Finished ProvidedTests." << std::endl;
}
Пример #23
0
  ExecStatus
  IteDom<View>::propagate(Space& home, const ModEventDelta& med) {
    if (b.one())
      GECODE_REWRITE(*this,(Rel::EqDom<View,View>::post(home(*this),x2,x0)));
    if (b.zero())
      GECODE_REWRITE(*this,(Rel::EqDom<View,View>::post(home(*this),x2,x1)));

    GECODE_ME_CHECK(x2.lq(home,std::max(x0.max(),x1.max())));
    GECODE_ME_CHECK(x2.gq(home,std::min(x0.min(),x1.min())));

    if (View::me(med) != ME_INT_DOM) {
      RelTest eq20 = rtest_eq_bnd(x2,x0);
      RelTest eq21 = rtest_eq_bnd(x2,x1);

      if ((eq20 == RT_FALSE) && (eq21 == RT_FALSE))
        return ES_FAILED;

      if (eq20 == RT_FALSE) {
        GECODE_ME_CHECK(b.zero_none(home));
        if (eq21 == RT_TRUE)
          return home.ES_SUBSUMED(*this);
        else
          GECODE_REWRITE(*this,
                         (Rel::EqDom<View,View>::post(home(*this),x2,x1)));
      }
      
      if (eq21 == RT_FALSE) {
        GECODE_ME_CHECK(b.one_none(home));
        if (eq20 == RT_TRUE)
          return home.ES_SUBSUMED(*this);
        else
          GECODE_REWRITE(*this,
                         (Rel::EqDom<View,View>::post(home(*this),x2,x0)));
      }
    
      if ((eq20 == RT_TRUE) && (eq21 == RT_TRUE))
        return home.ES_SUBSUMED(*this);

      return home.ES_FIX_PARTIAL(*this,View::med(ME_INT_DOM));
    }

    RelTest eq20 = rtest_eq_dom(x2,x0);
    RelTest eq21 = rtest_eq_dom(x2,x1);

    if ((eq20 == RT_FALSE) && (eq21 == RT_FALSE))
      return ES_FAILED;

    if (eq20 == RT_FALSE) {
      GECODE_ME_CHECK(b.zero_none(home));
      if (eq21 == RT_TRUE)
        return home.ES_SUBSUMED(*this);
      else
        GECODE_REWRITE(*this,
                       (Rel::EqDom<View,View>::post(home(*this),x2,x1)));
    }
      
    if (eq21 == RT_FALSE) {
      GECODE_ME_CHECK(b.one_none(home));
      if (eq20 == RT_TRUE)
        return home.ES_SUBSUMED(*this);
      else
        GECODE_REWRITE(*this,
                       (Rel::EqDom<View,View>::post(home(*this),x2,x0)));
    }
    
    assert((eq20 != RT_TRUE) || (eq21 != RT_TRUE));

    ViewRanges<View> r0(x0), r1(x1);
    Iter::Ranges::Union<ViewRanges<View>,ViewRanges<View> > u(r0,r1);
    
    if (!same(x0,x2) && !same(x1,x2))
      GECODE_ME_CHECK(x2.inter_r(home,u,false));
    else
      GECODE_ME_CHECK(x2.inter_r(home,u,true));

    return ES_FIX;
  }
Пример #24
0
bool RPCRequestHandler::executePHPFunction(Transport *transport,
                                           SourceRootInfo &sourceRootInfo) {
  ExecutionContext *context = hphp_context_init();

  // reset timeout counter
  ThreadInfo::s_threadInfo->m_reqInjectionData.started = time(0);

  std::string rpcFunc = transport->getCommand();
  {
    ServerStatsHelper ssh("input");
    RequestURI reqURI(rpcFunc);
    HttpProtocol::PrepareSystemVariables(transport, reqURI, sourceRootInfo);
    sourceRootInfo.clear();
  }

  bool error = false;

  Array params;
  std::string sparams = transport->getParam("params");
  if (!sparams.empty()) {
    Variant jparams = f_json_decode(String(sparams), true);
    if (jparams.isArray()) {
      params = jparams.toArray();
    } else {
      error = true;
    }
  } else {
    vector<string> sparams;
    transport->getArrayParam("p", sparams);
    if (!sparams.empty()) {
      for (unsigned int i = 0; i < sparams.size(); i++) {
        Variant jparams = f_json_decode(String(sparams[i]), true);
        if (same(jparams, false)) {
          error = true;
          break;
        }
        params.append(jparams);
      }
    } else {
      // single string parameter, used by xbox to avoid any en/decoding
      int size;
      const void *data = transport->getPostData(size);
      if (data && size) {
        params.append(String((char*)data, size, AttachLiteral));
      }
    }
  }

  if (transport->getIntParam("reset") == 1) {
    m_reset = true;
  }
  int output = transport->getIntParam("output");

  int code;
  if (!error) {
    Variant funcRet;
    std::string errorMsg = "Internal Server Error";
    string warmupDoc, reqInitFunc;
    if (m_serverInfo) {
      warmupDoc = m_serverInfo->getWarmupDoc();
      reqInitFunc = m_serverInfo->getReqInitFunc();
    }
    if (warmupDoc.empty()) {
      warmupDoc = RuntimeOption::WarmupDocument;
      reqInitFunc = RuntimeOption::RequestInitFunction;
    }
    warmupDoc = canonicalize_path(warmupDoc, "", 0);
    warmupDoc = get_source_filename(warmupDoc.c_str());
    bool ret = hphp_invoke(context, rpcFunc, true, params, ref(funcRet),
                           warmupDoc, reqInitFunc, error, errorMsg);
    if (ret) {
      String response;
      switch (output) {
      case 0: response = f_json_encode(funcRet);   break;
      case 1: response = context->obGetContents(); break;
      case 2:
        response =
          f_json_encode(CREATE_MAP2("output", context->obGetContents(),
                                    "return", f_json_encode(funcRet)));
        break;
      }
      code = 200;
      transport->sendRaw((void*)response.data(), response.size());
    } else if (error) {
      code = 500;
      transport->sendString(errorMsg, 500);
      m_reset = true;
    } else {
      code = 404;
      transport->sendString("Not Found", 404);
    }
  } else {
    code = 400;
    transport->sendString("Bad Request", 400);
  }
  params.reset();

  transport->onSendEnd();
  ServerStats::LogPage(rpcFunc, code);

  hphp_context_exit(context, true, false);
  return !error;
}
Пример #25
0
bool equalAsStr(double v1, litstr  v2) {
  return same(String(v1), v2);
}
Пример #26
0
int metaphone(const char *Word, char *Metaph, int max_phones) {
    char *n, *n_start, *n_end;    /* Pointers to string               */
    char *metaph_start = Metaph, *metaph_end;    
    /* Pointers to metaph         */
    int ntrans_len = strlen(Word)+4;
    char *ntrans = (char *)malloc(sizeof(char) * ntrans_len);
    /* Word with uppercase letters      */
    int KSflag;                   /* State flag for X translation     */

    /* SDE -- special case: if the word starts with a number, just
     * copy the leading digits and return. This means we don't
     * metaphone cardinal number suffixes (i.e. "st","nd","rd") */
    int leading_digit = isdigit(*Word);
    /* SDE -- check for a leading semivowel. needed because
     * the copy in ntrans gets destroyed by the metaphone process. */
    char leading_semivowel = '\0';

    /*
     ** Copy word to internal buffer, dropping non-alphabetic characters
     ** and converting to upper case.
     */
    for (n = ntrans + 1, n_end = ntrans + ntrans_len - 2;
            *Word && n < n_end; ++Word)
    {
        /* SDE -- see previous comment */
        if (leading_digit && isalpha(*Word))
            break;
        /* SDE -- copy numbers as well, for geocoding street names */
        /* was: if (isalpha(*Word)) */
        if (isalnum(*Word)) 
            *n++ = toupper(*Word);
    }

    if (n == ntrans + 1) {
        free(ntrans);
        Metaph[0]='\0';
        return 0;           /* Return if zero characters        */
    }
    else  n_end = n;          /* Set end of string pointer        */

    /*
     ** Pad with '\0's, front and rear
     */

    *n++ = '\0';
    *n   = '\0';
    n    = ntrans;
    *n++ = '\0';
    
    /* SDE: check for leading semivowel here */
    if (ntrans[1] == 'W' || ntrans[1] == 'Y')
        leading_semivowel = ntrans[1];

    /*
     ** Check for PN, KN, GN, WR, WH, and X at start
     */

    switch (*n)
    {
        case 'P':
        case 'K':
        case 'G':
            if ('N' == *(n + 1))
                *n++ = '\0';
            break;

        case 'A':
            if ('E' == *(n + 1))
                *n++ = '\0';
            break;

        case 'W':
            if ('R' == *(n + 1))
                *n++ = '\0';
            else if ('H' == *(n + 1))
            {
                *(n + 1) = *n;
                *n++ = '\0';
            }
            break;

        case 'X':
            *n = 'S';
            break;
    }

    /*
     ** Now loop through the string, stopping at the end of the string
     ** or when the computed Metaphone code is max_phones characters long.
     */

    KSflag = 0;              /* State flag for KStranslation     */
    for (metaph_end = Metaph + max_phones, n_start = n;
            n <= n_end && Metaph < metaph_end; ++n)
    {
        if (KSflag)
        {
            KSflag = 0;
            *Metaph++ = *n;
        }
        else
        {
            /* SDE -- special case: copy numbers verbatim */
            if (isdigit(*n)) {
                *Metaph++ = *n;
                continue;
            }

            /* Drop duplicates except for CC    */
            if (*(n - 1) == *n && *n != 'C')
                continue;

            /* Check for F J L M N R  or first letter vowel */

            if (same(*n) || (n == n_start && vowel(*n)))
                *Metaph++ = *n;
            else switch (*n)
            {
                case 'B':
                    if (n < n_end || *(n - 1) != 'M')
                        *Metaph++ = *n;
                    break;

                case 'C':
                    if (*(n - 1) != 'S' || !frontv(*(n + 1)))
                    {
                        if ('I' == *(n + 1) && 'A' == *(n + 2))
                            *Metaph++ = 'X';
                        else if (frontv(*(n + 1)))
                            *Metaph++ = 'S';
                        else if ('H' == *(n + 1))
                            *Metaph++ = ((n == n_start &&
                                        !vowel(*(n + 2))) ||
                                    'S' == *(n - 1)) ? 'K' : 'X';
                        else  *Metaph++ = 'K';
                    }
                    break;

                case 'D':
                    *Metaph++ = ('G' == *(n + 1) && frontv(*(n + 2))) ?
                        'J' : 'T';
                    break;

                case 'G':
                    if ((*(n + 1) != 'H' || vowel(*(n + 2))) &&
                            (*(n + 1) != 'N' || ((n + 1) < n_end &&
                                                 (*(n + 2) != 'E' || *(n + 3) != 'D'))) &&
                            (*(n - 1) != 'D' || !frontv(*(n + 1))))
                    {
                        *Metaph++ = (frontv(*(n + 1)) &&
                                *(n + 2) != 'G') ? 'J' : 'K';
                    }
                    else if ('H' == *(n + 1) && !noghf(*(n - 3)) &&
                            *(n - 4) != 'H')
                    {
                        *Metaph++ = 'F';
                    }
                    break;

                case 'H':
                    if (!varson(*(n - 1)) && (!vowel(*(n - 1)) ||
                                vowel(*(n + 1))))
                    {
                        *Metaph++ = 'H';
                    }
                    break;

                case 'K':
                    if (*(n - 1) != 'C')
                        *Metaph++ = 'K';
                    break;

                case 'P':
                    *Metaph++ = ('H' == *(n + 1)) ? 'F' : 'P';
                    break;

                case 'Q':
                    *Metaph++ = 'K';
                    break;

                case 'S':
                    *Metaph++ = ('H' == *(n + 1) || ('I' == *(n + 1) &&
                                ('O' == *(n + 2) || 'A' == *(n + 2)))) ?
                        'X' : 'S';
                    break;

                case 'T':
                    if ('I' == *(n + 1) && ('O' == *(n + 2) ||
                                'A' == *(n + 2)))
                    {
                        *Metaph++ = 'X';
                    }
                    else if ('H' == *(n + 1))
                        /* SDE: was:
                           *Metaph++ = 'O';
                           but that's WRONG. */
                        *Metaph++ = '0';
                    else if (*(n + 1) != 'C' || *(n + 2) != 'H')
                        *Metaph++ = 'T';
                    break;

                case 'V':
                    *Metaph++ = 'F';
                    break;

                case 'W':
                case 'Y':
                    if (vowel(*(n + 1)))
                        *Metaph++ = *n;
                    break;

                case 'X':
                    if (n == n_start)
                        *Metaph++ = 'S';
                    else
                    {
                        *Metaph++ = 'K';
                        KSflag = 1;
                    }
                    break;

                case 'Z':
                    *Metaph++ = 'S';
                    break;
            }
        }
    }

    /* SDE: special case: if word consists solely of W or Y, use that. */
    if (Metaph == metaph_start && leading_semivowel)
        *Metaph++ = leading_semivowel;

    *Metaph = '\0';
    free(ntrans);
    return strlen(metaph_start);
}
Пример #27
0
bool TestExtStream::test_stream_select() {
  Variant f = f_fopen("test/test_ext_file.txt", "r");
  Variant reads = CREATE_VECTOR1(f);
  VERIFY(!same(f_stream_select(ref(reads), uninit_null(), uninit_null(), 0, 0), false));
  return Count(true);
}
Пример #28
0
int threeway_merge(const struct cache_entry * const *stages,
		   struct unpack_trees_options *o)
{
	const struct cache_entry *index;
	const struct cache_entry *head;
	const struct cache_entry *remote = stages[o->head_idx + 1];
	int count;
	int head_match = 0;
	int remote_match = 0;

	int df_conflict_head = 0;
	int df_conflict_remote = 0;

	int any_anc_missing = 0;
	int no_anc_exists = 1;
	int i;

	for (i = 1; i < o->head_idx; i++) {
		if (!stages[i] || stages[i] == o->df_conflict_entry)
			any_anc_missing = 1;
		else
			no_anc_exists = 0;
	}

	index = stages[0];
	head = stages[o->head_idx];

	if (head == o->df_conflict_entry) {
		df_conflict_head = 1;
		head = NULL;
	}

	if (remote == o->df_conflict_entry) {
		df_conflict_remote = 1;
		remote = NULL;
	}

	/*
	 * First, if there's a #16 situation, note that to prevent #13
	 * and #14.
	 */
	if (!same(remote, head)) {
		for (i = 1; i < o->head_idx; i++) {
			if (same(stages[i], head)) {
				head_match = i;
			}
			if (same(stages[i], remote)) {
				remote_match = i;
			}
		}
	}

	/*
	 * We start with cases where the index is allowed to match
	 * something other than the head: #14(ALT) and #2ALT, where it
	 * is permitted to match the result instead.
	 */
	/* #14, #14ALT, #2ALT */
	if (remote && !df_conflict_head && head_match && !remote_match) {
		if (index && !same(index, remote) && !same(index, head))
			return reject_merge(index, o);
		return merged_entry(remote, index, o);
	}
	/*
	 * If we have an entry in the index cache, then we want to
	 * make sure that it matches head.
	 */
	if (index && !same(index, head))
		return reject_merge(index, o);

	if (head) {
		/* #5ALT, #15 */
		if (same(head, remote))
			return merged_entry(head, index, o);
		/* #13, #3ALT */
		if (!df_conflict_remote && remote_match && !head_match)
			return merged_entry(head, index, o);
	}

	/* #1 */
	if (!head && !remote && any_anc_missing)
		return 0;

	/*
	 * Under the "aggressive" rule, we resolve mostly trivial
	 * cases that we historically had git-merge-one-file resolve.
	 */
	if (o->aggressive) {
		int head_deleted = !head;
		int remote_deleted = !remote;
		const struct cache_entry *ce = NULL;

		if (index)
			ce = index;
		else if (head)
			ce = head;
		else if (remote)
			ce = remote;
		else {
			for (i = 1; i < o->head_idx; i++) {
				if (stages[i] && stages[i] != o->df_conflict_entry) {
					ce = stages[i];
					break;
				}
			}
		}

		/*
		 * Deleted in both.
		 * Deleted in one and unchanged in the other.
		 */
		if ((head_deleted && remote_deleted) ||
		    (head_deleted && remote && remote_match) ||
		    (remote_deleted && head && head_match)) {
			if (index)
				return deleted_entry(index, index, o);
			if (ce && !head_deleted) {
				if (verify_absent(ce, ERROR_WOULD_LOSE_UNTRACKED_REMOVED, o))
					return -1;
			}
			return 0;
		}
		/*
		 * Added in both, identically.
		 */
		if (no_anc_exists && head && remote && same(head, remote))
			return merged_entry(head, index, o);

	}

	/* Below are "no merge" cases, which require that the index be
	 * up-to-date to avoid the files getting overwritten with
	 * conflict resolution files.
	 */
	if (index) {
		if (verify_uptodate(index, o))
			return -1;
	}

	o->nontrivial_merge = 1;

	/* #2, #3, #4, #6, #7, #9, #10, #11. */
	count = 0;
	if (!head_match || !remote_match) {
		for (i = 1; i < o->head_idx; i++) {
			if (stages[i] && stages[i] != o->df_conflict_entry) {
				keep_entry(stages[i], o);
				count++;
				break;
			}
		}
	}
#if DBRT_DEBUG
	else {
		fprintf(stderr, "read-tree: warning #16 detected\n");
		show_stage_entry(stderr, "head   ", stages[head_match]);
		show_stage_entry(stderr, "remote ", stages[remote_match]);
	}
#endif
	if (head) { count += keep_entry(head, o); }
	if (remote) { count += keep_entry(remote, o); }
	return count;
}
Пример #29
0
bool TestExtNetwork::test_socket_set_blocking() {
  Variant f = f_fsockopen("facebook.com", 80);
  VERIFY(!same(f, false));
  f_socket_set_blocking(f, 0);
  return Count(true);
}
Пример #30
0
req::ptr<File> HttpStreamWrapper::open(const String& filename,
                                       const String& mode, int /*options*/,
                                       const req::ptr<StreamContext>& context) {
  if (RuntimeOption::ServerHttpSafeMode && !is_cli_mode()) {
    return nullptr;
  }

  if (strncmp(filename.data(), "http://",  sizeof("http://")  - 1) &&
      strncmp(filename.data(), "https://", sizeof("https://") - 1)) {
    return nullptr;
  }

  Array headers;
  String method = s_GET;
  String post_data = null_string;
  String proxy_host;
  String proxy_user;
  String proxy_pass;
  int proxy_port = -1;
  int max_redirs = 20;
  int timeout = -1;
  bool ignore_errors = false;

  if (context && !context->getOptions().isNull() &&
      !context->getOptions()[s_http].isNull()) {
    Array opts = context->getOptions()[s_http].toArray();
    if (opts.exists(s_method)) {
      method = opts[s_method].toString();
    }
    if (opts.exists(s_header)) {
      Array lines;
      if (opts[s_header].isString()) {
        lines = StringUtil::Explode(
          opts[s_header].toString(), "\r\n").toArray();
      } else if (opts[s_header].isArray()) {
        lines = opts[s_header];
      }

      for (ArrayIter it(lines); it; ++it) {
        Array parts = StringUtil::Explode(
          it.second().toString(), ":", 2).toArray();
        headers.set(parts.rvalAt(0).unboxed().tv(), parts.rvalAt(1).tv());
      }
    }
    if (opts.exists(s_user_agent) && !headers.exists(s_User_Agent)) {
      headers.set(s_User_Agent, opts[s_user_agent]);
    }
    if (opts.exists(s_max_redirects)) {
      max_redirs = opts[s_max_redirects].toInt64();
    }
    if (opts.exists(s_timeout)) {
      timeout = opts[s_timeout].toInt64();
    }
    if (opts.exists(s_ignore_errors)) {
      ignore_errors = opts[s_ignore_errors].toBoolean();
    }
    if (opts.exists(s_proxy)) {
      Variant host = f_parse_url(opts[s_proxy].toString(), k_PHP_URL_HOST);
      Variant port = f_parse_url(opts[s_proxy].toString(), k_PHP_URL_PORT);
      if (!same(host, false) && !same(port, false)) {
        proxy_host = host.toString();
        proxy_port = port.toInt64();
        Variant user = f_parse_url(opts[s_proxy].toString(), k_PHP_URL_USER);
        Variant pass = f_parse_url(opts[s_proxy].toString(), k_PHP_URL_PASS);
        if (!same(user, false) && !same(pass, false)) {
          proxy_user = user.toString();
          proxy_pass = pass.toString();
        }
      }
    }
    post_data = opts[s_content].toString();
  }

  if (!headers.exists(s_User_Agent)) {
    auto default_user_agent = ThreadInfo::s_threadInfo.getNoCheck()
      ->m_reqInjectionData.getUserAgent();
    if (!default_user_agent.empty()) {
      headers.set(s_User_Agent, default_user_agent);
    }
  }
  auto file = req::make<UrlFile>(method.data(), headers,
                                    post_data, max_redirs,
                                    timeout, ignore_errors);
  file->setStreamContext(context);
  file->setProxy(proxy_host, proxy_port, proxy_user, proxy_pass);
  bool ret = file->open(filename, mode);
  if (!ret) {
    raise_warning("Failed to open %s (%s)", filename.data(),
                  file->getLastError().c_str());
    return nullptr;
  }
  return file;
}