  virtual void clearRouteCache() {
    if (decoder_callbacks_)
      decoder_callbacks_->clearRouteCache();
  }


bool CephXTicketHandler::verify_service_ticket_reply(CryptoKey& secret,
						     bufferlist::iterator& indata)
{
  __u8 service_ticket_v;
  ::decode(service_ticket_v, indata);

  CephXServiceTicket msg_a;
  std::string error;
  if (decode_decrypt(cct, msg_a, secret, indata, error)) {
    ldout(cct, 0) << "verify_service_ticket_reply: failed decode_decrypt, error is: " << error << dendl;
    return false;
  }

  __u8 ticket_enc;
  ::decode(ticket_enc, indata);

  bufferlist service_ticket_bl;
  if (ticket_enc) {
    ldout(cct, 10) << " got encrypted ticket" << dendl;
    std::string error;
    if (decode_decrypt(cct, service_ticket_bl, session_key, indata, error)) {
      ldout(cct, 10) << "verify_service_ticket_reply: decode_decrypt failed "
	    << "with " << error << dendl;
      return false;
    }
  } else {
    ::decode(service_ticket_bl, indata);
  }
  bufferlist::iterator iter = service_ticket_bl.begin();
  ::decode(ticket, iter);
  ldout(cct, 10) << " ticket.secret_id=" <<  ticket.secret_id << dendl;

  ldout(cct, 10) << "verify_service_ticket_reply service " << ceph_entity_type_name(service_id)
	   << " secret_id " << ticket.secret_id
	   << " session_key " << msg_a.session_key
           << " validity=" << msg_a.validity << dendl;
  session_key = msg_a.session_key;
  if (!msg_a.validity.is_zero()) {
    expires = ceph_clock_now();
    expires += msg_a.validity;
    renew_after = expires;
    renew_after -= ((double)msg_a.validity.sec() / 4);
    ldout(cct, 10) << "ticket expires=" << expires << " renew_after=" << renew_after << dendl;
  }

  have_key_flag = true;
  return true;
}


png_set_compression_mem_level(png_structp png_ptr, int mem_level)
{
   png_debug(1, "in png_set_compression_mem_level");

   if (png_ptr == NULL)
      return;
   png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
   png_ptr->zlib_mem_level = mem_level;
}


static inline void tree_mod_log_read_lock(struct btrfs_fs_info *fs_info)
{
	read_lock(&fs_info->tree_mod_log_lock);
}


static void incomplete_class_unset_property ( zval * object , zval * member , const zend_literal * key TSRMLS_DC ) {
 incomplete_class_message ( object , E_NOTICE TSRMLS_CC ) ;
 }


static int atomic_open(struct nameidata *nd, struct dentry *dentry,
			struct path *path, struct file *file,
			const struct open_flags *op,
			int open_flag, umode_t mode)
{
	struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
	struct inode *dir =  nd->path.dentry->d_inode;
	int error;

	if (!(~open_flag & (O_EXCL | O_CREAT)))	/* both O_EXCL and O_CREAT */
		open_flag &= ~O_TRUNC;

	if (nd->flags & LOOKUP_DIRECTORY)
		open_flag |= O_DIRECTORY;

	file->f_path.dentry = DENTRY_NOT_SET;
	file->f_path.mnt = nd->path.mnt;
	error = dir->i_op->atomic_open(dir, dentry, file,
				       open_to_namei_flags(open_flag), mode);
	d_lookup_done(dentry);
	if (!error) {
		if (file->f_mode & FMODE_OPENED) {
			/*
			 * We didn't have the inode before the open, so check open
			 * permission here.
			 */
			int acc_mode = op->acc_mode;
			if (file->f_mode & FMODE_CREATED) {
				WARN_ON(!(open_flag & O_CREAT));
				fsnotify_create(dir, dentry);
				acc_mode = 0;
			}
			error = may_open(&file->f_path, acc_mode, open_flag);
			if (WARN_ON(error > 0))
				error = -EINVAL;
		} else if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
			error = -EIO;
		} else {
			if (file->f_path.dentry) {
				dput(dentry);
				dentry = file->f_path.dentry;
			}
			if (file->f_mode & FMODE_CREATED)
				fsnotify_create(dir, dentry);
			if (unlikely(d_is_negative(dentry))) {
				error = -ENOENT;
			} else {
				path->dentry = dentry;
				path->mnt = nd->path.mnt;
				return 0;
			}
		}
	}
	dput(dentry);
	return error;
}


static int asn1_encode_integer(int in, u8 ** obj, size_t * objsize)
{
	int i = sizeof(in) * 8, skip_zero, skip_sign;
	u8 *p, b;

	if (in < 0)
	{
		skip_sign = 1;
		skip_zero= 0;
	}
	else
	{
		skip_sign = 0;
		skip_zero= 1;
	}
	*obj = p = malloc(sizeof(in)+1);
	if (*obj == NULL)
		return SC_ERROR_OUT_OF_MEMORY;
	do {
		i -= 8;
		b = in >> i;
		if (skip_sign)
		{
			if (b != 0xff)
				skip_sign = 0;
			if (b & 0x80)
			{
				*p = b;
				if (0xff == b)
					continue;
			}
			else
			{
				p++;
				skip_sign = 0;
			}
		}
		if (b == 0 && skip_zero)
			continue;
		if (skip_zero) {
			skip_zero = 0;
			/* prepend 0x00 if MSb is 1 and integer positive */
			if ((b & 0x80) != 0 && in > 0)
				*p++ = 0;
		}
		*p++ = b;
	} while (i > 0);
	if (skip_sign)
		p++;
	*objsize = p - *obj;
	if (*objsize == 0) {
		*objsize = 1;
		(*obj)[0] = 0;
	}
	return 0;
}


static gcry_err_code_t dummy_check_secret_key ( int algorithm , gcry_mpi_t * skey ) {
 ( void ) algorithm ;
 ( void ) skey ;
 fips_signal_error ( "using dummy public key function" ) ;
 return GPG_ERR_NOT_IMPLEMENTED ;
 }


static void perform_gamma_sbit_tests(png_modifier *pm)
{
   png_byte sbit;

 /* The only interesting cases are colour and grayscale, alpha is ignored here
    * for overall speed.  Only bit depths where sbit is less than the bit depth
    * are tested.
    */
 for (sbit=pm->sbitlow; sbit<(1<<READ_BDHI); ++sbit)
 {

       png_byte colour_type = 0, bit_depth = 0;
       unsigned int npalette = 0;

      while (next_format(&colour_type, &bit_depth, &npalette,
                         pm->test_lbg_gamma_sbit, pm->test_tRNS))
          if ((colour_type & PNG_COLOR_MASK_ALPHA) == 0 &&
             ((colour_type == 3 && sbit < 8) ||
             (colour_type != 3 && sbit < bit_depth)))
 {
 unsigned int i;

 for (i=0; i<pm->ngamma_tests; ++i)
 {
 unsigned int j;

 for (j=0; j<pm->ngamma_tests; ++j) if (i != j)
 {
               gamma_transform_test(pm, colour_type, bit_depth, npalette,
                  pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
                  sbit, pm->use_input_precision_sbit, 0 /*scale16*/);

 if (fail(pm))
 return;
 }
 }
 }
 }
}


time_t convert_date(char *date_string) {
   /* convert date string in MM/DD/YY or DD.MM.YY format into Unix time */
   int year, month, day;
   char *p, str[256];
   struct tm tms;
   time_t ltime;

   strlcpy(str, date_string, sizeof(str));
   month = day = year = 0;

   if (strchr(str, '[')) {
      ltime = atoi(strchr(str, '[') + 1);
      return ltime;
   } else if (strchr(str, '/')) {
      /* MM/DD/YY format */
      p = strtok(str, "/");
      if (p) {
         month = atoi(p);
         p = strtok(NULL, "/");
         if (p) {
            day = atoi(p);
            p = strtok(NULL, "/");
            if (p)
               year = atoi(p);
         }
      }
   } else if (strchr(str, '.')) {
      /* DD.MM.YY format */
      p = strtok(str, ".");
      if (p) {
         day = atoi(p);
         p = strtok(NULL, ".");
         if (p) {
            month = atoi(p);
            p = strtok(NULL, ".");
            if (p)
               year = atoi(p);
         }
      }
   } else
      return 0;

   /* calculate years */
   if (year > 1900)             /* 1900-2100 */
      year += 0;
   else if (year < 70)          /* 00-69 */
      year += 2000;
   else if (year < 100)         /* 70-99 */
      year += 1900;

   /* use last day of month */
   memset(&tms, 0, sizeof(struct tm));
   tms.tm_year = year - 1900;
   tms.tm_mon = month - 1;
   tms.tm_mday = day;
   tms.tm_hour = 12;

   ltime = mktime(&tms);

   return ltime;
}


const Cluster* BlockEntry::GetCluster() const { return m_pCluster; }


static int stellaris_enet_can_receive(NetClientState *nc)
{
    stellaris_enet_state *s = qemu_get_nic_opaque(nc);

    if ((s->rctl & SE_RCTL_RXEN) == 0)
        return 1;

    return (s->np < 31);
}


static float _CanonConvertAperture(ushort in)
{
  if ((in == (ushort)0xffe0) || (in == (ushort)0x7fff)) return 0.0f;
  return powf64(2.0, in/64.0);
}


static void openrisc_sim_net_init(MemoryRegion *address_space,

                                  hwaddr base,

                                  hwaddr descriptors,

                                  qemu_irq irq, NICInfo *nd)

{

    DeviceState *dev;

    SysBusDevice *s;

    dev = qdev_create(NULL, "open_eth");

    qdev_set_nic_properties(dev, nd);

    qdev_init_nofail(dev);

    s = SYS_BUS_DEVICE(dev);

    sysbus_connect_irq(s, 0, irq);

    memory_region_add_subregion(address_space, base,

                                sysbus_mmio_get_region(s, 0));

    memory_region_add_subregion(address_space, descriptors,

                                sysbus_mmio_get_region(s, 1));

}


static int jpeg2000_decode_packets_po_iteration(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,

                                             int RSpoc, int CSpoc,

                                             int LYEpoc, int REpoc, int CEpoc,

                                             int Ppoc)

{

    int ret = 0;

    int layno, reslevelno, compno, precno, ok_reslevel;

    int x, y;

    int tp_index = 0;

    int step_x, step_y;

    switch (Ppoc) {

    case JPEG2000_PGOD_RLCP:

        av_log(s->avctx, AV_LOG_DEBUG, "Progression order RLCP\n");

        ok_reslevel = 1;

        for (reslevelno = RSpoc; ok_reslevel && reslevelno < REpoc; reslevelno++) {

            ok_reslevel = 0;

            for (layno = 0; layno < LYEpoc; layno++) {

                for (compno = CSpoc; compno < CEpoc; compno++) {

                    Jpeg2000CodingStyle *codsty = tile->codsty + compno;

                    Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;

                    if (reslevelno < codsty->nreslevels) {

                        Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +

                                                reslevelno;

                        ok_reslevel = 1;

                        for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)

                            if ((ret = jpeg2000_decode_packet(s, tile, &tp_index,

                                                              codsty, rlevel,

                                                              precno, layno,

                                                              qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),

                                                              qntsty->nguardbits)) < 0)

                                return ret;

                    }

                }

            }

        }

        break;

    case JPEG2000_PGOD_LRCP:

        av_log(s->avctx, AV_LOG_DEBUG, "Progression order LRCP\n");

        for (layno = 0; layno < LYEpoc; layno++) {

            ok_reslevel = 1;

            for (reslevelno = RSpoc; ok_reslevel && reslevelno < REpoc; reslevelno++) {

                ok_reslevel = 0;

                for (compno = CSpoc; compno < CEpoc; compno++) {

                    Jpeg2000CodingStyle *codsty = tile->codsty + compno;

                    Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;

                    if (reslevelno < codsty->nreslevels) {

                        Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +

                                                reslevelno;

                        ok_reslevel = 1;

                        for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)

                            if ((ret = jpeg2000_decode_packet(s, tile, &tp_index,

                                                              codsty, rlevel,

                                                              precno, layno,

                                                              qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),

                                                              qntsty->nguardbits)) < 0)

                                return ret;

                    }

                }

            }

        }

        break;

    case JPEG2000_PGOD_CPRL:

        av_log(s->avctx, AV_LOG_DEBUG, "Progression order CPRL\n");

        for (compno = CSpoc; compno < CEpoc; compno++) {

            Jpeg2000Component *comp     = tile->comp + compno;

            Jpeg2000CodingStyle *codsty = tile->codsty + compno;

            Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;

            step_x = 32;

            step_y = 32;

            for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {

                uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r

                Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;

                step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);

                step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);

            }

            step_x = 1<<step_x;

            step_y = 1<<step_y;

            for (y = tile->coord[1][0]; y < tile->coord[1][1]; y = (y/step_y + 1)*step_y) {

                for (x = tile->coord[0][0]; x < tile->coord[0][1]; x = (x/step_x + 1)*step_x) {

                    for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {

                        unsigned prcx, prcy;

                        uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r

                        Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;

                        int xc = x / s->cdx[compno];

                        int yc = y / s->cdy[compno];

                        if (yc % (1 << (rlevel->log2_prec_height + reducedresno)) && y != tile->coord[1][0]) //FIXME this is a subset of the check

                            continue;

                        if (xc % (1 << (rlevel->log2_prec_width + reducedresno)) && x != tile->coord[0][0]) //FIXME this is a subset of the check

                            continue;

                        // check if a precinct exists

                        prcx   = ff_jpeg2000_ceildivpow2(xc, reducedresno) >> rlevel->log2_prec_width;

                        prcy   = ff_jpeg2000_ceildivpow2(yc, reducedresno) >> rlevel->log2_prec_height;

                        prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> rlevel->log2_prec_width;

                        prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> rlevel->log2_prec_height;

                        precno = prcx + rlevel->num_precincts_x * prcy;

                        if (prcx >= rlevel->num_precincts_x || prcy >= rlevel->num_precincts_y) {

                            av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",

                                   prcx, prcy, rlevel->num_precincts_x, rlevel->num_precincts_y);

                            continue;

                        }

                        for (layno = 0; layno < LYEpoc; layno++) {

                            if ((ret = jpeg2000_decode_packet(s, tile, &tp_index, codsty, rlevel,

                                                              precno, layno,

                                                              qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),

                                                              qntsty->nguardbits)) < 0)

                                return ret;

                        }

                    }

                }

            }

        }

        break;

    case JPEG2000_PGOD_RPCL:

        av_log(s->avctx, AV_LOG_WARNING, "Progression order RPCL\n");

        ok_reslevel = 1;

        for (reslevelno = RSpoc; ok_reslevel && reslevelno < REpoc; reslevelno++) {

            ok_reslevel = 0;

            step_x = 30;

            step_y = 30;

            for (compno = CSpoc; compno < CEpoc; compno++) {

                Jpeg2000Component *comp     = tile->comp + compno;

                Jpeg2000CodingStyle *codsty = tile->codsty + compno;

                if (reslevelno < codsty->nreslevels) {

                    uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r

                    Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;

                    step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);

                    step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);

                }

            }

            step_x = 1<<step_x;

            step_y = 1<<step_y;

            for (y = tile->coord[1][0]; y < tile->coord[1][1]; y = (y/step_y + 1)*step_y) {

                for (x = tile->coord[0][0]; x < tile->coord[0][1]; x = (x/step_x + 1)*step_x) {

                    for (compno = CSpoc; compno < CEpoc; compno++) {

                        Jpeg2000Component *comp     = tile->comp + compno;

                        Jpeg2000CodingStyle *codsty = tile->codsty + compno;

                        Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;

                        uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r

                        Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;

                        unsigned prcx, prcy;

                        int xc = x / s->cdx[compno];

                        int yc = y / s->cdy[compno];

                        if (reslevelno >= codsty->nreslevels)

                            continue;

                        if (yc % (1 << (rlevel->log2_prec_height + reducedresno)) && y != tile->coord[1][0]) //FIXME this is a subset of the check

                            continue;

                        if (xc % (1 << (rlevel->log2_prec_width + reducedresno)) && x != tile->coord[0][0]) //FIXME this is a subset of the check

                            continue;

                        // check if a precinct exists

                        prcx   = ff_jpeg2000_ceildivpow2(xc, reducedresno) >> rlevel->log2_prec_width;

                        prcy   = ff_jpeg2000_ceildivpow2(yc, reducedresno) >> rlevel->log2_prec_height;

                        prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> rlevel->log2_prec_width;

                        prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> rlevel->log2_prec_height;

                        precno = prcx + rlevel->num_precincts_x * prcy;

                        ok_reslevel = 1;

                        if (prcx >= rlevel->num_precincts_x || prcy >= rlevel->num_precincts_y) {

                            av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",

                                   prcx, prcy, rlevel->num_precincts_x, rlevel->num_precincts_y);

                            continue;

                        }

                            for (layno = 0; layno < LYEpoc; layno++) {

                                if ((ret = jpeg2000_decode_packet(s, tile, &tp_index,

                                                                codsty, rlevel,

                                                                precno, layno,

                                                                qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),

                                                                qntsty->nguardbits)) < 0)

                                    return ret;

                            }

                    }

                }

            }

        }

        break;

    case JPEG2000_PGOD_PCRL:

        av_log(s->avctx, AV_LOG_WARNING, "Progression order PCRL\n");

        step_x = 32;

        step_y = 32;

        for (compno = CSpoc; compno < CEpoc; compno++) {

            Jpeg2000Component *comp     = tile->comp + compno;

            Jpeg2000CodingStyle *codsty = tile->codsty + compno;

            Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;

            for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {

                uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r

                Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;

                step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);

                step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);

            }

        }

        step_x = 1<<step_x;

        step_y = 1<<step_y;

        for (y = tile->coord[1][0]; y < tile->coord[1][1]; y = (y/step_y + 1)*step_y) {

            for (x = tile->coord[0][0]; x < tile->coord[0][1]; x = (x/step_x + 1)*step_x) {

                for (compno = CSpoc; compno < CEpoc; compno++) {

                    Jpeg2000Component *comp     = tile->comp + compno;

                    Jpeg2000CodingStyle *codsty = tile->codsty + compno;

                    Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;

                    int xc = x / s->cdx[compno];

                    int yc = y / s->cdy[compno];

                    for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {

                        unsigned prcx, prcy;

                        uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r

                        Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;

                        if (yc % (1 << (rlevel->log2_prec_height + reducedresno)) && y != tile->coord[1][0]) //FIXME this is a subset of the check

                            continue;

                        if (xc % (1 << (rlevel->log2_prec_width + reducedresno)) && x != tile->coord[0][0]) //FIXME this is a subset of the check

                            continue;

                        // check if a precinct exists

                        prcx   = ff_jpeg2000_ceildivpow2(xc, reducedresno) >> rlevel->log2_prec_width;

                        prcy   = ff_jpeg2000_ceildivpow2(yc, reducedresno) >> rlevel->log2_prec_height;

                        prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> rlevel->log2_prec_width;

                        prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> rlevel->log2_prec_height;

                        precno = prcx + rlevel->num_precincts_x * prcy;

                        if (prcx >= rlevel->num_precincts_x || prcy >= rlevel->num_precincts_y) {

                            av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",

                                   prcx, prcy, rlevel->num_precincts_x, rlevel->num_precincts_y);

                            continue;

                        }

                        for (layno = 0; layno < LYEpoc; layno++) {

                            if ((ret = jpeg2000_decode_packet(s, tile, &tp_index, codsty, rlevel,

                                                              precno, layno,

                                                              qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),

                                                              qntsty->nguardbits)) < 0)

                                return ret;

                        }

                    }

                }

            }

        }

        break;

    default:

        break;

    }

    return ret;

}


static CYTHON_INLINE int __Pyx_GetItemInt_ByteArray_Fast(PyObject* string, Py_ssize_t i,
                                                         int wraparound, int boundscheck) {
    Py_ssize_t length;
    if (wraparound | boundscheck) {
        length = PyByteArray_GET_SIZE(string);
        if (wraparound & unlikely(i < 0)) i += length;
        if ((!boundscheck) || likely(__Pyx_is_valid_index(i, length))) {
            return (unsigned char) (PyByteArray_AS_STRING(string)[i]);
        } else {
            PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
            return -1;
        }
    } else {
        return (unsigned char) (PyByteArray_AS_STRING(string)[i]);
    }
}


void WebPageProxy::initializePolicyClient(const WKPagePolicyClient* policyClient)
{
    m_policyClient.initialize(policyClient);
}


pgp_put_data(sc_card_t *card, unsigned int tag, const u8 *buf, size_t buf_len)
{
	struct pgp_priv_data *priv = DRVDATA(card);
	pgp_blob_t *affected_blob = NULL;
	struct do_info *dinfo = NULL;
	int r;

	LOG_FUNC_CALLED(card->ctx);

	/* check if the tag is writable */
	if (priv->current->id != tag)
		affected_blob = pgp_find_blob(card, tag);

	/* Non-readable DOs have no represented blob, we have to check from pgp_get_info_by_tag */
	if (affected_blob == NULL)
		dinfo = pgp_get_info_by_tag(card, tag);
	else
		dinfo = affected_blob->info;

	if (dinfo == NULL) {
		sc_log(card->ctx, "The DO %04X does not exist.", tag);
		LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
	}
	else if ((dinfo->access & WRITE_MASK) == WRITE_NEVER) {
		sc_log(card->ctx, "DO %04X is not writable.", tag);
		LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_ALLOWED);
	}

	/* Check data size.
	 * We won't check other DOs than 7F21 (certificate), because their capacity
	 * is hard-coded and may change in various version of the card.
	 * If we check here, the driver may be stuck to a limit version number of card.
	 * 7F21 size is soft-coded, so we can check it. */
	if (tag == DO_CERT && buf_len > priv->max_cert_size) {
		sc_log(card->ctx,
		       "Data size %"SC_FORMAT_LEN_SIZE_T"u exceeds DO size limit %"SC_FORMAT_LEN_SIZE_T"u.",
		       buf_len, priv->max_cert_size);
		LOG_FUNC_RETURN(card->ctx, SC_ERROR_WRONG_LENGTH);
	}

	if (tag == DO_CERT && card->type == SC_CARD_TYPE_OPENPGP_GNUK) {
		/* Gnuk need a special way to write certificate. */
		r = gnuk_write_certificate(card, buf, buf_len);
	}
	else {
		r = pgp_put_data_plain(card, tag, buf, buf_len);
	}

	/* instruct more in case of error */
	if (r == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) {
		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Please verify PIN first.");
	}
	LOG_TEST_RET(card->ctx, r, "PUT DATA returned error");

	if (affected_blob) {
		/* update the corresponding file */
		sc_log(card->ctx, "Updating the corresponding blob data");
		r = pgp_set_blob(affected_blob, buf, buf_len);
		if (r < 0)
			sc_log(card->ctx, "Failed to update blob %04X. Error %d.", affected_blob->id, r);
		/* pgp_set_blob()'s failures do not impact pgp_put_data()'s result */
	}

	LOG_FUNC_RETURN(card->ctx, (int)buf_len);
}


static kadm5_ret_t get_policy ( kadm5_server_handle_t handle , const char * name , kadm5_policy_ent_t policy_out , krb5_boolean * have_pol_out ) {
 kadm5_ret_t ret ;
 * have_pol_out = FALSE ;
 if ( name == NULL ) return 0 ;
 ret = kadm5_get_policy ( handle -> lhandle , ( char * ) name , policy_out ) ;
 if ( ret == 0 ) * have_pol_out = TRUE ;
 return ( ret == KADM5_UNK_POLICY ) ? 0 : ret ;
 }


static void mgmt_debug(const char *str, void *user_data)
{
	const char *prefix = user_data;

	info("%s%s", prefix, str);
}


u2fh_devs_discover (u2fh_devs * devs, unsigned *max_index)
{
  struct hid_device_info *di, *cur_dev;
  u2fh_rc res = U2FH_NO_U2F_DEVICE;
  struct u2fdevice *dev;

  di = hid_enumerate (0, 0);
  for (cur_dev = di; cur_dev; cur_dev = cur_dev->next)
    {
      int found = 0;
      unsigned short usage_page = 0, usage = 0;

      /* check if we already opened this device */
      for (dev = devs->first; dev != NULL; dev = dev->next)
	{
	  if (strcmp (dev->device_path, cur_dev->path) == 0)
	    {
	      if (ping_device (devs, dev->id) == U2FH_OK)
		{
		  found = 1;
		  res = U2FH_OK;
		}
	      else
		{
		  if (debug)
		    {
		      fprintf (stderr, "Device %s failed ping, dead.\n",
			       dev->device_path);
		    }
		  close_device (devs, dev);
		}
	      break;
	    }
	}
      if (found)
	{
	  continue;
	}

      get_usages (cur_dev, &usage_page, &usage);
      if (usage_page == FIDO_USAGE_PAGE && usage == FIDO_USAGE_U2FHID)
	{
	  dev = new_device (devs);
	  dev->devh = hid_open_path (cur_dev->path);
	  if (dev->devh != NULL)
	    {
	      dev->device_path = strdup (cur_dev->path);
	      if (dev->device_path == NULL)
		{
		  close_device (devs, dev);
		  goto out;
		}
	      if (init_device (devs, dev) == U2FH_OK)
		{
		  if (cur_dev->product_string)
		    {
		      size_t len =
			wcstombs (NULL, cur_dev->product_string, 0);
		      dev->device_string = malloc (len + 1);
		      if (dev->device_string == NULL)
			{
			  close_device (devs, dev);
			  goto out;
			}
		      memset (dev->device_string, 0, len + 1);
		      wcstombs (dev->device_string, cur_dev->product_string,
				len);
		      if (debug)
			{
			  fprintf (stderr, "device %s discovered as '%s'\n",
				   dev->device_path, dev->device_string);
			  fprintf (stderr,
				   "  version (Interface, Major, "
				   "Minor, Build): %d, %d, "
				   "%d, %d  capFlags: %d\n",
				   dev->versionInterface,
				   dev->versionMajor,
				   dev->versionMinor,
				   dev->versionBuild, dev->capFlags);
			}
		    }
		  res = U2FH_OK;
		  continue;
		}
	    }
	  close_device (devs, dev);
	}
    }

  /* loop through all open devices and make sure we find them in the enumeration */
  dev = devs->first;
  while (dev)
    {
      int found = 0;

      for (cur_dev = di; cur_dev; cur_dev = cur_dev->next)
	{
	  if (strcmp (cur_dev->path, dev->device_path) == 0)
	    {
	      found = 1;
	      dev = dev->next;
	      break;
	    }
	}
      if (!found)
	{
	  if (debug)
	    {
	      fprintf (stderr, "device %s looks dead.\n", dev->device_path);
	    }
	  dev = close_device (devs, dev);
	}
    }

out:
  hid_free_enumeration (di);
  if (res == U2FH_OK && max_index)
    *max_index = devs->max_id - 1;

  return res;
}


midi_synth_load_patch(int dev, int format, const char __user *addr,
		      int offs, int count, int pmgr_flag)
{
	int             orig_dev = synth_devs[dev]->midi_dev;

	struct sysex_info sysex;
	int             i;
	unsigned long   left, src_offs, eox_seen = 0;
	int             first_byte = 1;
	int             hdr_size = (unsigned long) &sysex.data[0] - (unsigned long) &sysex;

	leave_sysex(dev);

	if (!prefix_cmd(orig_dev, 0xf0))
		return 0;

	if (format != SYSEX_PATCH)
	{
/*		  printk("MIDI Error: Invalid patch format (key) 0x%x\n", format);*/
		  return -EINVAL;
	}
	if (count < hdr_size)
	{
/*		printk("MIDI Error: Patch header too short\n");*/
		return -EINVAL;
	}
	count -= hdr_size;

	/*
	 * Copy the header from user space but ignore the first bytes which have
	 * been transferred already.
	 */

	if(copy_from_user(&((char *) &sysex)[offs], &(addr)[offs], hdr_size - offs))
		return -EFAULT;

 	if (count < sysex.len)
	{
/*		printk(KERN_WARNING "MIDI Warning: Sysex record too short (%d<%d)\n", count, (int) sysex.len);*/
		sysex.len = count;
	}
  	left = sysex.len;
  	src_offs = 0;

	for (i = 0; i < left && !signal_pending(current); i++)
	{
		unsigned char   data;

		if (get_user(data,
		    (unsigned char __user *)(addr + hdr_size + i)))
			return -EFAULT;

		eox_seen = (i > 0 && data & 0x80);	/* End of sysex */

		if (eox_seen && data != 0xf7)
			data = 0xf7;

		if (i == 0)
		{
			if (data != 0xf0)
			{
				printk(KERN_WARNING "midi_synth: Sysex start missing\n");
				return -EINVAL;
			}
		}
		while (!midi_devs[orig_dev]->outputc(orig_dev, (unsigned char) (data & 0xff)) &&
			!signal_pending(current))
			schedule();

		if (!first_byte && data & 0x80)
			return 0;
		first_byte = 0;
	}

	if (!eox_seen)
		midi_outc(orig_dev, 0xf7);
	return 0;
}


void vp9_pick_inter_mode ( VP9_COMP * cpi , MACROBLOCK * x , const TileInfo * const tile , int mi_row , int mi_col , int * returnrate , int64_t * returndistortion , BLOCK_SIZE bsize , PICK_MODE_CONTEXT * ctx ) {
 VP9_COMMON * const cm = & cpi -> common ;
 MACROBLOCKD * const xd = & x -> e_mbd ;
 MB_MODE_INFO * const mbmi = & xd -> mi [ 0 ] . src_mi -> mbmi ;
 struct macroblockd_plane * const pd = & xd -> plane [ 0 ] ;
 PREDICTION_MODE best_mode = ZEROMV ;
 MV_REFERENCE_FRAME ref_frame , best_ref_frame = LAST_FRAME ;
 TX_SIZE best_tx_size = MIN ( max_txsize_lookup [ bsize ] , tx_mode_to_biggest_tx_size [ cm -> tx_mode ] ) ;
 INTERP_FILTER best_pred_filter = EIGHTTAP ;
 int_mv frame_mv [ MB_MODE_COUNT ] [ MAX_REF_FRAMES ] ;
 struct buf_2d yv12_mb [ 4 ] [ MAX_MB_PLANE ] ;
 static const int flag_list [ 4 ] = {
 0 , VP9_LAST_FLAG , VP9_GOLD_FLAG , VP9_ALT_FLAG }
 ;
 int64_t best_rd = INT64_MAX ;
 int64_t this_rd = INT64_MAX ;
 uint8_t skip_txfm = 0 ;
 int rate = INT_MAX ;
 int64_t dist = INT64_MAX ;
 unsigned int var_y = UINT_MAX ;
 unsigned int sse_y = UINT_MAX ;
 const int intra_cost_penalty = * vp9_dc_quant ( cm -> base_qindex , cm -> y_dc_delta_q , cm -> bit_depth ) ;
 const int64_t inter_mode_thresh = RDCOST ( x -> rdmult , x -> rddiv , intra_cost_penalty , 0 ) ;
 const int intra_mode_cost = 50 ;
 const int8_t segment_id = mbmi -> segment_id ;
 const int * const rd_threshes = cpi -> rd . threshes [ segment_id ] [ bsize ] ;
 const int * const rd_thresh_freq_fact = cpi -> rd . thresh_freq_fact [ bsize ] ;
 INTERP_FILTER filter_ref = cm -> interp_filter ;
 const int bsl = mi_width_log2 ( bsize ) ;
 const int pred_filter_search = cm -> interp_filter == SWITCHABLE ? ( ( ( mi_row + mi_col ) >> bsl ) + get_chessboard_index ( cm -> current_video_frame ) ) & 0x1 : 0 ;
 int const_motion [ MAX_REF_FRAMES ] = {
 0 }
 ;
 const int bh = num_4x4_blocks_high_lookup [ bsize ] << 2 ;
 const int bw = num_4x4_blocks_wide_lookup [ bsize ] << 2 ;
 PRED_BUFFER tmp [ 4 ] ;
 DECLARE_ALIGNED_ARRAY ( 16 , uint8_t , pred_buf , 3 * 64 * 64 ) ;
 struct buf_2d orig_dst = pd -> dst ;
 PRED_BUFFER * best_pred = NULL ;
 PRED_BUFFER * this_mode_pred = NULL ;
 if ( cpi -> sf . reuse_inter_pred_sby ) {
 int i ;
 for ( i = 0 ;
 i < 3 ;
 i ++ ) {
 tmp [ i ] . data = & pred_buf [ bw * bh * i ] ;
 tmp [ i ] . stride = bw ;
 tmp [ i ] . in_use = 0 ;
 }
 tmp [ 3 ] . data = pd -> dst . buf ;
 tmp [ 3 ] . stride = pd -> dst . stride ;
 tmp [ 3 ] . in_use = 0 ;
 }
 x -> skip_encode = cpi -> sf . skip_encode_frame && x -> q_index < QIDX_SKIP_THRESH ;
 x -> skip = 0 ;
 * returnrate = INT_MAX ;
 * returndistortion = INT64_MAX ;
 vpx_memset ( mbmi , 0 , sizeof ( MB_MODE_INFO ) ) ;
 mbmi -> sb_type = bsize ;
 mbmi -> ref_frame [ 0 ] = NONE ;
 mbmi -> ref_frame [ 1 ] = NONE ;
 mbmi -> tx_size = MIN ( max_txsize_lookup [ bsize ] , tx_mode_to_biggest_tx_size [ cm -> tx_mode ] ) ;
 mbmi -> interp_filter = cm -> interp_filter == SWITCHABLE ? EIGHTTAP : cm -> interp_filter ;
 mbmi -> segment_id = segment_id ;
 for ( ref_frame = LAST_FRAME ;
 ref_frame <= ALTREF_FRAME ;
 ++ ref_frame ) {
 PREDICTION_MODE this_mode ;
 x -> pred_mv_sad [ ref_frame ] = INT_MAX ;
 frame_mv [ NEWMV ] [ ref_frame ] . as_int = INVALID_MV ;
 frame_mv [ ZEROMV ] [ ref_frame ] . as_int = 0 ;
 if ( xd -> up_available ) filter_ref = xd -> mi [ - xd -> mi_stride ] . src_mi -> mbmi . interp_filter ;
 else if ( xd -> left_available ) filter_ref = xd -> mi [ - 1 ] . src_mi -> mbmi . interp_filter ;
 if ( cpi -> ref_frame_flags & flag_list [ ref_frame ] ) {
 const YV12_BUFFER_CONFIG * yv12 = get_ref_frame_buffer ( cpi , ref_frame ) ;
 int_mv * const candidates = mbmi -> ref_mvs [ ref_frame ] ;
 const struct scale_factors * const sf = & cm -> frame_refs [ ref_frame - 1 ] . sf ;
 vp9_setup_pred_block ( xd , yv12_mb [ ref_frame ] , yv12 , mi_row , mi_col , sf , sf ) ;
 if ( ! cm -> error_resilient_mode ) vp9_find_mv_refs ( cm , xd , tile , xd -> mi [ 0 ] . src_mi , ref_frame , candidates , mi_row , mi_col ) ;
 else const_motion [ ref_frame ] = mv_refs_rt ( cm , xd , tile , xd -> mi [ 0 ] . src_mi , ref_frame , candidates , mi_row , mi_col ) ;
 vp9_find_best_ref_mvs ( xd , cm -> allow_high_precision_mv , candidates , & frame_mv [ NEARESTMV ] [ ref_frame ] , & frame_mv [ NEARMV ] [ ref_frame ] ) ;
 if ( ! vp9_is_scaled ( sf ) && bsize >= BLOCK_8X8 ) vp9_mv_pred ( cpi , x , yv12_mb [ ref_frame ] [ 0 ] . buf , yv12 -> y_stride , ref_frame , bsize ) ;
 }
 else {
 continue ;
 }
 xd -> plane [ 0 ] . pre [ 0 ] = yv12_mb [ ref_frame ] [ 0 ] ;
 clamp_mv2 ( & frame_mv [ NEARESTMV ] [ ref_frame ] . as_mv , xd ) ;
 clamp_mv2 ( & frame_mv [ NEARMV ] [ ref_frame ] . as_mv , xd ) ;
 mbmi -> ref_frame [ 0 ] = ref_frame ;
 for ( this_mode = NEARESTMV ;
 this_mode <= NEWMV ;
 ++ this_mode ) {
 int rate_mv = 0 ;
 int mode_rd_thresh ;
 if ( const_motion [ ref_frame ] && ( this_mode == NEARMV || this_mode == ZEROMV ) ) continue ;
 if ( ! ( cpi -> sf . inter_mode_mask [ bsize ] & ( 1 << this_mode ) ) ) continue ;
 mode_rd_thresh = rd_threshes [ mode_idx [ ref_frame - LAST_FRAME ] [ INTER_OFFSET ( this_mode ) ] ] ;
 if ( rd_less_than_thresh ( best_rd , mode_rd_thresh , rd_thresh_freq_fact [ this_mode ] ) ) continue ;
 if ( this_mode == NEWMV ) {
 if ( this_rd < ( int64_t ) ( 1 << num_pels_log2_lookup [ bsize ] ) ) continue ;
 if ( ! combined_motion_search ( cpi , x , bsize , mi_row , mi_col , & frame_mv [ NEWMV ] [ ref_frame ] , & rate_mv , best_rd ) ) continue ;
 }
 if ( this_mode != NEARESTMV && frame_mv [ this_mode ] [ ref_frame ] . as_int == frame_mv [ NEARESTMV ] [ ref_frame ] . as_int ) continue ;
 mbmi -> mode = this_mode ;
 mbmi -> mv [ 0 ] . as_int = frame_mv [ this_mode ] [ ref_frame ] . as_int ;
 if ( cpi -> sf . reuse_inter_pred_sby ) {
 if ( this_mode == NEARESTMV ) {
 this_mode_pred = & tmp [ 3 ] ;
 }
 else {
 this_mode_pred = & tmp [ get_pred_buffer ( tmp , 3 ) ] ;
 pd -> dst . buf = this_mode_pred -> data ;
 pd -> dst . stride = bw ;
 }
 }
 if ( ( this_mode == NEWMV || filter_ref == SWITCHABLE ) && pred_filter_search && ( ( mbmi -> mv [ 0 ] . as_mv . row & 0x07 ) != 0 || ( mbmi -> mv [ 0 ] . as_mv . col & 0x07 ) != 0 ) ) {
 int pf_rate [ 3 ] ;
 int64_t pf_dist [ 3 ] ;
 unsigned int pf_var [ 3 ] ;
 unsigned int pf_sse [ 3 ] ;
 TX_SIZE pf_tx_size [ 3 ] ;
 int64_t best_cost = INT64_MAX ;
 INTERP_FILTER best_filter = SWITCHABLE , filter ;
 PRED_BUFFER * current_pred = this_mode_pred ;
 for ( filter = EIGHTTAP ;
 filter <= EIGHTTAP_SHARP ;
 ++ filter ) {
 int64_t cost ;
 mbmi -> interp_filter = filter ;
 vp9_build_inter_predictors_sby ( xd , mi_row , mi_col , bsize ) ;
 model_rd_for_sb_y ( cpi , bsize , x , xd , & pf_rate [ filter ] , & pf_dist [ filter ] , & pf_var [ filter ] , & pf_sse [ filter ] ) ;
 cost = RDCOST ( x -> rdmult , x -> rddiv , vp9_get_switchable_rate ( cpi ) + pf_rate [ filter ] , pf_dist [ filter ] ) ;
 pf_tx_size [ filter ] = mbmi -> tx_size ;
 if ( cost < best_cost ) {
 best_filter = filter ;
 best_cost = cost ;
 skip_txfm = x -> skip_txfm [ 0 ] ;
 if ( cpi -> sf . reuse_inter_pred_sby ) {
 if ( this_mode_pred != current_pred ) {
 free_pred_buffer ( this_mode_pred ) ;
 this_mode_pred = current_pred ;
 }
 if ( filter < EIGHTTAP_SHARP ) {
 current_pred = & tmp [ get_pred_buffer ( tmp , 3 ) ] ;
 pd -> dst . buf = current_pred -> data ;
 pd -> dst . stride = bw ;
 }
 }
 }
 }
 if ( cpi -> sf . reuse_inter_pred_sby && this_mode_pred != current_pred ) free_pred_buffer ( current_pred ) ;
 mbmi -> interp_filter = best_filter ;
 mbmi -> tx_size = pf_tx_size [ mbmi -> interp_filter ] ;
 rate = pf_rate [ mbmi -> interp_filter ] ;
 dist = pf_dist [ mbmi -> interp_filter ] ;
 var_y = pf_var [ mbmi -> interp_filter ] ;
 sse_y = pf_sse [ mbmi -> interp_filter ] ;
 x -> skip_txfm [ 0 ] = skip_txfm ;
 }
 else {
 mbmi -> interp_filter = ( filter_ref == SWITCHABLE ) ? EIGHTTAP : filter_ref ;
 vp9_build_inter_predictors_sby ( xd , mi_row , mi_col , bsize ) ;
 model_rd_for_sb_y ( cpi , bsize , x , xd , & rate , & dist , & var_y , & sse_y ) ;
 }
 rate += rate_mv ;
 rate += cpi -> inter_mode_cost [ mbmi -> mode_context [ ref_frame ] ] [ INTER_OFFSET ( this_mode ) ] ;
 this_rd = RDCOST ( x -> rdmult , x -> rddiv , rate , dist ) ;
 if ( cpi -> allow_encode_breakout ) {
 encode_breakout_test ( cpi , x , bsize , mi_row , mi_col , ref_frame , this_mode , var_y , sse_y , yv12_mb , & rate , & dist ) ;
 if ( x -> skip ) {
 rate += rate_mv ;
 this_rd = RDCOST ( x -> rdmult , x -> rddiv , rate , dist ) ;
 }
 }
 # if CONFIG_VP9_TEMPORAL_DENOISING if ( cpi -> oxcf . noise_sensitivity > 0 ) {
 vp9_denoiser_update_frame_stats ( mbmi , sse_y , this_mode , ctx ) ;
 }
 # else ( void ) ctx ;
 # endif if ( this_rd < best_rd || x -> skip ) {
 best_rd = this_rd ;
 * returnrate = rate ;
 * returndistortion = dist ;
 best_mode = this_mode ;
 best_pred_filter = mbmi -> interp_filter ;
 best_tx_size = mbmi -> tx_size ;
 best_ref_frame = ref_frame ;
 skip_txfm = x -> skip_txfm [ 0 ] ;
 if ( cpi -> sf . reuse_inter_pred_sby ) {
 free_pred_buffer ( best_pred ) ;
 best_pred = this_mode_pred ;
 }
 }
 else {
 if ( cpi -> sf . reuse_inter_pred_sby ) free_pred_buffer ( this_mode_pred ) ;
 }
 if ( x -> skip ) break ;
 }
 if ( best_rd < INT64_MAX ) break ;
 }
 if ( best_pred != NULL && cpi -> sf . reuse_inter_pred_sby && best_pred -> data != orig_dst . buf ) {
 pd -> dst = orig_dst ;
 vp9_convolve_copy ( best_pred -> data , bw , pd -> dst . buf , pd -> dst . stride , NULL , 0 , NULL , 0 , bw , bh ) ;
 }
 mbmi -> mode = best_mode ;
 mbmi -> interp_filter = best_pred_filter ;
 mbmi -> tx_size = best_tx_size ;
 mbmi -> ref_frame [ 0 ] = best_ref_frame ;
 mbmi -> mv [ 0 ] . as_int = frame_mv [ best_mode ] [ best_ref_frame ] . as_int ;
 xd -> mi [ 0 ] . src_mi -> bmi [ 0 ] . as_mv [ 0 ] . as_int = mbmi -> mv [ 0 ] . as_int ;
 x -> skip_txfm [ 0 ] = skip_txfm ;
 if ( ! x -> skip && best_rd > inter_mode_thresh && bsize <= cpi -> sf . max_intra_bsize ) {
 PREDICTION_MODE this_mode ;
 struct estimate_block_intra_args args = {
 cpi , x , DC_PRED , 0 , 0 }
 ;
 const TX_SIZE intra_tx_size = MIN ( max_txsize_lookup [ bsize ] , tx_mode_to_biggest_tx_size [ cpi -> common . tx_mode ] ) ;
 if ( cpi -> sf . reuse_inter_pred_sby ) {
 pd -> dst . buf = tmp [ 0 ] . data ;
 pd -> dst . stride = bw ;
 }
 for ( this_mode = DC_PRED ;
 this_mode <= DC_PRED ;
 ++ this_mode ) {
 const TX_SIZE saved_tx_size = mbmi -> tx_size ;
 args . mode = this_mode ;
 args . rate = 0 ;
 args . dist = 0 ;
 mbmi -> tx_size = intra_tx_size ;
 vp9_foreach_transformed_block_in_plane ( xd , bsize , 0 , estimate_block_intra , & args ) ;
 mbmi -> tx_size = saved_tx_size ;
 rate = args . rate ;
 dist = args . dist ;
 rate += cpi -> mbmode_cost [ this_mode ] ;
 rate += intra_cost_penalty ;
 this_rd = RDCOST ( x -> rdmult , x -> rddiv , rate , dist ) ;
 if ( this_rd + intra_mode_cost < best_rd ) {
 best_rd = this_rd ;
 * returnrate = rate ;
 * returndistortion = dist ;
 mbmi -> mode = this_mode ;
 mbmi -> tx_size = intra_tx_size ;
 mbmi -> ref_frame [ 0 ] = INTRA_FRAME ;
 mbmi -> uv_mode = this_mode ;
 mbmi -> mv [ 0 ] . as_int = INVALID_MV ;
 }
 else {
 x -> skip_txfm [ 0 ] = skip_txfm ;
 }
 }
 if ( cpi -> sf . reuse_inter_pred_sby ) pd -> dst = orig_dst ;
 }
 }


TEST_P(StrictDnsParamTest, ImmediateResolve) {
  auto dns_resolver = std::make_shared<NiceMock<Network::MockDnsResolver>>();
  ReadyWatcher initialized;
  const std::string yaml = R"EOF(
    name: name
    connect_timeout: 0.25s
    type: strict_dns
    )EOF" + std::get<0>(GetParam()) +
                           R"EOF(
    lb_policy: round_robin
    load_assignment:
        endpoints:
          - lb_endpoints:
            - endpoint:
                address:
                  socket_address:
                    address: foo.bar.com
                    port_value: 443
  )EOF";
  EXPECT_CALL(initialized, ready());
  EXPECT_CALL(*dns_resolver, resolve("foo.bar.com", std::get<1>(GetParam()), _))
      .WillOnce(Invoke([&](const std::string&, Network::DnsLookupFamily,
                           Network::DnsResolver::ResolveCb cb) -> Network::ActiveDnsQuery* {
        cb(Network::DnsResolver::ResolutionStatus::Success,
           TestUtility::makeDnsResponse(std::get<2>(GetParam())));
        return nullptr;
      }));
  envoy::config::cluster::v3::Cluster cluster_config = parseClusterFromV3Yaml(yaml);
  Envoy::Stats::ScopePtr scope = stats_.createScope(fmt::format(
      "cluster.{}.", cluster_config.alt_stat_name().empty() ? cluster_config.name()
                                                            : cluster_config.alt_stat_name()));
  Envoy::Server::Configuration::TransportSocketFactoryContextImpl factory_context(
      admin_, ssl_context_manager_, *scope, cm_, local_info_, dispatcher_, stats_,
      singleton_manager_, tls_, validation_visitor_, *api_, options_);

  StrictDnsClusterImpl cluster(cluster_config, runtime_, dns_resolver, factory_context,
                               std::move(scope), false);
  cluster.initialize([&]() -> void { initialized.ready(); });
  EXPECT_EQ(2UL, cluster.prioritySet().hostSetsPerPriority()[0]->hosts().size());
  EXPECT_EQ(2UL, cluster.prioritySet().hostSetsPerPriority()[0]->healthyHosts().size());
}


static Jsi_RC InfoMethodsCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
    Jsi_Value **ret, Jsi_Func *funcPtr)
{
    Jsi_Value *arg = Jsi_ValueArrayIndex(interp, args, 0);
    Jsi_RC rc = InfoFuncDataSub(interp, arg, _this, ret, funcPtr, 1, NULL);
    if (rc == JSI_OK && Jsi_ValueIsArray(interp, *ret)) {
        Jsi_Obj *nobj = (*ret)->d.obj;
        InfoCmdsCmdSub(interp, arg, _this, ret, funcPtr, 0, 1, nobj, 3);
    }
    return rc;
}


static void RaisesExceptionGetterLongAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) {
  v8::Local<v8::Object> holder = info.Holder();

  TestObject* impl = V8TestObject::ToImpl(holder);

  ExceptionState exception_state(info.GetIsolate(), ExceptionState::kGetterContext, "TestObject", "raisesExceptionGetterLongAttribute");

  int32_t cpp_value(impl->raisesExceptionGetterLongAttribute(exception_state));

  if (UNLIKELY(exception_state.HadException()))
    return;

  V8SetReturnValueInt(info, cpp_value);
}


GLES2Implementation::DeferredErrorCallback::DeferredErrorCallback(
    std::string message,
    int32_t id)
    : message(std::move(message)), id(id) {}


int iscsi_login_tx_data(
	struct iscsi_conn *conn,
	char *pdu_buf,
	char *text_buf,
	int text_length)
{
	int length, tx_sent, iov_cnt = 1;
	struct kvec iov[2];

	length = (ISCSI_HDR_LEN + text_length);

	memset(&iov[0], 0, 2 * sizeof(struct kvec));
	iov[0].iov_len		= ISCSI_HDR_LEN;
	iov[0].iov_base		= pdu_buf;

	if (text_buf && text_length) {
		iov[1].iov_len	= text_length;
		iov[1].iov_base	= text_buf;
		iov_cnt++;
	}

	/*
	 * Initial Marker-less Interval.
	 * Add the values regardless of IFMarker/OFMarker, considering
	 * it may not be negoitated yet.
	 */
	conn->if_marker += length;

	tx_sent = tx_data(conn, &iov[0], iov_cnt, length);
	if (tx_sent != length) {
		pr_err("tx_data returned %d, expecting %d.\n",
				tx_sent, length);
		return -1;
	}

	return 0;
}


int imap_check_mailbox(struct Context *ctx, int force)
{
  return imap_check(ctx->data, force);
}


void DownloadPathReservationTrackerTest::TestReservedPathCallback(
    base::FilePath* return_path, bool* return_verified, bool* did_run_callback,
    const base::FilePath& path, bool verified) {
  *did_run_callback = true;
  *return_path = path;
  *return_verified = verified;
}


void RenderThreadImpl::ScheduleIdleHandler(int64_t initial_delay_ms) {
  idle_notification_delay_in_ms_ = initial_delay_ms;
  idle_timer_.Stop();
  idle_timer_.Start(FROM_HERE,
      base::TimeDelta::FromMilliseconds(initial_delay_ms),
      this, &RenderThreadImpl::IdleHandler);
}


SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
		int, newdfd, const char __user *, newname)
{
	int error;
	char *from;
	char *to;
	struct dentry *dentry;
	struct nameidata nd;

	from = getname(oldname);
	if (IS_ERR(from))
		return PTR_ERR(from);

	error = user_path_parent(newdfd, newname, &nd, &to);
	if (error)
		goto out_putname;

	dentry = lookup_create(&nd, 0);
	error = PTR_ERR(dentry);
	if (IS_ERR(dentry))
		goto out_unlock;

	error = mnt_want_write(nd.path.mnt);
	if (error)
		goto out_dput;
	error = security_path_symlink(&nd.path, dentry, from);
	if (error)
		goto out_drop_write;
	error = vfs_symlink(nd.path.dentry->d_inode, dentry, from);
out_drop_write:
	mnt_drop_write(nd.path.mnt);
out_dput:
	dput(dentry);
out_unlock:
	mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
	path_put(&nd.path);
	putname(to);
out_putname:
	putname(from);
	return error;
}


const Tensor& indices() const { return ix_; }


static void cpu_handle_guest_debug ( CPUState * cpu ) {
 gdb_set_stop_cpu ( cpu ) ;
 qemu_system_debug_request ( ) ;
 cpu -> stopped = true ;
 }


int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)

{

    f->owner = avctx;

    return ff_get_buffer(avctx, f->f, flags);

}


parse_netscreen_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer* buf,
    char *line, int *err, gchar **err_info)
{
	int		sec;
	int		dsec;
	char		cap_int[NETSCREEN_MAX_INT_NAME_LENGTH];
	char		direction[2];
	guint		pkt_len;
	char		cap_src[13];
	char		cap_dst[13];
	guint8		*pd;
	gchar		*p;
	int		n, i = 0;
	guint		offset = 0;
	gchar		dststr[13];

	phdr->rec_type = REC_TYPE_PACKET;
	phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;

	if (sscanf(line, "%9d.%9d: %15[a-z0-9/:.-](%1[io]) len=%9u:%12s->%12s/",
		   &sec, &dsec, cap_int, direction, &pkt_len, cap_src, cap_dst) < 5) {
		*err = WTAP_ERR_BAD_FILE;
		*err_info = g_strdup("netscreen: Can't parse packet-header");
		return -1;
	}
	if (pkt_len > WTAP_MAX_PACKET_SIZE) {
		/*
		 * Probably a corrupt capture file; don't blow up trying
		 * to allocate space for an immensely-large packet.
		 */
		*err = WTAP_ERR_BAD_FILE;
		*err_info = g_strdup_printf("netscreen: File has %u-byte packet, bigger than maximum of %u",
		    pkt_len, WTAP_MAX_PACKET_SIZE);
		return FALSE;
	}

	/*
	 * If direction[0] is 'o', the direction is NETSCREEN_EGRESS,
	 * otherwise it's NETSCREEN_INGRESS.
	 */

	phdr->ts.secs  = sec;
	phdr->ts.nsecs = dsec * 100000000;
	phdr->len = pkt_len;

	/* Make sure we have enough room for the packet */
	ws_buffer_assure_space(buf, pkt_len);
	pd = ws_buffer_start_ptr(buf);

	while(1) {

		/* The last packet is not delimited by an empty line, but by EOF
		 * So accept EOF as a valid delimiter too
		 */
		if (file_gets(line, NETSCREEN_LINE_LENGTH, fh) == NULL) {
			break;
		}

		/*
		 * Skip blanks.
		 * The number of blanks is not fixed - for wireless
		 * interfaces, there may be 14 extra spaces before
		 * the hex data.
		 */
		for (p = &line[0]; g_ascii_isspace(*p); p++)
			;
		/* packets are delimited with empty lines */
		if (*p == '\0') {
			break;
		}

		n = parse_single_hex_dump_line(p, pd, offset);

		/* the smallest packet has a length of 6 bytes, if
		 * the first hex-data is less then check whether
		 * it is a info-line and act accordingly
		 */
		if (offset == 0 && n < 6) {
			if (info_line(line)) {
				if (++i <= NETSCREEN_MAX_INFOLINES) {
					continue;
				}
			} else {
				*err = WTAP_ERR_BAD_FILE;
				*err_info = g_strdup("netscreen: cannot parse hex-data");
				return FALSE;
			}
		}

		/* If there is no more data and the line was not empty,
		 * then there must be an error in the file
		 */
		if (n == -1) {
			*err = WTAP_ERR_BAD_FILE;
			*err_info = g_strdup("netscreen: cannot parse hex-data");
			return FALSE;
		}

		/* Adjust the offset to the data that was just added to the buffer */
		offset += n;

		/* If there was more hex-data than was announced in the len=x
		 * header, then then there must be an error in the file
		 */
		if (offset > pkt_len) {
			*err = WTAP_ERR_BAD_FILE;
			*err_info = g_strdup("netscreen: too much hex-data");
			return FALSE;
		}
	}

	/*
	 * Determine the encapsulation type, based on the
	 * first 4 characters of the interface name
	 *
	 * XXX	convert this to a 'case' structure when adding more
	 *	(non-ethernet) interfacetypes
	 */
	if (strncmp(cap_int, "adsl", 4) == 0) {
		/* The ADSL interface can be bridged with or without
		 * PPP encapsulation. Check whether the first six bytes
		 * of the hex data are the same as the destination mac
		 * address in the header. If they are, assume ethernet
		 * LinkLayer or else PPP
		 */
		g_snprintf(dststr, 13, "%02x%02x%02x%02x%02x%02x",
		   pd[0], pd[1], pd[2], pd[3], pd[4], pd[5]);
		if (strncmp(dststr, cap_dst, 12) == 0)
			phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
		else
			phdr->pkt_encap = WTAP_ENCAP_PPP;
		}
	else if (strncmp(cap_int, "seri", 4) == 0)
		phdr->pkt_encap = WTAP_ENCAP_PPP;
	else
		phdr->pkt_encap = WTAP_ENCAP_ETHERNET;

	phdr->caplen = offset;

	return TRUE;
}


nfsd4_verify_copy(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
		  stateid_t *src_stateid, struct file **src,
		  stateid_t *dst_stateid, struct file **dst)
{
	__be32 status;

	status = nfs4_preprocess_stateid_op(rqstp, cstate, &cstate->save_fh,
					    src_stateid, RD_STATE, src, NULL);
	if (status) {
		dprintk("NFSD: %s: couldn't process src stateid!\n", __func__);
		goto out;
	}

	status = nfs4_preprocess_stateid_op(rqstp, cstate, &cstate->current_fh,
					    dst_stateid, WR_STATE, dst, NULL);
	if (status) {
		dprintk("NFSD: %s: couldn't process dst stateid!\n", __func__);
		goto out_put_src;
	}

	/* fix up for NFS-specific error code */
	if (!S_ISREG(file_inode(*src)->i_mode) ||
	    !S_ISREG(file_inode(*dst)->i_mode)) {
		status = nfserr_wrong_type;
		goto out_put_dst;
	}

out:
	return status;
out_put_dst:
	fput(*dst);
out_put_src:
	fput(*src);
	goto out;
}


static int get_htab_fd(sPAPRMachineState *spapr)

{

    if (spapr->htab_fd >= 0) {

        return spapr->htab_fd;

    }

    spapr->htab_fd = kvmppc_get_htab_fd(false);

    if (spapr->htab_fd < 0) {

        error_report("Unable to open fd for reading hash table from KVM: %s",

                     strerror(errno));

    }

    return spapr->htab_fd;

}


xmlParseStartTag2(xmlParserCtxtPtr ctxt, const xmlChar **pref,
                  const xmlChar **URI, int *tlen) {
    const xmlChar *localname;
    const xmlChar *prefix;
    const xmlChar *attname;
    const xmlChar *aprefix;
    const xmlChar *nsname;
    xmlChar *attvalue;
    const xmlChar **atts = ctxt->atts;
    int maxatts = ctxt->maxatts;
    int nratts, nbatts, nbdef;
    int i, j, nbNs, attval;
    unsigned long cur;
    int nsNr = ctxt->nsNr;

    if (RAW != '<') return(NULL);
    NEXT1;

    /*
     * NOTE: it is crucial with the SAX2 API to never call SHRINK beyond that
     *       point since the attribute values may be stored as pointers to
     *       the buffer and calling SHRINK would destroy them !
     *       The Shrinking is only possible once the full set of attribute
     *       callbacks have been done.
     */
    SHRINK;
    cur = ctxt->input->cur - ctxt->input->base;
    nbatts = 0;
    nratts = 0;
    nbdef = 0;
    nbNs = 0;
    attval = 0;
    /* Forget any namespaces added during an earlier parse of this element. */
    ctxt->nsNr = nsNr;

    localname = xmlParseQName(ctxt, &prefix);
    if (localname == NULL) {
	xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
		       "StartTag: invalid element name\n");
        return(NULL);
    }
    *tlen = ctxt->input->cur - ctxt->input->base - cur;

    /*
     * Now parse the attributes, it ends up with the ending
     *
     * (S Attribute)* S?
     */
    SKIP_BLANKS;
    GROW;

    while (((RAW != '>') &&
	   ((RAW != '/') || (NXT(1) != '>')) &&
	   (IS_BYTE_CHAR(RAW))) && (ctxt->instate != XML_PARSER_EOF)) {
	const xmlChar *q = CUR_PTR;
	unsigned int cons = ctxt->input->consumed;
	int len = -1, alloc = 0;

	attname = xmlParseAttribute2(ctxt, prefix, localname,
	                             &aprefix, &attvalue, &len, &alloc);
        if ((attname == NULL) || (attvalue == NULL))
            goto next_attr;
	if (len < 0) len = xmlStrlen(attvalue);

        if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) {
            const xmlChar *URL = xmlDictLookup(ctxt->dict, attvalue, len);
            xmlURIPtr uri;

            if (URL == NULL) {
                xmlErrMemory(ctxt, "dictionary allocation failure");
                if ((attvalue != NULL) && (alloc != 0))
                    xmlFree(attvalue);
                return(NULL);
            }
            if (*URL != 0) {
                uri = xmlParseURI((const char *) URL);
                if (uri == NULL) {
                    xmlNsErr(ctxt, XML_WAR_NS_URI,
                             "xmlns: '%s' is not a valid URI\n",
                                       URL, NULL, NULL);
                } else {
                    if (uri->scheme == NULL) {
                        xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE,
                                  "xmlns: URI %s is not absolute\n",
                                  URL, NULL, NULL);
                    }
                    xmlFreeURI(uri);
                }
                if (URL == ctxt->str_xml_ns) {
                    if (attname != ctxt->str_xml) {
                        xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
                     "xml namespace URI cannot be the default namespace\n",
                                 NULL, NULL, NULL);
                    }
                    goto next_attr;
                }
                if ((len == 29) &&
                    (xmlStrEqual(URL,
                             BAD_CAST "http://www.w3.org/2000/xmlns/"))) {
                    xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
                         "reuse of the xmlns namespace name is forbidden\n",
                             NULL, NULL, NULL);
                    goto next_attr;
                }
            }
            /*
             * check that it's not a defined namespace
             */
            for (j = 1;j <= nbNs;j++)
                if (ctxt->nsTab[ctxt->nsNr - 2 * j] == NULL)
                    break;
            if (j <= nbNs)
                xmlErrAttributeDup(ctxt, NULL, attname);
            else
                if (nsPush(ctxt, NULL, URL) > 0) nbNs++;

        } else if (aprefix == ctxt->str_xmlns) {
            const xmlChar *URL = xmlDictLookup(ctxt->dict, attvalue, len);
            xmlURIPtr uri;

            if (attname == ctxt->str_xml) {
                if (URL != ctxt->str_xml_ns) {
                    xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
                             "xml namespace prefix mapped to wrong URI\n",
                             NULL, NULL, NULL);
                }
                /*
                 * Do not keep a namespace definition node
                 */
                goto next_attr;
            }
            if (URL == ctxt->str_xml_ns) {
                if (attname != ctxt->str_xml) {
                    xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
                             "xml namespace URI mapped to wrong prefix\n",
                             NULL, NULL, NULL);
                }
                goto next_attr;
            }
            if (attname == ctxt->str_xmlns) {
                xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
                         "redefinition of the xmlns prefix is forbidden\n",
                         NULL, NULL, NULL);
                goto next_attr;
            }
            if ((len == 29) &&
                (xmlStrEqual(URL,
                             BAD_CAST "http://www.w3.org/2000/xmlns/"))) {
                xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
                         "reuse of the xmlns namespace name is forbidden\n",
                         NULL, NULL, NULL);
                goto next_attr;
            }
            if ((URL == NULL) || (URL[0] == 0)) {
                xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
                         "xmlns:%s: Empty XML namespace is not allowed\n",
                              attname, NULL, NULL);
                goto next_attr;
            } else {
                uri = xmlParseURI((const char *) URL);
                if (uri == NULL) {
                    xmlNsErr(ctxt, XML_WAR_NS_URI,
                         "xmlns:%s: '%s' is not a valid URI\n",
                                       attname, URL, NULL);
                } else {
                    if ((ctxt->pedantic) && (uri->scheme == NULL)) {
                        xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE,
                                  "xmlns:%s: URI %s is not absolute\n",
                                  attname, URL, NULL);
                    }
                    xmlFreeURI(uri);
                }
            }

            /*
             * check that it's not a defined namespace
             */
            for (j = 1;j <= nbNs;j++)
                if (ctxt->nsTab[ctxt->nsNr - 2 * j] == attname)
                    break;
            if (j <= nbNs)
                xmlErrAttributeDup(ctxt, aprefix, attname);
            else
                if (nsPush(ctxt, attname, URL) > 0) nbNs++;

        } else {
            /*
             * Add the pair to atts
             */
            if ((atts == NULL) || (nbatts + 5 > maxatts)) {
                if (xmlCtxtGrowAttrs(ctxt, nbatts + 5) < 0) {
                    goto next_attr;
                }
                maxatts = ctxt->maxatts;
                atts = ctxt->atts;
            }
            ctxt->attallocs[nratts++] = alloc;
            atts[nbatts++] = attname;
            atts[nbatts++] = aprefix;
            /*
             * The namespace URI field is used temporarily to point at the
             * base of the current input buffer for non-alloced attributes.
             * When the input buffer is reallocated, all the pointers become
             * invalid, but they can be reconstructed later.
             */
            if (alloc)
                atts[nbatts++] = NULL;
            else
                atts[nbatts++] = ctxt->input->base;
            atts[nbatts++] = attvalue;
            attvalue += len;
            atts[nbatts++] = attvalue;
            /*
             * tag if some deallocation is needed
             */
            if (alloc != 0) attval = 1;
            attvalue = NULL; /* moved into atts */
        }

next_attr:
        if ((attvalue != NULL) && (alloc != 0)) {
            xmlFree(attvalue);
            attvalue = NULL;
        }

	GROW
        if (ctxt->instate == XML_PARSER_EOF)
            break;
	if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>'))))
	    break;
	if (!IS_BLANK_CH(RAW)) {
	    xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
			   "attributes construct error\n");
	    break;
	}
	SKIP_BLANKS;
        if ((cons == ctxt->input->consumed) && (q == CUR_PTR) &&
            (attname == NULL) && (attvalue == NULL)) {
	    xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
	         "xmlParseStartTag: problem parsing attributes\n");
	    break;
	}
        GROW;
    }

    /* Reconstruct attribute value pointers. */
    for (i = 0, j = 0; j < nratts; i += 5, j++) {
        if (atts[i+2] != NULL) {
            /*
             * Arithmetic on dangling pointers is technically undefined
             * behavior, but well...
             */
            ptrdiff_t offset = ctxt->input->base - atts[i+2];
            atts[i+2]  = NULL;    /* Reset repurposed namespace URI */
            atts[i+3] += offset;  /* value */
            atts[i+4] += offset;  /* valuend */
        }
    }

    /*
     * The attributes defaulting
     */
    if (ctxt->attsDefault != NULL) {
        xmlDefAttrsPtr defaults;

	defaults = xmlHashLookup2(ctxt->attsDefault, localname, prefix);
	if (defaults != NULL) {
	    for (i = 0;i < defaults->nbAttrs;i++) {
	        attname = defaults->values[5 * i];
		aprefix = defaults->values[5 * i + 1];

                /*
		 * special work for namespaces defaulted defs
		 */
		if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) {
		    /*
		     * check that it's not a defined namespace
		     */
		    for (j = 1;j <= nbNs;j++)
		        if (ctxt->nsTab[ctxt->nsNr - 2 * j] == NULL)
			    break;
	            if (j <= nbNs) continue;

		    nsname = xmlGetNamespace(ctxt, NULL);
		    if (nsname != defaults->values[5 * i + 2]) {
			if (nsPush(ctxt, NULL,
			           defaults->values[5 * i + 2]) > 0)
			    nbNs++;
		    }
		} else if (aprefix == ctxt->str_xmlns) {
		    /*
		     * check that it's not a defined namespace
		     */
		    for (j = 1;j <= nbNs;j++)
		        if (ctxt->nsTab[ctxt->nsNr - 2 * j] == attname)
			    break;
	            if (j <= nbNs) continue;

		    nsname = xmlGetNamespace(ctxt, attname);
		    if (nsname != defaults->values[2]) {
			if (nsPush(ctxt, attname,
			           defaults->values[5 * i + 2]) > 0)
			    nbNs++;
		    }
		} else {
		    /*
		     * check that it's not a defined attribute
		     */
		    for (j = 0;j < nbatts;j+=5) {
			if ((attname == atts[j]) && (aprefix == atts[j+1]))
			    break;
		    }
		    if (j < nbatts) continue;

		    if ((atts == NULL) || (nbatts + 5 > maxatts)) {
			if (xmlCtxtGrowAttrs(ctxt, nbatts + 5) < 0) {
			    return(NULL);
			}
			maxatts = ctxt->maxatts;
			atts = ctxt->atts;
		    }
		    atts[nbatts++] = attname;
		    atts[nbatts++] = aprefix;
		    if (aprefix == NULL)
			atts[nbatts++] = NULL;
		    else
		        atts[nbatts++] = xmlGetNamespace(ctxt, aprefix);
		    atts[nbatts++] = defaults->values[5 * i + 2];
		    atts[nbatts++] = defaults->values[5 * i + 3];
		    if ((ctxt->standalone == 1) &&
		        (defaults->values[5 * i + 4] != NULL)) {
			xmlValidityError(ctxt, XML_DTD_STANDALONE_DEFAULTED,
	  "standalone: attribute %s on %s defaulted from external subset\n",
	                                 attname, localname);
		    }
		    nbdef++;
		}
	    }
	}
    }

    /*
     * The attributes checkings
     */
    for (i = 0; i < nbatts;i += 5) {
        /*
	* The default namespace does not apply to attribute names.
	*/
	if (atts[i + 1] != NULL) {
	    nsname = xmlGetNamespace(ctxt, atts[i + 1]);
	    if (nsname == NULL) {
		xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE,
		    "Namespace prefix %s for %s on %s is not defined\n",
		    atts[i + 1], atts[i], localname);
	    }
	    atts[i + 2] = nsname;
	} else
	    nsname = NULL;
	/*
	 * [ WFC: Unique Att Spec ]
	 * No attribute name may appear more than once in the same
	 * start-tag or empty-element tag.
	 * As extended by the Namespace in XML REC.
	 */
        for (j = 0; j < i;j += 5) {
	    if (atts[i] == atts[j]) {
	        if (atts[i+1] == atts[j+1]) {
		    xmlErrAttributeDup(ctxt, atts[i+1], atts[i]);
		    break;
		}
		if ((nsname != NULL) && (atts[j + 2] == nsname)) {
		    xmlNsErr(ctxt, XML_NS_ERR_ATTRIBUTE_REDEFINED,
			     "Namespaced Attribute %s in '%s' redefined\n",
			     atts[i], nsname, NULL);
		    break;
		}
	    }
	}
    }

    nsname = xmlGetNamespace(ctxt, prefix);
    if ((prefix != NULL) && (nsname == NULL)) {
	xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE,
	         "Namespace prefix %s on %s is not defined\n",
		 prefix, localname, NULL);
    }
    *pref = prefix;
    *URI = nsname;

    /*
     * SAX: Start of Element !
     */
    if ((ctxt->sax != NULL) && (ctxt->sax->startElementNs != NULL) &&
	(!ctxt->disableSAX)) {
	if (nbNs > 0)
	    ctxt->sax->startElementNs(ctxt->userData, localname, prefix,
			  nsname, nbNs, &ctxt->nsTab[ctxt->nsNr - 2 * nbNs],
			  nbatts / 5, nbdef, atts);
	else
	    ctxt->sax->startElementNs(ctxt->userData, localname, prefix,
	                  nsname, 0, NULL, nbatts / 5, nbdef, atts);
    }

    /*
     * Free up attribute allocated strings if needed
     */
    if (attval != 0) {
	for (i = 3,j = 0; j < nratts;i += 5,j++)
	    if ((ctxt->attallocs[j] != 0) && (atts[i] != NULL))
	        xmlFree((xmlChar *) atts[i]);
    }

    return(localname);
}


 void *atomic_thread(void *context) {
   struct atomic_test_s32_s *at = (struct atomic_test_s32_s *)context;
   for (int i = 0; i < at->max_val; i++) {
    TEMP_FAILURE_RETRY(usleep(1));
     atomic_inc_prefix_s32(&at->data[i]);
   }
   return NULL;
}


void RenderViewHostManager::OnCrossSiteResponse(int new_render_process_host_id,
                                                int new_request_id) {
  if (!cross_navigation_pending_)
    return;
  DCHECK(pending_render_view_host_);

  render_view_host_->SwapOut(new_render_process_host_id, new_request_id);

  pending_render_view_host_->SetHasPendingCrossSiteRequest(false,
                                                           new_request_id);
}


  bool try_stop_deletion() {
    Mutex::Locker l(lock);
    stop_deleting = true;
    /**
     * If we are in DELETING_DIR or CLEARING_DIR, there are in progress
     * operations we have to wait for before continuing on.  States
     * CLEARING_WAITING and QUEUED indicate that the remover will check
     * stop_deleting before queueing any further operations.  CANCELED
     * indicates that the remover has already halted.  DELETED_DIR
     * indicates that the deletion has been fully queued.
     */
    while (status == DELETING_DIR || status == CLEARING_DIR)
      cond.Wait(lock);
    return status != DELETED_DIR;
  } ///< @return true if we don't need to recreate the collection


static void showregs (RList *list) {
	if (!r_list_empty (list)) {
		char *reg;
		RListIter *iter;
		r_list_foreach (list, iter, reg) {
			r_cons_print (reg);
			if (iter->n) {
				r_cons_printf (" ");
			}
		}
	}
	r_cons_newline();
}


static void print_verifier_state(struct bpf_verifier_state *state)
{
	struct bpf_reg_state *reg;
	enum bpf_reg_type t;
	int i;

	for (i = 0; i < MAX_BPF_REG; i++) {
		reg = &state->regs[i];
		t = reg->type;
		if (t == NOT_INIT)
			continue;
		verbose(" R%d=%s", i, reg_type_str[t]);
		if (t == CONST_IMM || t == PTR_TO_STACK)
			verbose("%lld", reg->imm);
		else if (t == PTR_TO_PACKET)
			verbose("(id=%d,off=%d,r=%d)",
				reg->id, reg->off, reg->range);
		else if (t == UNKNOWN_VALUE && reg->imm)
			verbose("%lld", reg->imm);
		else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE ||
			 t == PTR_TO_MAP_VALUE_OR_NULL ||
			 t == PTR_TO_MAP_VALUE_ADJ)
			verbose("(ks=%d,vs=%d,id=%u)",
				reg->map_ptr->key_size,
				reg->map_ptr->value_size,
				reg->id);
		if (reg->min_value != BPF_REGISTER_MIN_RANGE)
			verbose(",min_value=%lld",
				(long long)reg->min_value);
		if (reg->max_value != BPF_REGISTER_MAX_RANGE)
			verbose(",max_value=%llu",
				(unsigned long long)reg->max_value);
	}
	for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
		if (state->stack_slot_type[i] == STACK_SPILL)
			verbose(" fp%d=%s", -MAX_BPF_STACK + i,
				reg_type_str[state->spilled_regs[i / BPF_REG_SIZE].type]);
	}
	verbose("\n");
}


file_pstring_length_size(const struct magic *m)
{
	switch (m->str_flags & PSTRING_LEN) {
	case PSTRING_1_LE:
		return 1;
	case PSTRING_2_LE:
	case PSTRING_2_BE:
		return 2;
	case PSTRING_4_LE:
	case PSTRING_4_BE:
		return 4;
	default:
		abort();	/* Impossible */
		return 1;
	}
}


void acpi_add_table(GArray *table_offsets, GArray *table_data)

{

    uint32_t offset = cpu_to_le32(table_data->len);

    g_array_append_val(table_offsets, offset);

}


parse_SAMPLE(char *arg, struct ofpbuf *ofpacts,
             enum ofputil_protocol *usable_protocols OVS_UNUSED)
{
    struct ofpact_sample *os = ofpact_put_SAMPLE(ofpacts);
    os->sampling_port = OFPP_NONE;
    os->direction = NX_ACTION_SAMPLE_DEFAULT;

    char *key, *value;
    while (ofputil_parse_key_value(&arg, &key, &value)) {
        char *error = NULL;

        if (!strcmp(key, "probability")) {
            error = str_to_u16(value, "probability", &os->probability);
            if (!error && os->probability == 0) {
                error = xasprintf("invalid probability value \"%s\"", value);
            }
        } else if (!strcmp(key, "collector_set_id")) {
            error = str_to_u32(value, &os->collector_set_id);
        } else if (!strcmp(key, "obs_domain_id")) {
            error = str_to_u32(value, &os->obs_domain_id);
        } else if (!strcmp(key, "obs_point_id")) {
            error = str_to_u32(value, &os->obs_point_id);
        } else if (!strcmp(key, "sampling_port")) {
            if (!ofputil_port_from_string(value, &os->sampling_port)) {
                error = xasprintf("%s: unknown port", value);
            }
        } else if (!strcmp(key, "ingress")) {
            os->direction = NX_ACTION_SAMPLE_INGRESS;
        } else if (!strcmp(key, "egress")) {
            os->direction = NX_ACTION_SAMPLE_EGRESS;
        } else {
            error = xasprintf("invalid key \"%s\" in \"sample\" argument",
                              key);
        }
        if (error) {
            return error;
        }
    }
    if (os->probability == 0) {
        return xstrdup("non-zero \"probability\" must be specified on sample");
    }

    return NULL;
}


TfLiteStatus ReshapeOutput(TfLiteContext* context, TfLiteNode* node) {
  const TfLiteTensor* input = GetInput(context, node, kInputTensor);
  TF_LITE_ENSURE(context, input != nullptr);
  TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
  TF_LITE_ENSURE(context, output != nullptr);
  // Tensorflow's Reshape allows one of the shape components to have the
  // special -1 value, meaning it will be calculated automatically based on the
  // input. Here we calculate what that dimension should be so that the number
  // of output elements in the same as the number of input elements.
  int num_input_elements = NumElements(input);
  TfLiteIntArray* output_shape = output->dims;

  if (NumInputs(node) == 1 &&  // Legacy scalar supported with params.
      output_shape->size == 1 && output_shape->data[0] == 0) {
    // Legacy tflite models use a shape parameter of [0] to indicate scalars,
    // so adjust accordingly. TODO(b/111614235): Allow zero-sized buffers during
    // toco conversion.
    output_shape->size = 0;
  }

  int num_output_elements = 1;
  int stretch_dim = -1;
  for (int i = 0; i < output_shape->size; ++i) {
    int value = output_shape->data[i];
    if (value == -1) {
      TF_LITE_ENSURE_EQ(context, stretch_dim, -1);
      stretch_dim = i;
    } else {
      num_output_elements *= value;
    }
  }
  if (stretch_dim != -1) {
    output_shape->data[stretch_dim] = num_input_elements / num_output_elements;
    num_output_elements *= output_shape->data[stretch_dim];
  }

  TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);
  TF_LITE_ENSURE_EQ(context, num_input_elements, num_output_elements);
  return kTfLiteOk;
}


      static double mp_vector_map_v(_cimg_math_parser& mp) { // Operator(vector)
        unsigned int
          siz = (unsigned int)mp.opcode[2],
          ptrs = (unsigned int)mp.opcode[4] + 1;
        double *ptrd = &_mp_arg(1) + 1;
        mp_func op = (mp_func)mp.opcode[3];
        CImg<ulongT> l_opcode(1,3);
        l_opcode.swap(mp.opcode);
        ulongT &argument = mp.opcode[2];
        while (siz-->0) { argument = ptrs++; *(ptrd++) = (*op)(mp); }
        l_opcode.swap(mp.opcode);
        return cimg::type<double>::nan();


static int multiSelectValues(
  Parse *pParse,        /* Parsing context */
  Select *p,            /* The right-most of SELECTs to be coded */
  SelectDest *pDest     /* What to do with query results */
){
  int nRow = 1;
  int rc = 0;
  int bShowAll = p->pLimit==0;
  assert( p->selFlags & SF_MultiValue );
  do{
    assert( p->selFlags & SF_Values );
    assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
    assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
    if( p->pWin ) return -1;
    if( p->pPrior==0 ) break;
    assert( p->pPrior->pNext==p );
    p = p->pPrior;
    nRow += bShowAll;
  }while(1);
  ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow,
                    nRow==1 ? "" : "S"));
  while( p ){
    selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1);
    if( !bShowAll ) break;
    p->nSelectRow = nRow;
    p = p->pNext;
  }
  return rc;
}


PassRefPtrWillBeRawPtr<DocumentFragment> Document::createDocumentFragment()
{
    return DocumentFragment::create(*this);
}


static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
					 struct kvm_xsave *guest_xsave)
{
	if (cpu_has_xsave)
		memcpy(guest_xsave->region,
			&vcpu->arch.guest_fpu.state->xsave,
			xstate_size);
	else {
		memcpy(guest_xsave->region,
			&vcpu->arch.guest_fpu.state->fxsave,
			sizeof(struct i387_fxsave_struct));
		*(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
			XSTATE_FPSSE;
	}
}


struct pid *pidfd_pid(const struct file *file)
{
	if (file->f_op == &pidfd_fops)
		return file->private_data;

	return ERR_PTR(-EBADF);
}


ftp_do_pasv (int csock, ip_address *addr, int *port)
{
  if (!opt.server_response)
    logputs (LOG_VERBOSE, "==> PASV ... ");
  return ftp_pasv (csock, addr, port);
}


virtual void ReleaseTransportDIB(TransportDIB* memory) {}


static int DefragMfIpv6Test(void)
{
    int retval = 0;
    int ip_id = 9;
    Packet *p = NULL;

    DefragInit();

    Packet *p1 = IPV6BuildTestPacket(ip_id, 2, 1, 'C', 8);
    Packet *p2 = IPV6BuildTestPacket(ip_id, 0, 1, 'A', 8);
    Packet *p3 = IPV6BuildTestPacket(ip_id, 1, 0, 'B', 8);
    if (p1 == NULL || p2 == NULL || p3 == NULL) {
        goto end;
    }

    p = Defrag(NULL, NULL, p1, NULL);
    if (p != NULL) {
        goto end;
    }

    p = Defrag(NULL, NULL, p2, NULL);
    if (p != NULL) {
        goto end;
    }

    /* This should return a packet as MF=0. */
    p = Defrag(NULL, NULL, p3, NULL);
    if (p == NULL) {
        goto end;
    }

    /* For IPv6 the expected length is just the length of the payload
     * of 2 fragments, so 16. */
    if (IPV6_GET_PLEN(p) != 16) {
        goto end;
    }

    retval = 1;
end:
    if (p1 != NULL) {
        SCFree(p1);
    }
    if (p2 != NULL) {
        SCFree(p2);
    }
    if (p3 != NULL) {
        SCFree(p3);
    }
    if (p != NULL) {
        SCFree(p);
    }
    DefragDestroy();
    return retval;
}


bool ExtensionApiTest::RunExtensionTestWithFlags(
    const std::string& extension_name,
    int flags) {
  return RunExtensionTestImpl(extension_name, std::string(), nullptr, flags);
}


BaseGroupVerifierImpl(const BaseVerifierImpl* parent) : BaseVerifierImpl(parent) {}


int cifs_file_strict_mmap(struct file *file, struct vm_area_struct *vma)
{
	int rc, xid;
	struct inode *inode = file_inode(file);

	xid = get_xid();

	if (!CIFS_CACHE_READ(CIFS_I(inode))) {
		rc = cifs_invalidate_mapping(inode);
		if (rc)
			return rc;
	}

	rc = generic_file_mmap(file, vma);
	if (rc == 0)
		vma->vm_ops = &cifs_file_vm_ops;
	free_xid(xid);
	return rc;
}


char *vnc_display_local_addr(DisplayState *ds)

{

    VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;

    return vnc_socket_local_addr("%s:%s", vs->lsock);

}


void AXObjectCacheImpl::handleUpdateActiveMenuOption(LayoutMenuList* menuList,
                                                     int optionIndex) {
  AXObject* obj = get(menuList);
  if (!obj || !obj->isMenuList())
    return;

  toAXMenuList(obj)->didUpdateActiveOption(optionIndex);
}


  SpaceToBatchNDContext(TfLiteContext* context, TfLiteNode* node) {
    input = GetInput(context, node, 0);
    block_shape = GetInput(context, node, 1);
    paddings = GetInput(context, node, 2);
    output = GetOutput(context, node, 0);
  }


void var_set_int(const char* name, int value)
{
  char buf[21];
  my_snprintf(buf, sizeof(buf), "%d", value);
  var_set_string(name, buf);
}


_archive_write_disk_close(struct archive *_a)
{
	struct archive_write_disk *a = (struct archive_write_disk *)_a;
	struct fixup_entry *next, *p;
	int ret;

	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
	    ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
	    "archive_write_disk_close");
	ret = _archive_write_disk_finish_entry(&a->archive);

	/* Sort dir list so directories are fixed up in depth-first order. */
	p = sort_dir_list(a->fixup_list);

	while (p != NULL) {
		a->pst = NULL; /* Mark stat cache as out-of-date. */
		if (p->fixup & TODO_TIMES) {
			set_times(a, -1, p->mode, p->name,
			    p->atime, p->atime_nanos,
			    p->birthtime, p->birthtime_nanos,
			    p->mtime, p->mtime_nanos,
			    p->ctime, p->ctime_nanos);
		}
		if (p->fixup & TODO_MODE_BASE)
			chmod(p->name, p->mode);
		if (p->fixup & TODO_ACLS)
			archive_write_disk_set_acls(&a->archive,
						    -1, p->name, &p->acl);
		if (p->fixup & TODO_FFLAGS)
			set_fflags_platform(a, -1, p->name,
			    p->mode, p->fflags_set, 0);
		if (p->fixup & TODO_MAC_METADATA)
			set_mac_metadata(a, p->name, p->mac_metadata,
					 p->mac_metadata_size);
		next = p->next;
		archive_acl_clear(&p->acl);
		free(p->mac_metadata);
		free(p->name);
		free(p);
		p = next;
	}
	a->fixup_list = NULL;
	return (ret);
}


void FaviconWebUIHandler::RegisterMessages() {
  web_ui_->RegisterMessageCallback("getFaviconDominantColor",
      NewCallback(this, &FaviconWebUIHandler::HandleGetFaviconDominantColor));
}


static void mp_put_chars(struct tty_struct *tty)
{
	mp_start(tty);
}


static int readAPListRid(struct airo_info *ai, APListRid *aplr)
{
	return PC4500_readrid(ai, RID_APLIST, aplr, sizeof(*aplr), 1);
}


static void coin_cleanup(void* c)
{
  uivector_cleanup(&((Coin*)c)->symbols);
}


static bool cmd_set_features(IDEState *s, uint8_t cmd)
{
    uint16_t *identify_data;

    if (!s->blk) {
        ide_abort_command(s);
        return true;
    }

    /* XXX: valid for CDROM ? */
    switch (s->feature) {
    case 0x02: /* write cache enable */
        blk_set_enable_write_cache(s->blk, true);
        identify_data = (uint16_t *)s->identify_data;
        put_le16(identify_data + 85, (1 << 14) | (1 << 5) | 1);
        return true;
    case 0x82: /* write cache disable */
        blk_set_enable_write_cache(s->blk, false);
        identify_data = (uint16_t *)s->identify_data;
        put_le16(identify_data + 85, (1 << 14) | 1);
        ide_flush_cache(s);
        return false;
    case 0xcc: /* reverting to power-on defaults enable */
    case 0x66: /* reverting to power-on defaults disable */
    case 0xaa: /* read look-ahead enable */
    case 0x55: /* read look-ahead disable */
    case 0x05: /* set advanced power management mode */
    case 0x85: /* disable advanced power management mode */
    case 0x69: /* NOP */
    case 0x67: /* NOP */
    case 0x96: /* NOP */
    case 0x9a: /* NOP */
    case 0x42: /* enable Automatic Acoustic Mode */
    case 0xc2: /* disable Automatic Acoustic Mode */
        return true;
    case 0x03: /* set transfer mode */
        {
            uint8_t val = s->nsector & 0x07;
            identify_data = (uint16_t *)s->identify_data;

            switch (s->nsector >> 3) {
            case 0x00: /* pio default */
            case 0x01: /* pio mode */
                put_le16(identify_data + 62, 0x07);
                put_le16(identify_data + 63, 0x07);
                put_le16(identify_data + 88, 0x3f);
                break;
            case 0x02: /* sigle word dma mode*/
                put_le16(identify_data + 62, 0x07 | (1 << (val + 8)));
                put_le16(identify_data + 63, 0x07);
                put_le16(identify_data + 88, 0x3f);
                break;
            case 0x04: /* mdma mode */
                put_le16(identify_data + 62, 0x07);
                put_le16(identify_data + 63, 0x07 | (1 << (val + 8)));
                put_le16(identify_data + 88, 0x3f);
                break;
            case 0x08: /* udma mode */
                put_le16(identify_data + 62, 0x07);
                put_le16(identify_data + 63, 0x07);
                put_le16(identify_data + 88, 0x3f | (1 << (val + 8)));
                break;
            default:
                goto abort_cmd;
            }
            return true;
        }
    }

abort_cmd:
    ide_abort_command(s);
    return true;
}


uint32_t GPMF_StructSize(GPMF_stream *ms)
{
	if (ms && ms->pos+1 < ms->buffer_size_longs)
	{
		uint32_t ssize = GPMF_SAMPLE_SIZE(ms->buffer[ms->pos + 1]);
		uint32_t size = (GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]) >> 2);

		if (GPMF_OK != IsValidSize(ms, size)) return 0; // as the structure is corrupted. i.e. GPMF_ERROR_BAD_STRUCTURE;

		return ssize;
	}
	return 0;
}


free_config_tree(
	config_tree *ptree
	)
{
#if defined(_MSC_VER) && defined (_DEBUG)
	_CrtCheckMemory();
#endif

	if (ptree->source.value.s != NULL)
		free(ptree->source.value.s);

	free_config_other_modes(ptree);
	free_config_auth(ptree);
	free_config_tos(ptree);
	free_config_monitor(ptree);
	free_config_access(ptree);
	free_config_tinker(ptree);
	free_config_system_opts(ptree);
	free_config_logconfig(ptree);
	free_config_phone(ptree);
	free_config_qos(ptree);
	free_config_setvar(ptree);
	free_config_ttl(ptree);
	free_config_trap(ptree);
	free_config_fudge(ptree);
	free_config_vars(ptree);
	free_config_peers(ptree);
	free_config_unpeers(ptree);
	free_config_nic_rules(ptree);
#ifdef SIM
	free_config_sim(ptree);
#endif
	free_auth_node(ptree);

	free(ptree);

#if defined(_MSC_VER) && defined (_DEBUG)
	_CrtCheckMemory();
#endif
}


void dd_save_text(struct dump_dir *dd, const char *name, const char *data)
{
    if (!dd->locked)
        error_msg_and_die("dump_dir is not opened"); /* bug */

    if (!str_is_correct_filename(name))
        error_msg_and_die("Cannot save text. '%s' is not a valid file name", name);

    char *full_path = concat_path_file(dd->dd_dirname, name);
    save_binary_file(full_path, data, strlen(data), dd->dd_uid, dd->dd_gid, dd->mode);
    free(full_path);
}


 TestNativeHandler::TestNativeHandler(ScriptContext* context)
     : ObjectBackedNativeHandler(context) {
   RouteFunction(
      "GetWakeEventPage",
       base::Bind(&TestNativeHandler::GetWakeEventPage, base::Unretained(this)));
 }


static int glyphmatches ( SplineChar * sc , SplineChar * sc2 , int layer ) {
 RefChar * r , * r2 ;
 SplineSet * ss , * ss2 ;
 SplinePoint * sp , * sp2 ;
 if ( sc -> width != sc2 -> width ) return ( false ) ;
 if ( sc -> ttf_instrs_len != sc2 -> ttf_instrs_len ) return ( false ) ;
 if ( sc -> ttf_instrs_len != 0 && memcmp ( sc -> ttf_instrs , sc2 -> ttf_instrs , sc -> ttf_instrs_len ) != 0 ) return ( false ) ;
 for ( r = sc -> layers [ layer ] . refs , r2 = sc2 -> layers [ layer ] . refs ;
 r != NULL && r2 != NULL ;
 r = r -> next , r2 = r2 -> next ) {
 if ( r -> transform [ 0 ] != r2 -> transform [ 0 ] || r -> transform [ 1 ] != r2 -> transform [ 1 ] || r -> transform [ 2 ] != r2 -> transform [ 2 ] || r -> transform [ 3 ] != r2 -> transform [ 3 ] || r -> transform [ 4 ] != r2 -> transform [ 4 ] || r -> transform [ 5 ] != r2 -> transform [ 5 ] ) return ( false ) ;
 if ( r -> sc -> unicodeenc != r2 -> sc -> unicodeenc ) return ( false ) ;
 if ( r -> sc -> unicodeenc == - 1 && strcmp ( r -> sc -> name , r2 -> sc -> name ) != 0 ) return ( false ) ;
 }
 if ( r != NULL || r2 != NULL ) return ( false ) ;
 for ( ss = sc -> layers [ layer ] . splines , ss2 = sc2 -> layers [ layer ] . splines ;
 ss != NULL && ss2 != NULL ;
 ss = ss -> next , ss2 = ss2 -> next ) {
 for ( sp = ss -> first , sp2 = ss2 -> first ;
 sp != NULL && sp2 != NULL ;
 ) {
 if ( sp -> me . x != sp2 -> me . x || sp -> me . y != sp2 -> me . y || sp -> nextcp . x != sp2 -> nextcp . x || sp -> nextcp . y != sp2 -> nextcp . y || sp -> prevcp . x != sp2 -> prevcp . x || sp -> prevcp . y != sp2 -> prevcp . y ) return ( false ) ;
 sp = ( sp -> next ? sp -> next -> to : NULL ) ;
 sp2 = ( sp2 -> next ? sp2 -> next -> to : NULL ) ;
 if ( sp == ss -> first ) {
 if ( sp2 == ss2 -> first ) break ;
 return ( false ) ;
 }
 else if ( sp2 == ss2 -> first ) return ( false ) ;
 }
 if ( ( sp == NULL && sp2 != NULL ) || ( sp != NULL && sp2 == NULL ) ) return ( false ) ;
 }
 if ( ss == NULL && ss2 == NULL ) return ( true ) ;
 return ( false ) ;
 }


static uint64_t assigned_dev_ioport_rw(AssignedDevRegion *dev_region,

                                       target_phys_addr_t addr, int size,

                                       uint64_t *data)

{

    uint64_t val = 0;

    int fd = dev_region->region->resource_fd;

    if (fd >= 0) {

        if (data) {

            DEBUG("pwrite data=%" PRIx64 ", size=%d, e_phys=" TARGET_FMT_plx

                  ", addr="TARGET_FMT_plx"\n", *data, size, addr, addr);

            if (pwrite(fd, data, size, addr) != size) {

                error_report("%s - pwrite failed %s",

                             __func__, strerror(errno));

            }

        } else {

            if (pread(fd, &val, size, addr) != size) {

                error_report("%s - pread failed %s",

                             __func__, strerror(errno));

                val = (1UL << (size * 8)) - 1;

            }

            DEBUG("pread val=%" PRIx64 ", size=%d, e_phys=" TARGET_FMT_plx

                  ", addr=" TARGET_FMT_plx "\n", val, size, addr, addr);

        }

    } else {

        uint32_t port = addr + dev_region->u.r_baseport;

        if (data) {

            DEBUG("out data=%" PRIx64 ", size=%d, e_phys=" TARGET_FMT_plx

                  ", host=%x\n", *data, size, addr, port);

            switch (size) {

            case 1:

                outb(*data, port);

                break;

            case 2:

                outw(*data, port);

                break;

            case 4:

                outl(*data, port);

                break;

            }

        } else {

            switch (size) {

            case 1:

                val = inb(port);

                break;

            case 2:

                val = inw(port);

                break;

            case 4:

                val = inl(port);

                break;

            }

            DEBUG("in data=%" PRIx64 ", size=%d, e_phys=" TARGET_FMT_plx

                  ", host=%x\n", val, size, addr, port);

        }

    }

    return val;

}


void SoftVorbis::onQueueFilled(OMX_U32 portIndex) {
 List<BufferInfo *> &inQueue = getPortQueue(0);
 List<BufferInfo *> &outQueue = getPortQueue(1);

 if (mOutputPortSettingsChange != NONE) {
 return;
 }

 if (portIndex == 0 && mInputBufferCount < 2) {
 BufferInfo *info = *inQueue.begin();
        OMX_BUFFERHEADERTYPE *header = info->mHeader;

         const uint8_t *data = header->pBuffer + header->nOffset;
         size_t size = header->nFilledLen;
        if (size < 7) {
            ALOGE("Too small input buffer: %zu bytes", size);
            android_errorWriteLog(0x534e4554, "27833616");
            notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
            return;
        }

         ogg_buffer buf;
         ogg_reference ref;
        oggpack_buffer bits;

        makeBitReader(
 (const uint8_t *)data + 7, size - 7,
 &buf, &ref, &bits);

 if (mInputBufferCount == 0) {
            CHECK(mVi == NULL);
            mVi = new vorbis_info;
            vorbis_info_init(mVi);

            CHECK_EQ(0, _vorbis_unpack_info(mVi, &bits));
 } else {
            CHECK_EQ(0, _vorbis_unpack_books(mVi, &bits));

            CHECK(mState == NULL);
            mState = new vorbis_dsp_state;
            CHECK_EQ(0, vorbis_dsp_init(mState, mVi));

            notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
            mOutputPortSettingsChange = AWAITING_DISABLED;
 }

        inQueue.erase(inQueue.begin());
        info->mOwnedByUs = false;
        notifyEmptyBufferDone(header);

 ++mInputBufferCount;

 return;
 }

 while ((!inQueue.empty() || (mSawInputEos && !mSignalledOutputEos)) && !outQueue.empty()) {
 BufferInfo *inInfo = NULL;
        OMX_BUFFERHEADERTYPE *inHeader = NULL;
 if (!inQueue.empty()) {
            inInfo = *inQueue.begin();
            inHeader = inInfo->mHeader;
 }

 BufferInfo *outInfo = *outQueue.begin();
        OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;

 int32_t numPageSamples = 0;

 if (inHeader) {
 if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
                mSawInputEos = true;
 }

 if (inHeader->nFilledLen || !mSawInputEos) {
                CHECK_GE(inHeader->nFilledLen, sizeof(numPageSamples));
                memcpy(&numPageSamples,
                       inHeader->pBuffer
 + inHeader->nOffset + inHeader->nFilledLen - 4,
 sizeof(numPageSamples));

 if (inHeader->nOffset == 0) {
                    mAnchorTimeUs = inHeader->nTimeStamp;
                    mNumFramesOutput = 0;
 }

                inHeader->nFilledLen -= sizeof(numPageSamples);;
 }
 }

 if (numPageSamples >= 0) {
            mNumFramesLeftOnPage = numPageSamples;
 }

        ogg_buffer buf;
        buf.data = inHeader ? inHeader->pBuffer + inHeader->nOffset : NULL;
        buf.size = inHeader ? inHeader->nFilledLen : 0;
        buf.refcount = 1;
        buf.ptr.owner = NULL;

        ogg_reference ref;
        ref.buffer = &buf;
        ref.begin = 0;
        ref.length = buf.size;
        ref.next = NULL;

        ogg_packet pack;
        pack.packet = &ref;
        pack.bytes = ref.length;
        pack.b_o_s = 0;
        pack.e_o_s = 0;
        pack.granulepos = 0;
        pack.packetno = 0;

 int numFrames = 0;

        outHeader->nFlags = 0;
 int err = vorbis_dsp_synthesis(mState, &pack, 1);
 if (err != 0) {
#if !defined(__arm__) && !defined(__aarch64__)
            ALOGV("vorbis_dsp_synthesis returned %d", err);
#else

             ALOGW("vorbis_dsp_synthesis returned %d", err);
 #endif
         } else {
            size_t numSamplesPerBuffer = kMaxNumSamplesPerBuffer;
            if (numSamplesPerBuffer > outHeader->nAllocLen / sizeof(int16_t)) {
                numSamplesPerBuffer = outHeader->nAllocLen / sizeof(int16_t);
                android_errorWriteLog(0x534e4554, "27833616");
            }
             numFrames = vorbis_dsp_pcmout(
                     mState, (int16_t *)outHeader->pBuffer,
                    (numSamplesPerBuffer / mVi->channels));

             if (numFrames < 0) {
                 ALOGE("vorbis_dsp_pcmout returned %d", numFrames);
                numFrames = 0;
 }
 }

 if (mNumFramesLeftOnPage >= 0) {
 if (numFrames > mNumFramesLeftOnPage) {
                ALOGV("discarding %d frames at end of page",
                     numFrames - mNumFramesLeftOnPage);
                numFrames = mNumFramesLeftOnPage;
 if (mSawInputEos) {
                    outHeader->nFlags = OMX_BUFFERFLAG_EOS;
                    mSignalledOutputEos = true;
 }
 }
            mNumFramesLeftOnPage -= numFrames;
 }

        outHeader->nFilledLen = numFrames * sizeof(int16_t) * mVi->channels;
        outHeader->nOffset = 0;

        outHeader->nTimeStamp =
            mAnchorTimeUs
 + (mNumFramesOutput * 1000000ll) / mVi->rate;

        mNumFramesOutput += numFrames;

 if (inHeader) {
            inInfo->mOwnedByUs = false;
            inQueue.erase(inQueue.begin());
            inInfo = NULL;
            notifyEmptyBufferDone(inHeader);
            inHeader = NULL;
 }

        outInfo->mOwnedByUs = false;
        outQueue.erase(outQueue.begin());
        outInfo = NULL;
        notifyFillBufferDone(outHeader);
        outHeader = NULL;

 ++mInputBufferCount;
 }
}


String HHVM_FUNCTION(nl2br,
                     const String& str,
                     bool is_xhtml /* = true */) {
  if (str.empty()) {
    return str;
  }
  String htmlType;

  if (is_xhtml) {
    htmlType = s_br;
  } else {
    htmlType = s_non_xhtml_br;
  }

  return stringForEachBuffered(
    str.size(), str,
    [&](StringBuffer& ret, const char*& src, const char* /*end*/) {
      // PHP treats a carriage return beside a newline as the same break
      // no matter what order they're in.  Don't do it for two of the same in
      // a row, though...
      switch (*src) {
        case '\n':
          ret.append(htmlType);
          // skip next if carriage return
          if (*(src + 1) == '\r') {
            ret.append(*src);
            ++src;
          }
          ret.append(*src);
          break;
        case '\r':
          ret.append(htmlType);
          // skip next if newline
          if (*(src + 1) == '\n') {
            ret.append(*src);
            ++src;
          }
        /* fall through */
        default: ret.append(*src);
      }
    });
}


static int make_cdt16_entry ( int p1 , int p2 , int16_t * cdt ) {
 int r , b , lo ;
 b = cdt [ p2 ] ;
 r = cdt [ p1 ] << 11 ;
 lo = b + r ;
 return ( lo + ( lo << 16 ) ) << 1 ;
 }


handle_tlv_table_request(struct ofconn *ofconn, const struct ofp_header *oh)
{
    const struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
    struct ofputil_tlv_table_reply ttr;
    struct ofpbuf *b;

    tun_metadata_table_request(ofproto_get_tun_tab(ofproto), &ttr);

    b = ofputil_encode_tlv_table_reply(oh, &ttr);
    ofputil_uninit_tlv_table(&ttr.mappings);

    ofconn_send_reply(ofconn, b);
    return 0;
}


PredictorEncodeTile(TIFF* tif, uint8* bp0, tmsize_t cc0, uint16 s)
{
	static const char module[] = "PredictorEncodeTile";
	TIFFPredictorState *sp = PredictorState(tif);
        uint8 *working_copy;
	tmsize_t cc = cc0, rowsize;
	unsigned char* bp;
        int result_code;

	assert(sp != NULL);
	assert(sp->encodepfunc != NULL);
	assert(sp->encodetile != NULL);

        /*
         * Do predictor manipulation in a working buffer to avoid altering
         * the callers buffer. http://trac.osgeo.org/gdal/ticket/1965
         */
        working_copy = (uint8*) _TIFFmalloc(cc0);
        if( working_copy == NULL )
        {
            TIFFErrorExt(tif->tif_clientdata, module,
                         "Out of memory allocating " TIFF_SSIZE_FORMAT " byte temp buffer.",
                         cc0 );
            return 0;
        }
        memcpy( working_copy, bp0, cc0 );
        bp = working_copy;

	rowsize = sp->rowsize;
	assert(rowsize > 0);
	if((cc0%rowsize)!=0)
    {
        TIFFErrorExt(tif->tif_clientdata, "PredictorEncodeTile",
                     "%s", "(cc0%rowsize)!=0");
        return 0;
    }
	while (cc > 0) {
		(*sp->encodepfunc)(tif, bp, rowsize);
		cc -= rowsize;
		bp += rowsize;
	}
	result_code = (*sp->encodetile)(tif, working_copy, cc0, s);

        _TIFFfree( working_copy );

        return result_code;
}


static void do_flush_tlb_all(void *info)
{
	count_vm_tlb_event(NR_TLB_REMOTE_FLUSH_RECEIVED);
	__flush_tlb_all();
	if (this_cpu_read(cpu_tlbstate.state) == TLBSTATE_LAZY)
		leave_mm(smp_processor_id());
}


ZEND_API int _zend_get_parameters_array_ex(int param_count, zval ***argument_array TSRMLS_DC) /* {{{ */
{
	void **p;
	int arg_count;

	p = zend_vm_stack_top(TSRMLS_C) - 1;
	arg_count = (int)(zend_uintptr_t) *p;

	if (param_count>arg_count) {
		return FAILURE;
	}

	while (param_count-->0) {
		zval **value = (zval**)(p-arg_count);

		*(argument_array++) = value;
		arg_count--;
	}

	return SUCCESS;
}
/* }}} */


void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
{
	kvm_multiple_exception(vcpu, nr, true, error_code, true);
}