void ACSequentialScan::WriteFrameType(class ByteStream *io)
{
#if ACCUSOFT_CODE
  UBYTE hidden = m_pFrame->TablesOf()->HiddenDCTBitsOf();

  if (m_ucScanStart > 0 || m_ucScanStop < 63 || m_ucLowBit > hidden) {
    // is progressive.
    if (m_bResidual) {
      io->PutWord(0xffba); // progressive sequential
    } else {
      if (m_bDifferential) {
        io->PutWord(0xffce);
      } else {
        io->PutWord(0xffca);
      }
    }
  } else {
    if (m_bResidual) {
      io->PutWord(0xffb9); // residual AC sequential
    } else if (m_bDifferential) {
      io->PutWord(0xffcd); // AC differential sequential
    } else if (m_bLargeRange) {
      io->PutWord(0xffbb);
    } else {
      io->PutWord(0xffc9); // AC sequential
    }
  }
#else
  NOREF(io);
#endif
}


static int nl80211_del_key(struct sk_buff *skb, struct genl_info *info)
{
	struct cfg80211_registered_device *rdev = info->user_ptr[0];
	int err;
	struct net_device *dev = info->user_ptr[1];
	u8 *mac_addr = NULL;
	struct key_parse key;

	err = nl80211_parse_key(info, &key);
	if (err)
		return err;

	if (info->attrs[NL80211_ATTR_MAC])
		mac_addr = nla_data(info->attrs[NL80211_ATTR_MAC]);

	if (key.type == -1) {
		if (mac_addr)
			key.type = NL80211_KEYTYPE_PAIRWISE;
		else
			key.type = NL80211_KEYTYPE_GROUP;
	}

	/* for now */
	if (key.type != NL80211_KEYTYPE_PAIRWISE &&
	    key.type != NL80211_KEYTYPE_GROUP)
		return -EINVAL;

	if (!rdev->ops->del_key)
		return -EOPNOTSUPP;

	wdev_lock(dev->ieee80211_ptr);
	err = nl80211_key_allowed(dev->ieee80211_ptr);

	if (key.type == NL80211_KEYTYPE_PAIRWISE && mac_addr &&
	    !(rdev->wiphy.flags & WIPHY_FLAG_IBSS_RSN))
		err = -ENOENT;

	if (!err)
		err = rdev->ops->del_key(&rdev->wiphy, dev, key.idx,
					 key.type == NL80211_KEYTYPE_PAIRWISE,
					 mac_addr);

#ifdef CONFIG_CFG80211_WEXT
	if (!err) {
		if (key.idx == dev->ieee80211_ptr->wext.default_key)
			dev->ieee80211_ptr->wext.default_key = -1;
		else if (key.idx == dev->ieee80211_ptr->wext.default_mgmt_key)
			dev->ieee80211_ptr->wext.default_mgmt_key = -1;
	}
#endif
	wdev_unlock(dev->ieee80211_ptr);

	return err;
}


static int qeth_setadpparms_change_macaddr_cb(struct qeth_card *card,
		struct qeth_reply *reply, unsigned long data)
{
	struct qeth_ipa_cmd *cmd;

	QETH_CARD_TEXT(card, 4, "chgmaccb");

	cmd = (struct qeth_ipa_cmd *) data;
	if (!card->options.layer2 ||
	    !(card->info.mac_bits & QETH_LAYER2_MAC_READ)) {
		memcpy(card->dev->dev_addr,
		       &cmd->data.setadapterparms.data.change_addr.addr,
		       OSA_ADDR_LEN);
		card->info.mac_bits |= QETH_LAYER2_MAC_READ;
	}
	qeth_default_setadapterparms_cb(card, reply, (unsigned long) cmd);
	return 0;
}


static void fdctrl_start_transfer(FDCtrl *fdctrl, int direction)

{

    FDrive *cur_drv;

    uint8_t kh, kt, ks;

    SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);

    cur_drv = get_cur_drv(fdctrl);

    kt = fdctrl->fifo[2];

    kh = fdctrl->fifo[3];

    ks = fdctrl->fifo[4];

    FLOPPY_DPRINTF("Start transfer at %d %d %02x %02x (%d)\n",

                   GET_CUR_DRV(fdctrl), kh, kt, ks,

                   fd_sector_calc(kh, kt, ks, cur_drv->last_sect,

                                  NUM_SIDES(cur_drv)));

    switch (fd_seek(cur_drv, kh, kt, ks, fdctrl->config & FD_CONFIG_EIS)) {

    case 2:

        /* sect too big */

        fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, 0x00, 0x00);

        fdctrl->fifo[3] = kt;

        fdctrl->fifo[4] = kh;

        fdctrl->fifo[5] = ks;

        return;

    case 3:

        /* track too big */

        fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, FD_SR1_EC, 0x00);

        fdctrl->fifo[3] = kt;

        fdctrl->fifo[4] = kh;

        fdctrl->fifo[5] = ks;

        return;

    case 4:

        /* No seek enabled */

        fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, 0x00, 0x00);

        fdctrl->fifo[3] = kt;

        fdctrl->fifo[4] = kh;

        fdctrl->fifo[5] = ks;

        return;

    case 1:

        fdctrl->status0 |= FD_SR0_SEEK;

        break;

    default:

        break;

    }

    /* Check the data rate. If the programmed data rate does not match

     * the currently inserted medium, the operation has to fail. */

    if (fdctrl->check_media_rate &&

        (fdctrl->dsr & FD_DSR_DRATEMASK) != cur_drv->media_rate) {

        FLOPPY_DPRINTF("data rate mismatch (fdc=%d, media=%d)\n",

                       fdctrl->dsr & FD_DSR_DRATEMASK, cur_drv->media_rate);

        fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, FD_SR1_MA, 0x00);

        fdctrl->fifo[3] = kt;

        fdctrl->fifo[4] = kh;

        fdctrl->fifo[5] = ks;

        return;

    }

    /* Set the FIFO state */

    fdctrl->data_dir = direction;

    fdctrl->data_pos = 0;

    fdctrl->msr |= FD_MSR_CMDBUSY;

    if (fdctrl->fifo[0] & 0x80)

        fdctrl->data_state |= FD_STATE_MULTI;

    else

        fdctrl->data_state &= ~FD_STATE_MULTI;

    if (fdctrl->fifo[5] == 00) {

        fdctrl->data_len = fdctrl->fifo[8];

    } else {

        int tmp;

        fdctrl->data_len = 128 << (fdctrl->fifo[5] > 7 ? 7 : fdctrl->fifo[5]);

        tmp = (fdctrl->fifo[6] - ks + 1);

        if (fdctrl->fifo[0] & 0x80)

            tmp += fdctrl->fifo[6];

        fdctrl->data_len *= tmp;

    }

    fdctrl->eot = fdctrl->fifo[6];

    if (fdctrl->dor & FD_DOR_DMAEN) {

        int dma_mode;

        /* DMA transfer are enabled. Check if DMA channel is well programmed */

        dma_mode = DMA_get_channel_mode(fdctrl->dma_chann);

        dma_mode = (dma_mode >> 2) & 3;

        FLOPPY_DPRINTF("dma_mode=%d direction=%d (%d - %d)\n",

                       dma_mode, direction,

                       (128 << fdctrl->fifo[5]) *

                       (cur_drv->last_sect - ks + 1), fdctrl->data_len);

        if (((direction == FD_DIR_SCANE || direction == FD_DIR_SCANL ||

              direction == FD_DIR_SCANH) && dma_mode == 0) ||

            (direction == FD_DIR_WRITE && dma_mode == 2) ||

            (direction == FD_DIR_READ && dma_mode == 1)) {

            /* No access is allowed until DMA transfer has completed */

            fdctrl->msr &= ~FD_MSR_RQM;

            /* Now, we just have to wait for the DMA controller to

             * recall us...

             */

            DMA_hold_DREQ(fdctrl->dma_chann);

            DMA_schedule(fdctrl->dma_chann);

            return;

        } else {

            FLOPPY_DPRINTF("bad dma_mode=%d direction=%d\n", dma_mode,

                           direction);

        }

    }

    FLOPPY_DPRINTF("start non-DMA transfer\n");

    fdctrl->msr |= FD_MSR_NONDMA;

    if (direction != FD_DIR_WRITE)

        fdctrl->msr |= FD_MSR_DIO;

    /* IO based transfer: calculate len */

    fdctrl_raise_irq(fdctrl);

}


int ptsname_namespace(int pty, char **ret) {
        int no = -1, r;

        /* Like ptsname(), but doesn't assume that the path is
         * accessible in the local namespace. */

        r = ioctl(pty, TIOCGPTN, &no);
        if (r < 0)
                return -errno;

        if (no < 0)
                return -EIO;

        if (asprintf(ret, "/dev/pts/%i", no) < 0)
                return -ENOMEM;

        return 0;
}


R_API void r_bin_java_print_rtip_annotations_attr_summary(RBinJavaAttrInfo *attr) {
	RBinJavaAnnotationsArray *annotation_array = NULL;
	RListIter *iter = NULL, *iter_tmp = NULL;
	if (attr && attr->type == R_BIN_JAVA_ATTR_TYPE_RUNTIME_INVISIBLE_PARAMETER_ANNOTATION_ATTR) {
		eprintf ("Runtime Invisible Parameter Annotations Attribute Information:\n");
		eprintf ("  Attribute Offset: 0x%08"PFMT64x "\n", attr->file_offset);
		eprintf ("  Attribute Name Index: %d (%s)\n", attr->name_idx, attr->name);
		eprintf ("  Attribute Length: %d\n", attr->length);
		eprintf ("  Number of Runtime Invisible Parameters: %d\n", attr->info.rtip_annotations_attr.num_parameters);
		r_list_foreach_safe (attr->info.rtip_annotations_attr.parameter_annotations, iter, iter_tmp, annotation_array) {
			r_bin_java_print_annotation_array_summary (annotation_array);
		}
	}
}


handle_queue_stats_dump_cb(uint32_t queue_id,
                           struct netdev_queue_stats *stats,
                           void *cbdata_)
{
    struct queue_stats_cbdata *cbdata = cbdata_;

    put_queue_stats(cbdata, queue_id, stats);
}


const char *avio_enum_protocols(void **opaque, int output)

{

    URLProtocol *p;

    *opaque = ffurl_protocol_next(*opaque);

    if (!(p = *opaque))

        return NULL;

    if ((output && p->url_write) || (!output && p->url_read))

        return p->name;

    return avio_enum_protocols(opaque, output);

}


static void sbr_neg_odd_64_c ( float * x ) {
 union av_intfloat32 * xi = ( union av_intfloat32 * ) x ;
 int i ;
 for ( i = 1 ;
 i < 64 ;
 i += 4 ) {
 xi [ i + 0 ] . i ^= 1U << 31 ;
 xi [ i + 2 ] . i ^= 1U << 31 ;
 }
 }


yaffs_initialize_spare_format(YAFFSFS_INFO * yfs, TSK_OFF_T maxBlocksToTest){

    // Testing parameters - can all be changed
    unsigned int blocksToTest = 10;  // Number of blocks (64 chunks) to test
    unsigned int chunksToTest = 10;  // Number of chunks to test in each block
    unsigned int minChunksRead = 10; // Minimum number of chunks we require to run the test (we might not get the full number we want to test for a very small file)

    unsigned int chunkSize = yfs->page_size + yfs->spare_size;
    unsigned int blockSize = yfs->chunks_per_block * chunkSize;

    TSK_FS_INFO *fs = &(yfs->fs_info);
    unsigned char *spareBuffer;

    unsigned int blockIndex;
    unsigned int chunkIndex;

    unsigned int currentOffset;

    unsigned char * allSpares;
    unsigned int allSparesLength;

    TSK_OFF_T maxBlocks;

    bool skipBlock;
    int goodOffset;
    unsigned int nGoodSpares;
    unsigned int nBlocksTested;

    int okOffsetFound = 0;   // Used as a flag for if we've found an offset that sort of works but doesn't seem great
    int goodOffsetFound = 0; // Flag to mark that we've found an offset that also passed secondary testing
    int bestOffset = 0;

    bool allSameByte; // Used in test that the spare area fields not be one repeated byte

    unsigned int i;

    int thisChunkBase;
    int lastChunkBase;

    // The spare area needs to be at least 16 bytes to run the test
    if(yfs->spare_size < 16){
        if(tsk_verbose && (! yfs->autoDetect)){
            tsk_fprintf(stderr,
                "yaffs_initialize_spare_format failed - given spare size (%d) is not large enough to contain needed fields\n", yfs->spare_size);
        }
        return TSK_ERR;
    }

    if ((spareBuffer = (unsigned char*) tsk_malloc(yfs->spare_size)) == NULL) {
        return TSK_ERR;
    }

    allSparesLength = yfs->spare_size * blocksToTest * chunksToTest;
    if ((allSpares = (unsigned char*) tsk_malloc(allSparesLength)) == NULL) {
        free(spareBuffer);
        return TSK_ERR;
    }

    // Initialize the pointers to one of the configurations we've seen (thought these defaults should not get used)
    yfs->spare_seq_offset = 0;
    yfs->spare_obj_id_offset = 4;
    yfs->spare_chunk_id_offset = 8;
    yfs->spare_nbytes_offset = 12;

    // Assume the data we want is 16 consecutive bytes in the order:
    //  seq num, obj id, chunk id, byte count
    //  (not sure we're guaranteed this but we wouldn't be able to deal with the alternative anyway)
    // Seq num is the important one. This number is constant in each block (block = 64 chunks), meaning
    //  all chunks in a block will share the same sequence number. The YAFFS2 descriptions would seem to
    //  indicate it should be different for each block, but this doesn't seem to always be the case.
    //  In particular we frequently see the 0x1000 seq number used over multiple blocks, but this isn't the only
    //  observed exception.

    // Calculate the number of blocks in the image
    maxBlocks = yfs->fs_info.img_info->size / (yfs->chunks_per_block * chunkSize);

    // If maxBlocksToTest = 0 (unlimited), set it to the total number of blocks
    // Also reduce the number of blocks to test if it is larger than the total number of blocks
    if ((maxBlocksToTest == 0) || (maxBlocksToTest > maxBlocks)){
        maxBlocksToTest = maxBlocks;
    }

    nGoodSpares = 0;
    nBlocksTested = 0;
    for (TSK_OFF_T blockIndex = 0;blockIndex < maxBlocksToTest;blockIndex++){

        // Read the last spare area that we want to test first
        TSK_OFF_T offset = (TSK_OFF_T)blockIndex * blockSize + (chunksToTest - 1) * chunkSize + yfs->page_size;
        ssize_t cnt = tsk_img_read(fs->img_info, offset, (char *) spareBuffer,
            yfs->spare_size);
        if ((cnt < 0) || ((unsigned int)cnt < yfs->spare_size)) {
            break;
        }

        // Is the spare all 0xff / 0x00?
        // If not, we know we should have all allocated chunks since YAFFS2 writes sequentially in a block
        //  - can't have an unallocated chunk followed by an allocated one
        // We occasionally see almost all null spare area with a few 0xff, which is not a valid spare.
        skipBlock = true;
        for (i = 0;i < yfs->spare_size;i++){
            if((spareBuffer[i] != 0xff) && (spareBuffer[i] != 0x00)){
                skipBlock = false;
                break;
            }
        }

        if (skipBlock){
            continue;
        }

        // If this block is potentialy valid (i.e., the spare contains something besides 0x00 and 0xff), copy all the spares into
        // the big array of extracted spare areas

        // Copy this spare area
        nGoodSpares++;
        for (i = 0;i < yfs->spare_size;i++){
            allSpares[nBlocksTested * yfs->spare_size * chunksToTest + (chunksToTest - 1) * yfs->spare_size + i] = spareBuffer[i];
        }

        // Copy all earlier spare areas in the block
        for (chunkIndex = 0;chunkIndex < chunksToTest - 1;chunkIndex++){
            offset = blockIndex * blockSize + chunkIndex * chunkSize + yfs->page_size;
            cnt = tsk_img_read(fs->img_info, offset, (char *) spareBuffer,
                yfs->spare_size);
            if ((cnt < 0) || ((unsigned int)cnt < yfs->spare_size)) {
                // We really shouldn't run out of data here since we already read in the furthest entry
                break; // Break out of chunksToTest loop
            }

            nGoodSpares++;
            for(i = 0;i < yfs->spare_size;i++){
                allSpares[nBlocksTested * yfs->spare_size * chunksToTest + chunkIndex * yfs->spare_size + i] = spareBuffer[i];
            }
        }

        // Record that we've found a potentially valid block
        nBlocksTested++;

        // If we've found enough potentailly valid blocks, break
        if (nBlocksTested >= blocksToTest){
            break;
        }
    }

    // Make sure we read enough data to reasonably perform the testing
    if (nGoodSpares < minChunksRead){

        if (tsk_verbose && (! yfs->autoDetect)){
            tsk_fprintf(stderr,
                "yaffs_initialize_spare_format failed - not enough potentially valid data could be read\n");
        }

        free(spareBuffer);
        free(allSpares);
        return TSK_ERR;
    }

    if (tsk_verbose && (! yfs->autoDetect)){
        tsk_fprintf(stderr,
            "yaffs_initialize_spare_format: Testing potential offsets for the sequence number in the spare area\n");
    }

    // Print out the collected spare areas if we're in verbose mode
    if(tsk_verbose && (! yfs->autoDetect)){
        for(blockIndex = 0;blockIndex < nBlocksTested;blockIndex++){
            for(chunkIndex = 0;chunkIndex < chunksToTest;chunkIndex++){
                for(i = 0;i < yfs->spare_size;i++){
                    fprintf(stderr, "%02x", allSpares[blockIndex * yfs->spare_size * chunksToTest + chunkIndex * yfs->spare_size + i]);
                }
                fprintf(stderr, "\n");
            }
        }
    }

    // Test all indices into the spare area (that leave enough space for all 16 bytes)
    for(currentOffset = 0;currentOffset <= yfs->spare_size - 16;currentOffset++){
        goodOffset = 1;
        for(blockIndex = 0;blockIndex < nBlocksTested;blockIndex++){
            for(chunkIndex = 1;chunkIndex < chunksToTest;chunkIndex++){

                lastChunkBase = blockIndex * yfs->spare_size * chunksToTest + (chunkIndex - 1) * yfs->spare_size;
                thisChunkBase = lastChunkBase + yfs->spare_size;

                // Seq num should not be all 0xff (we tested earlier that the chunk has been initialized)
                if((0xff == allSpares[thisChunkBase + currentOffset]) &&
                    (0xff == allSpares[thisChunkBase + currentOffset + 1]) &&
                    (0xff == allSpares[thisChunkBase + currentOffset + 2]) &&
                    (0xff == allSpares[thisChunkBase + currentOffset + 3])){
                        if(tsk_verbose && (! yfs->autoDetect)){
                            tsk_fprintf(stderr,
                                "yaffs_initialize_spare_format: Eliminating offset %d - invalid sequence number 0xffffffff\n",
                                currentOffset);
                        }
                        goodOffset = 0;
                        break;
                }

                // Seq num should not be zero
                if((0 == allSpares[thisChunkBase + currentOffset]) &&
                    (0 == allSpares[thisChunkBase + currentOffset + 1]) &&
                    (0 == allSpares[thisChunkBase + currentOffset + 2]) &&
                    (0 == allSpares[thisChunkBase + currentOffset + 3])){
                        if(tsk_verbose && (! yfs->autoDetect)){
                            tsk_fprintf(stderr,
                                "yaffs_initialize_spare_format: Eliminating offset %d - invalid sequence number 0\n",
                                currentOffset);
                        }
                        goodOffset = 0;
                        break;
                }

                // Seq num should match the previous one in the block
                if((allSpares[lastChunkBase + currentOffset] != allSpares[thisChunkBase + currentOffset]) ||
                    (allSpares[lastChunkBase + currentOffset + 1] != allSpares[thisChunkBase + currentOffset + 1]) ||
                    (allSpares[lastChunkBase + currentOffset + 2] != allSpares[thisChunkBase + currentOffset + 2]) ||
                    (allSpares[lastChunkBase + currentOffset + 3] != allSpares[thisChunkBase + currentOffset + 3])){
                        if(tsk_verbose && (! yfs->autoDetect)){
                            tsk_fprintf(stderr,
                                "yaffs_initialize_spare_format: Eliminating offset %d - did not match previous chunk sequence number\n",
                                currentOffset);
                        }
                        goodOffset = 0;
                        break;
                }

                // Obj id should not be zero
                if((0 == allSpares[thisChunkBase + currentOffset + 4]) &&
                    (0 == allSpares[thisChunkBase + currentOffset + 5]) &&
                    (0 == allSpares[thisChunkBase + currentOffset + 6]) &&
                    (0 == allSpares[thisChunkBase + currentOffset + 7])){
                        if(tsk_verbose && (! yfs->autoDetect)){
                            tsk_fprintf(stderr,
                                "yaffs_initialize_spare_format: Eliminating offset %d - invalid object id 0\n",
                                currentOffset);
                        }
                        goodOffset = 0;
                        break;
                }

                // All 16 bytes should not be the same
                // (It is theoretically possible that this could be valid, but incredibly unlikely)
                allSameByte = true;
                for(i = 1;i < 16;i++){
                    if(allSpares[thisChunkBase + currentOffset] != allSpares[thisChunkBase + currentOffset + i]){
                        allSameByte = false;
                        break;
                    }
                }
                if(allSameByte){
                    if(tsk_verbose && (! yfs->autoDetect)){
                        tsk_fprintf(stderr,
                            "yaffs_initialize_spare_format: Eliminating offset %d - all repeated bytes\n",
                            currentOffset);
                    }
                    goodOffset = 0;
                    break;
                }

            } // End of loop over chunks

            if(!goodOffset){ // Break out of loop over blocks
                break;
            }
        }
        if(goodOffset){

            // Note that we've found an offset that is at least promising
            if((! goodOffsetFound) && (! okOffsetFound)){
                bestOffset = currentOffset;
            }
            okOffsetFound = 1;

            if(tsk_verbose && (! yfs->autoDetect)){
                tsk_fprintf(stderr,
                    "yaffs_initialize_spare_format: Found potential spare offsets:  %d (sequence number), %d (object id), %d (chunk id), %d (n bytes)\n",
                    currentOffset, currentOffset+4, currentOffset+8, currentOffset+12);
            }

            // Now do some more tests
            // Really need some more real-world test data to do this right.
            int possibleError = 0;

            // We probably don't want the first byte to always be 0xff
            int firstByteFF = 1;
            for(blockIndex = 0;blockIndex < nBlocksTested;blockIndex++){
                for(chunkIndex = 1;chunkIndex < chunksToTest;chunkIndex++){
                    if(allSpares[blockIndex * yfs->spare_size * chunksToTest + chunkIndex * yfs->spare_size + currentOffset] != 0xff){
                        firstByteFF = 0;
                    }
                }
            }

            if(firstByteFF){
                if(tsk_verbose && (! yfs->autoDetect)){
                    tsk_fprintf(stderr,
                        "yaffs_initialize_spare_format:  Previous data starts with all 0xff bytes. Looking for better offsets.\n");
                }
                possibleError = 1;
            }

            if(! possibleError){

                // If we already have a good offset, print this one out but don't record it
                if(! goodOffsetFound){

                    goodOffsetFound = 1;
                    bestOffset = currentOffset;

                    // Offset passed additional testing and we haven't seen an earlier good one, so go ahead and use it
                    if(tsk_verbose && (! yfs->autoDetect)){
                        tsk_fprintf(stderr,
                            "yaffs_initialize_spare_format:  Previous offsets appear good - will use as final offsets\n");
                    }

                }
                else{
                    // Keep using the old one
                    if(tsk_verbose && (! yfs->autoDetect)){
                        tsk_fprintf(stderr,
                            "yaffs_initialize_spare_format:  Previous offsets appear good but staying with earlier valid ones\n");
                    }
                }
            }
        }
    }

    free(spareBuffer);
    free(allSpares);

    if(okOffsetFound || goodOffsetFound){
        // Record everything
        yfs->spare_seq_offset = bestOffset;
        yfs->spare_obj_id_offset = bestOffset + 4;
        yfs->spare_chunk_id_offset = bestOffset + 8;
        yfs->spare_nbytes_offset = bestOffset + 12;

        if(tsk_verbose && (! yfs->autoDetect)){
            tsk_fprintf(stderr,
                "yaffs_initialize_spare_format: Final offsets: %d (sequence number), %d (object id), %d (chunk id), %d (n bytes)\n",
                bestOffset, bestOffset+4, bestOffset+8, bestOffset+12);
            tsk_fprintf(stderr,
                "If these do not seem valid: %s\n", YAFFS_HELP_MESSAGE);
        }
        return TSK_OK;
    }
    else{
        return TSK_ERR;
    }
}


int flv_h263_decode_picture_header(MpegEncContext *s)

{

    int format, width, height;

    /* picture header */

    if (get_bits_long(&s->gb, 17) != 1) {

        av_log(s->avctx, AV_LOG_ERROR, "Bad picture start code\n");

        return -1;

    }

    format = get_bits(&s->gb, 5);

    if (format != 0 && format != 1) {

        av_log(s->avctx, AV_LOG_ERROR, "Bad picture format\n");

        return -1;

    }

    s->h263_flv = format+1;

    s->picture_number = get_bits(&s->gb, 8); /* picture timestamp */

    format = get_bits(&s->gb, 3);

    switch (format) {

    case 0:

        width = get_bits(&s->gb, 8);

        height = get_bits(&s->gb, 8);

        break;

    case 1:

        width = get_bits(&s->gb, 16);

        height = get_bits(&s->gb, 16);

        break;

    case 2:

        width = 352;

        height = 288;

        break;

    case 3:

        width = 176;

        height = 144;

        break;

    case 4:

        width = 128;

        height = 96;

        break;

    case 5:

        width = 320;

        height = 240;

        break;

    case 6:

        width = 160;

        height = 120;

        break;

    default:

        width = height = 0;

        break;

    }

    if ((width == 0) || (height == 0))

        return -1;

    s->width = width;

    s->height = height;

    s->pict_type = I_TYPE + get_bits(&s->gb, 2);

    if (s->pict_type > P_TYPE)

        s->pict_type = P_TYPE;

    skip_bits1(&s->gb);	/* deblocking flag */

    s->qscale = get_bits(&s->gb, 5);

    s->h263_plus = 0;

    s->unrestricted_mv = 1;

    s->h263_long_vectors = 0;

    /* PEI */

    while (get_bits1(&s->gb) != 0) {

        skip_bits(&s->gb, 8);

    }

    s->f_code = 1;

    if(s->avctx->debug & FF_DEBUG_PICT_INFO){

        av_log(s->avctx, AV_LOG_DEBUG, "%c esc_type:%d, qp:%d num:%d\n",

               av_get_pict_type_char(s->pict_type), s->h263_flv-1, s->qscale, s->picture_number);

    }

    s->y_dc_scale_table=

    s->c_dc_scale_table= ff_mpeg1_dc_scale_table;

    return 0;

}


void mbedtls_ecp_keypair_init( mbedtls_ecp_keypair *key )
{
    if( key == NULL )
        return;

    mbedtls_ecp_group_init( &key->grp );
    mbedtls_mpi_init( &key->d );
    mbedtls_ecp_point_init( &key->Q );
}


__init int net_sysctl_init(void)
{
	static struct ctl_table empty[1];
	int ret = -ENOMEM;
	/* Avoid limitations in the sysctl implementation by
	 * registering "/proc/sys/net" as an empty directory not in a
	 * network namespace.
	 */
	net_header = register_sysctl("net", empty);
	if (!net_header)
		goto out;
	ret = register_pernet_subsys(&sysctl_pernet_ops);
	if (ret)
		goto out;
	register_sysctl_root(&net_sysctl_root);
out:
	return ret;
}


void vcbprintf(
    vcbprintf_callback user_callback, //!< Unknown
    void *user_data,                  //!< Unknown
    const char *fmt,                  //!< The format specified
    va_list argp                      //!< List of parameter values
  ) {
  char buf[32];
  while (*fmt) {
    if (*fmt == '%') {
      fmt++;
      char fmtChar = *fmt++;
      switch (fmtChar) {
      case '0':
      case '1':
      case '2':
      case '3':
      case '4':
      case '5':
      case '6':
      case '7':
      case '8':
      case '9':
      {
        const char *pad = " ";
        if (fmtChar=='0') {
          pad = "0";
          fmtChar = *fmt++;
        }
        int digits = fmtChar - '0';
         // of the form '%02d'
        int v = va_arg(argp, int);
        if (*fmt=='x') itostr_extra(v, buf, false, 16);
        else { assert('d' == *fmt); itostr(v, buf, 10); }
        fmt++; // skip over 'd'
        int len = (int)strlen(buf);
        while (len < digits) {
          user_callback(pad,user_data);
          len++;
        }
        user_callback(buf,user_data);
        break;
      }
      case 'd': itostr(va_arg(argp, int), buf, 10); user_callback(buf,user_data); break;
      case 'x': itostr_extra(va_arg(argp, int), buf, false, 16); user_callback(buf,user_data); break;
      case 'L': {
        unsigned int rad = 10;
        bool signedVal = true;
        if (*fmt=='x') { rad=16; fmt++; signedVal = false; }
        itostr_extra(va_arg(argp, JsVarInt), buf, signedVal, rad); user_callback(buf,user_data);
      } break;
      case 'f': ftoa_bounded(va_arg(argp, JsVarFloat), buf, sizeof(buf)); user_callback(buf,user_data);  break;
      case 's': user_callback(va_arg(argp, char *), user_data); break;
      case 'c': buf[0]=(char)va_arg(argp, int/*char*/);buf[1]=0; user_callback(buf, user_data); break;
      case 'q':
      case 'v': {
        bool quoted = fmtChar=='q';
        if (quoted) user_callback("\"",user_data);
        JsVar *v = jsvAsString(va_arg(argp, JsVar*), false/*no unlock*/);
        buf[1] = 0;
        if (jsvIsString(v)) {
          JsvStringIterator it;
          jsvStringIteratorNew(&it, v, 0);
          // OPT: this could be faster than it is (sending whole blocks at once)
          while (jsvStringIteratorHasChar(&it)) {
            buf[0] = jsvStringIteratorGetChar(&it);
            if (quoted) {
              user_callback(escapeCharacter(buf[0]), user_data);
            } else {
              user_callback(buf,user_data);
            }
            jsvStringIteratorNext(&it);
          }
          jsvStringIteratorFree(&it);
          jsvUnLock(v);
        }
        if (quoted) user_callback("\"",user_data);
      } break;
      case 'j': {
        JsVar *v = va_arg(argp, JsVar*);
        jsfGetJSONWithCallback(v, JSON_SOME_NEWLINES | JSON_PRETTY | JSON_SHOW_DEVICES, 0, user_callback, user_data);
        break;
      }
      case 't': {
        JsVar *v = va_arg(argp, JsVar*);
        const char *n = jsvIsNull(v)?"null":jswGetBasicObjectName(v);
        if (!n) n = jsvGetTypeOf(v);
        user_callback(n, user_data);
        break;
      }
      case 'p': jshGetPinString(buf, (Pin)va_arg(argp, int/*Pin*/)); user_callback(buf, user_data); break;
      default: assert(0); return; // eep
      }
    } else {
      buf[0] = *(fmt++);
      buf[1] = 0;
      user_callback(&buf[0], user_data);
    }
  }
}


point_sub(PG_FUNCTION_ARGS)
{
	Point	   *p1 = PG_GETARG_POINT_P(0);
	Point	   *p2 = PG_GETARG_POINT_P(1);
	Point	   *result;

	result = (Point *) palloc(sizeof(Point));

	result->x = (p1->x - p2->x);
	result->y = (p1->y - p2->y);

	PG_RETURN_POINT_P(result);
}


static int aes_xts_cipher ( EVP_CIPHER_CTX * ctx , unsigned char * out , const unsigned char * in , size_t len ) {
 EVP_AES_XTS_CTX * xctx = EVP_C_DATA ( EVP_AES_XTS_CTX , ctx ) ;
 if ( ! xctx -> xts . key1 || ! xctx -> xts . key2 ) return 0 ;
 if ( ! out || ! in || len < AES_BLOCK_SIZE ) return 0 ;
 if ( xctx -> stream ) ( * xctx -> stream ) ( in , out , len , xctx -> xts . key1 , xctx -> xts . key2 , EVP_CIPHER_CTX_iv_noconst ( ctx ) ) ;
 else if ( CRYPTO_xts128_encrypt ( & xctx -> xts , EVP_CIPHER_CTX_iv_noconst ( ctx ) , in , out , len , EVP_CIPHER_CTX_encrypting ( ctx ) ) ) return 0 ;
 return 1 ;
 }


fpu__alloc_mathframe(unsigned long sp, int ia32_frame,
		     unsigned long *buf_fx, unsigned long *size)
{
	unsigned long frame_size = xstate_sigframe_size();

	*buf_fx = sp = round_down(sp - frame_size, 64);
	if (ia32_frame && use_fxsr()) {
		frame_size += sizeof(struct fregs_state);
		sp -= sizeof(struct fregs_state);
	}

	*size = frame_size;

	return sp;
}


void AppCacheUpdateJob::CancelAllMasterEntryFetches(
    const AppCacheErrorDetails& error_details) {

  for (PendingUrlFetches::iterator it = master_entry_fetches_.begin();
       it != master_entry_fetches_.end(); ++it) {
    delete it->second;
    master_entries_to_fetch_.insert(it->first);  // back in unfetched list
  }
  master_entry_fetches_.clear();

  master_entries_completed_ += master_entries_to_fetch_.size();

  HostNotifier host_notifier;
  while (!master_entries_to_fetch_.empty()) {
    const GURL& url = *master_entries_to_fetch_.begin();
    PendingMasters::iterator found = pending_master_entries_.find(url);
    DCHECK(found != pending_master_entries_.end());
    PendingHosts& hosts = found->second;
    for (PendingHosts::iterator host_it = hosts.begin();
         host_it != hosts.end(); ++host_it) {
      AppCacheHost* host = *host_it;
      host->AssociateNoCache(GURL());
      host_notifier.AddHost(host);
      host->RemoveObserver(this);
    }
    hosts.clear();

    master_entries_to_fetch_.erase(master_entries_to_fetch_.begin());
  }
  host_notifier.SendErrorNotifications(error_details);
}


static inline void gen_bx_im(DisasContext *s, uint32_t addr)

{

    TCGv tmp;

    s->is_jmp = DISAS_UPDATE;

    if (s->thumb != (addr & 1)) {

        tmp = new_tmp();

        tcg_gen_movi_i32(tmp, addr & 1);

        tcg_gen_st_i32(tmp, cpu_env, offsetof(CPUState, thumb));

        dead_tmp(tmp);

    }

    tcg_gen_movi_i32(cpu_R[15], addr & ~1);

}


static void sigcomp_cleanup_udvm ( void ) {
 g_hash_table_destroy ( state_buffer_table ) ;
 }


void i2c_register_slave(I2CSlaveInfo *info)

{

    assert(info->qdev.size >= sizeof(i2c_slave));

    info->qdev.init = i2c_slave_qdev_init;

    info->qdev.bus_type = BUS_TYPE_I2C;

    qdev_register(&info->qdev);

}


static int dissect_h245_H235Media ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_sequence ( tvb , offset , actx , tree , hf_index , ett_h245_H235Media , H235Media_sequence ) ;
 return offset ;
 }


TEST_P(Http2IntegrationTest, GoAway) {
  config_helper_.addFilter(ConfigHelper::DEFAULT_HEALTH_CHECK_FILTER);
  initialize();

  codec_client_ = makeHttpConnection(lookupPort("http"));
  auto encoder_decoder = codec_client_->startRequest(Http::TestHeaderMapImpl{
      {":method", "GET"}, {":path", "/healthcheck"}, {":scheme", "http"}, {":authority", "host"}});
  request_encoder_ = &encoder_decoder.first;
  auto response = std::move(encoder_decoder.second);
  codec_client_->goAway();
  codec_client_->sendData(*request_encoder_, 0, true);
  response->waitForEndStream();
  codec_client_->close();

  EXPECT_TRUE(response->complete());
  EXPECT_EQ("200", response->headers().Status()->value().getStringView());
}


static int ip_vs_stats_percpu_seq_open(struct inode *inode, struct file *file)
{
	return single_open_net(inode, file, ip_vs_stats_percpu_show);
}


void SessionService::WindowClosing(const SessionID& window_id) {
  if (!ShouldTrackChangesToWindow(window_id))
    return;

  if (has_open_trackable_browsers_) {
    has_open_trackable_browsers_ = HasOpenTrackableBrowsers(window_id);
  }
  if (should_record_close_as_pending())
    pending_window_close_ids_.insert(window_id.id());
  else
    window_closing_ids_.insert(window_id.id());
}


error_t icecastClientConnect(IcecastClientContext *context)
{
   error_t error;
   size_t length;
   uint16_t serverPort;
   IpAddr serverIpAddr;
   NetInterface *interface;

   //Underlying network interface
   interface = context->settings.interface;

   //Force traffic to go through a proxy server?
   if(osStrcmp(interface->proxyName, ""))
   {
      //Icecast request template
      const char_t requestTemplate[] =
         "GET http://%s:%" PRIu16 "%s HTTP/1.1\r\n"
         "Host: %s:%" PRIu16 "\r\n"
         "User-agent: UserAgent\r\n"
         "Icy-MetaData: 1\r\n"
         "Connection: close\r\n"
         "\r\n";

      //Format Icecast request
      length = osSprintf(context->buffer, requestTemplate,
         context->settings.serverName, context->settings.serverPort,
         context->settings.resource, context->settings.serverName,
         context->settings.serverPort);

      //The specified proxy server can be either an IP or a host name
      error = getHostByName(interface, interface->proxyName, &serverIpAddr, 0);
      //Unable to resolve server name?
      if(error)
         return error;

      //Proxy server port
      serverPort = interface->proxyPort;
   }
   else
   {
      //Icecast request template
      const char_t requestTemplate[] =
         "GET %s HTTP/1.1\r\n"
         "Host: %s\r\n"
         "User-agent: UserAgent\r\n"
         "Icy-MetaData: 1\r\n"
         "Connection: close\r\n"
         "\r\n";

      //Format Icecast request
      length = osSprintf(context->buffer, requestTemplate,
         context->settings.resource, context->settings.serverName);

      //The specified Icecast server can be either an IP or a host name
      error = getHostByName(interface, context->settings.serverName, &serverIpAddr, 0);
      //Unable to resolve server name?
      if(error)
         return error;

      //Icecast server port
      serverPort = context->settings.serverPort;
   }

   //Open a TCP socket
   context->socket = socketOpen(SOCKET_TYPE_STREAM, SOCKET_IP_PROTO_TCP);
   //Failed to open socket?
   if(context->socket == NULL)
      return ERROR_OUT_OF_RESOURCES;

   //Start of exception handling block
   do
   {
      //Associate the socket with the relevant interface
      error = socketBindToInterface(context->socket, interface);
      //Unable to bind the socket to the desired interface?
      if(error)
         break;

      //Adjust receive timeout
      error = socketSetTimeout(context->socket, ICECAST_CLIENT_TIMEOUT);
      //Any error to report?
      if(error)
         break;

      //Connect to the server
      error = socketConnect(context->socket, &serverIpAddr, serverPort);
      //Connection with server failed?
      if(error)
         break;

      //Display Icecast request for debugging purpose
      TRACE_DEBUG(context->buffer);

      //Send request to the server
      error = socketSend(context->socket, context->buffer,
         length, NULL, SOCKET_FLAG_WAIT_ACK);
      //Failed to send the request?
      if(error)
         break;

      //Parse response header
      while(1)
      {
         char_t *separator;
         char_t *property;
         char_t *value;

         //Read a line from the response header
         error = socketReceive(context->socket, context->buffer,
            ICECAST_CLIENT_METADATA_MAX_SIZE, &length, SOCKET_FLAG_BREAK_CRLF);
         //Failed to read data?
         if(error)
            break;

         //Properly terminate the string with a NULL character
         context->buffer[length] = '\0';

         //The end of the header has been reached?
         if(!osStrcmp(context->buffer, "\r\n"))
            break;

         //Check whether a separator is present
         separator = strchr(context->buffer, ':');

         //Separator found?
         if(separator)
         {
            //Split the line
            *separator = '\0';

            //Get property name and value
            property = strTrimWhitespace(context->buffer);
            value = strTrimWhitespace(separator + 1);

            //Debug message
            TRACE_INFO("<%s>=<%s>\r\n", property, value);

            //Icy-Metaint property found?
            if(!osStrcasecmp(property, "Icy-Metaint"))
            {
               //Retrieve the block size used by the Icecast server
               context->blockSize = atoi(value);
            }
         }
      }

      //End of exception handling block
   } while(0);

   //Check whether an error occurred
   if(error)
   {
      //Clean up side effects
      socketClose(context->socket);
   }

   //Return status code
   return error;
}


void vp9_denoiser_denoise ( VP9_DENOISER * denoiser , MACROBLOCK * mb , int mi_row , int mi_col , BLOCK_SIZE bs , PICK_MODE_CONTEXT * ctx ) {
 int motion_magnitude = 0 ;
 VP9_DENOISER_DECISION decision = FILTER_BLOCK ;
 YV12_BUFFER_CONFIG avg = denoiser -> running_avg_y [ INTRA_FRAME ] ;
 YV12_BUFFER_CONFIG mc_avg = denoiser -> mc_running_avg_y ;
 uint8_t * avg_start = block_start ( avg . y_buffer , avg . y_stride , mi_row , mi_col ) ;
 uint8_t * mc_avg_start = block_start ( mc_avg . y_buffer , mc_avg . y_stride , mi_row , mi_col ) ;
 struct buf_2d src = mb -> plane [ 0 ] . src ;
 decision = perform_motion_compensation ( denoiser , mb , bs , denoiser -> increase_denoising , mi_row , mi_col , ctx , & motion_magnitude ) ;
 if ( decision == FILTER_BLOCK ) {
 decision = denoiser_filter ( src . buf , src . stride , mc_avg_start , mc_avg . y_stride , avg_start , avg . y_stride , 0 , bs , motion_magnitude ) ;
 }
 if ( decision == FILTER_BLOCK ) {
 copy_block ( src . buf , src . stride , avg_start , avg . y_stride , bs ) ;
 }
 else {
 copy_block ( avg_start , avg . y_stride , src . buf , src . stride , bs ) ;
 }
 }


inline void Conv(const uint8* input_data, const Dims<4>& input_dims,
                 int32 input_offset, const uint8* filter_data,
                 const Dims<4>& filter_dims, int32 filter_offset,
                 const int32* bias_data, const Dims<4>& bias_dims,
                 int stride_width, int stride_height, int pad_width,
                 int pad_height, int32 output_offset, int32 output_multiplier,
                 int output_shift, int32 output_activation_min,
                 int32 output_activation_max, uint8* output_data,
                 const Dims<4>& output_dims, uint8* im2col_data,
                 const Dims<4>& im2col_dims,
                 gemmlowp::GemmContext* gemmlowp_context) {
  Conv(input_data, input_dims, input_offset, filter_data, filter_dims,
       filter_offset, bias_data, bias_dims, stride_width, stride_height, 1, 1,
       pad_width, pad_height, output_offset, output_multiplier, output_shift,
       output_activation_min, output_activation_max, output_data, output_dims,
       im2col_data, im2col_dims, gemmlowp_context);
}


static void access_with_adjusted_size(hwaddr addr,

                                      uint64_t *value,

                                      unsigned size,

                                      unsigned access_size_min,

                                      unsigned access_size_max,

                                      void (*access)(MemoryRegion *mr,

                                                     hwaddr addr,

                                                     uint64_t *value,

                                                     unsigned size,

                                                     unsigned shift,

                                                     uint64_t mask),

                                      MemoryRegion *mr)

{

    uint64_t access_mask;

    unsigned access_size;

    unsigned i;

    if (!access_size_min) {

        access_size_min = 1;

    }

    if (!access_size_max) {

        access_size_max = 4;

    }

    /* FIXME: support unaligned access? */

    access_size = MAX(MIN(size, access_size_max), access_size_min);

    access_mask = -1ULL >> (64 - access_size * 8);

    for (i = 0; i < size; i += access_size) {

#ifdef TARGET_WORDS_BIGENDIAN

        access(mr, addr + i, value, access_size,

               (size - access_size - i) * 8, access_mask);

#else

        access(mr, addr + i, value, access_size, i * 8, access_mask);

#endif

    }

}


static void activityLoggedAttrGetter2AttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
    TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
    V8PerContextData* contextData = V8PerContextData::from(info.GetIsolate()->GetCurrentContext());
    if (contextData && contextData->activityLogger())
        contextData->activityLogger()->log("TestObject.activityLoggedAttrGetter2", 0, 0, "Getter");
    TestObjectV8Internal::activityLoggedAttrGetter2AttributeGetter(info);
    TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}


decode_NXAST_RAW_OUTPUT_REG(const struct nx_action_output_reg *naor,
                            enum ofp_version ofp_version OVS_UNUSED,
                            const struct vl_mff_map *vl_mff_map,
                            uint64_t *tlv_bitmap, struct ofpbuf *out)
{
    struct ofpact_output_reg *output_reg;
    enum ofperr error;

    if (!is_all_zeros(naor->zero, sizeof naor->zero)) {
        return OFPERR_OFPBAC_BAD_ARGUMENT;
    }

    output_reg = ofpact_put_OUTPUT_REG(out);
    output_reg->ofpact.raw = NXAST_RAW_OUTPUT_REG;
    output_reg->src.ofs = nxm_decode_ofs(naor->ofs_nbits);
    output_reg->src.n_bits = nxm_decode_n_bits(naor->ofs_nbits);
    output_reg->max_len = ntohs(naor->max_len);
    error = mf_vl_mff_mf_from_nxm_header(ntohl(naor->src), vl_mff_map,
                                         &output_reg->src.field, tlv_bitmap);
    if (error) {
        return error;
    }

    return mf_check_src(&output_reg->src, NULL);
}


void cred_to_ucred(struct pid *pid, const struct cred *cred,
		   struct ucred *ucred)
{
	ucred->pid = pid_vnr(pid);
	ucred->uid = ucred->gid = -1;
	if (cred) {
		struct user_namespace *current_ns = current_user_ns();

		ucred->uid = from_kuid(current_ns, cred->euid);
		ucred->gid = from_kgid(current_ns, cred->egid);
	}
}


static bool tcp_ecn_rcv_ecn_echo(const struct tcp_sock *tp, const struct tcphdr *th)
{
	if (th->ece && !th->syn && (tp->ecn_flags & TCP_ECN_OK))
		return true;
	return false;
}


int avresample_convert(AVAudioResampleContext *avr, void **output,

                       int out_plane_size, int out_samples, void **input,

                       int in_plane_size, int in_samples)

{

    AudioData input_buffer;

    AudioData output_buffer;

    AudioData *current_buffer;

    int ret;

    /* reset internal buffers */

    if (avr->in_buffer) {

        avr->in_buffer->nb_samples = 0;

        ff_audio_data_set_channels(avr->in_buffer,

                                   avr->in_buffer->allocated_channels);

    }

    if (avr->resample_out_buffer) {

        avr->resample_out_buffer->nb_samples = 0;

        ff_audio_data_set_channels(avr->resample_out_buffer,

                                   avr->resample_out_buffer->allocated_channels);

    }

    if (avr->out_buffer) {

        avr->out_buffer->nb_samples = 0;

        ff_audio_data_set_channels(avr->out_buffer,

                                   avr->out_buffer->allocated_channels);

    }

    av_dlog(avr, "[start conversion]\n");

    /* initialize output_buffer with output data */

    if (output) {

        ret = ff_audio_data_init(&output_buffer, output, out_plane_size,

                                 avr->out_channels, out_samples,

                                 avr->out_sample_fmt, 0, "output");

        if (ret < 0)

            return ret;

        output_buffer.nb_samples = 0;

    }

    if (input) {

        /* initialize input_buffer with input data */

        ret = ff_audio_data_init(&input_buffer, input, in_plane_size,

                                 avr->in_channels, in_samples,

                                 avr->in_sample_fmt, 1, "input");

        if (ret < 0)

            return ret;

        current_buffer = &input_buffer;

        if (avr->upmix_needed && !avr->in_convert_needed && !avr->resample_needed &&

            !avr->out_convert_needed && output && out_samples >= in_samples) {

            /* in some rare cases we can copy input to output and upmix

               directly in the output buffer */

            av_dlog(avr, "[copy] %s to output\n", current_buffer->name);

            ret = ff_audio_data_copy(&output_buffer, current_buffer);

            if (ret < 0)

                return ret;

            current_buffer = &output_buffer;

        } else if (avr->mixing_needed || avr->in_convert_needed) {

            /* if needed, copy or convert input to in_buffer, and downmix if

               applicable */

            if (avr->in_convert_needed) {

                ret = ff_audio_data_realloc(avr->in_buffer,

                                            current_buffer->nb_samples);

                if (ret < 0)

                    return ret;

                av_dlog(avr, "[convert] %s to in_buffer\n", current_buffer->name);

                ret = ff_audio_convert(avr->ac_in, avr->in_buffer, current_buffer,

                                       current_buffer->nb_samples);

                if (ret < 0)

                    return ret;

            } else {

                av_dlog(avr, "[copy] %s to in_buffer\n", current_buffer->name);

                ret = ff_audio_data_copy(avr->in_buffer, current_buffer);

                if (ret < 0)

                    return ret;

            }

            ff_audio_data_set_channels(avr->in_buffer, avr->in_channels);

            if (avr->downmix_needed) {

                av_dlog(avr, "[downmix] in_buffer\n");

                ret = ff_audio_mix(avr->am, avr->in_buffer);

                if (ret < 0)

                    return ret;

            }

            current_buffer = avr->in_buffer;

        }

    } else {

        /* flush resampling buffer and/or output FIFO if input is NULL */

        if (!avr->resample_needed)

            return handle_buffered_output(avr, output ? &output_buffer : NULL,

                                          NULL);

        current_buffer = NULL;

    }

    if (avr->resample_needed) {

        AudioData *resample_out;

        int consumed = 0;

        if (!avr->out_convert_needed && output && out_samples > 0)

            resample_out = &output_buffer;

        else

            resample_out = avr->resample_out_buffer;

        av_dlog(avr, "[resample] %s to %s\n", current_buffer->name,

                resample_out->name);

        ret = ff_audio_resample(avr->resample, resample_out,

                                current_buffer, &consumed);

        if (ret < 0)

            return ret;

        /* if resampling did not produce any samples, just return 0 */

        if (resample_out->nb_samples == 0) {

            av_dlog(avr, "[end conversion]\n");

            return 0;

        }

        current_buffer = resample_out;

    }

    if (avr->upmix_needed) {

        av_dlog(avr, "[upmix] %s\n", current_buffer->name);

        ret = ff_audio_mix(avr->am, current_buffer);

        if (ret < 0)

            return ret;

    }

    /* if we resampled or upmixed directly to output, return here */

    if (current_buffer == &output_buffer) {

        av_dlog(avr, "[end conversion]\n");

        return current_buffer->nb_samples;

    }

    if (avr->out_convert_needed) {

        if (output && out_samples >= current_buffer->nb_samples) {

            /* convert directly to output */

            av_dlog(avr, "[convert] %s to output\n", current_buffer->name);

            ret = ff_audio_convert(avr->ac_out, &output_buffer, current_buffer,

                                   current_buffer->nb_samples);

            if (ret < 0)

                return ret;

            av_dlog(avr, "[end conversion]\n");

            return output_buffer.nb_samples;

        } else {

            ret = ff_audio_data_realloc(avr->out_buffer,

                                        current_buffer->nb_samples);

            if (ret < 0)

                return ret;

            av_dlog(avr, "[convert] %s to out_buffer\n", current_buffer->name);

            ret = ff_audio_convert(avr->ac_out, avr->out_buffer,

                                   current_buffer, current_buffer->nb_samples);

            if (ret < 0)

                return ret;

            current_buffer = avr->out_buffer;

        }

    }

    return handle_buffered_output(avr, &output_buffer, current_buffer);

}


void BackendImpl::DeleteBlock(Addr block_address, bool deep) {
  block_files_.DeleteBlock(block_address, deep);
}


BOOLEAN UIPC_SendBuf(tUIPC_CH_ID ch_id, BT_HDR *p_msg)
{
    UNUSED(p_msg);

    BTIF_TRACE_DEBUG("UIPC_SendBuf : ch_id %d NOT IMPLEMENTED", ch_id);

    UIPC_LOCK();

 /* currently not used */

    UIPC_UNLOCK();

 return FALSE;
}


static int device_open(AVFormatContext *ctx)

{

    struct v4l2_capability cap;

    int fd;

#if CONFIG_LIBV4L2

    int fd_libv4l;

#endif

    int res, err;

    int flags = O_RDWR;

    if (ctx->flags & AVFMT_FLAG_NONBLOCK) {

        flags |= O_NONBLOCK;

    }

    fd = v4l2_open(ctx->filename, flags, 0);

    if (fd < 0) {

        err = errno;

        av_log(ctx, AV_LOG_ERROR, "Cannot open video device %s : %s\n",

               ctx->filename, strerror(err));

        return AVERROR(err);

    }

#if CONFIG_LIBV4L2

    fd_libv4l = v4l2_fd_open(fd, 0);

    if (fd < 0) {

        err = AVERROR(errno);

        av_log(ctx, AV_LOG_ERROR, "Cannot open video device with libv4l neither %s : %s\n",

               ctx->filename, strerror(errno));

        return err;

    }

    fd = fd_libv4l;

#endif

    res = v4l2_ioctl(fd, VIDIOC_QUERYCAP, &cap);

    if (res < 0) {

        err = errno;

        av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYCAP): %s\n",

               strerror(err));

        goto fail;

    }

    av_log(ctx, AV_LOG_VERBOSE, "[%d]Capabilities: %x\n",

           fd, cap.capabilities);

    if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {

        av_log(ctx, AV_LOG_ERROR, "Not a video capture device.\n");

        err = ENODEV;

        goto fail;

    }

    if (!(cap.capabilities & V4L2_CAP_STREAMING)) {

        av_log(ctx, AV_LOG_ERROR,

               "The device does not support the streaming I/O method.\n");

        err = ENOSYS;

        goto fail;

    }

    return fd;

fail:

    v4l2_close(fd);

    return AVERROR(err);

}


static bool isCommandLineAPIGetter(const String16& name)
{
    if (name.length() != 2)
        return false;
    return name[0] == '$' && ((name[1] >= '0' && name[1] <= '4') || name[1] == '_');
}


raptor_libxml_getParameterEntity(void* user_data, const xmlChar *name) {
  raptor_sax2* sax2 = (raptor_sax2*)user_data;
  return libxml2_getParameterEntity(sax2->xc, name);
}


static int vgacon_resize(struct vc_data *c, unsigned int width,
			 unsigned int height, unsigned int user)
{
	if ((width << 1) * height > vga_vram_size)
		return -EINVAL;

	if (width % 2 || width > screen_info.orig_video_cols ||
	    height > (screen_info.orig_video_lines * vga_default_font_height)/
	    c->vc_font.height)
		/* let svgatextmode tinker with video timings and
		   return success */
		return (user) ? 0 : -EINVAL;

	if (con_is_visible(c) && !vga_is_gfx) /* who knows */
		vgacon_doresize(c, width, height);
	return 0;
}


void PlatformSensorAmbientLightMac::StopSensor() {
  light_sensor_port_.reset();
  light_sensor_notification_.reset();
  light_sensor_busy_notification_.reset();
  light_sensor_object_.reset();
  light_sensor_service_.reset();
  current_lux_ = 0.0;
}


CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem)
{
    replace_item_in_object(object, string, newitem, true);
}


l_noret luaG_tointerror (lua_State *L, const TValue *p1, const TValue *p2) {
  lua_Integer temp;
  if (!tointegerns(p1, &temp))
    p2 = p1;
  luaG_runerror(L, "number%s has no integer representation", varinfo(L, p2));
}


bool is_standardized_encoding(const String& encoding)
{
    return encoding.equals_ignoring_case(get_standardized_encoding(encoding));
}


MODCOMMAND *CSoundFile::AllocatePattern(UINT rows, UINT nchns)
{
	MODCOMMAND *p = new MODCOMMAND[rows*nchns];
	if (p) memset(p, 0, rows*nchns*sizeof(MODCOMMAND));
	return p;
}


static void sig_connect_failed ( SERVER_REC * server , gchar * msg ) {
 g_return_if_fail ( server != NULL ) ;
 if ( msg == NULL ) {
 printformat ( server , NULL , MSGLEVEL_CLIENTNOTICE , TXT_CONNECTION_LOST , server -> connrec -> address ) ;
 }
 else {
 printformat ( server , NULL , MSGLEVEL_CLIENTERROR , TXT_CANT_CONNECT , server -> connrec -> address , server -> connrec -> port , msg ) ;
 }
 }


void WebPage::notifyInRegionScrollStopped()
{
    d->notifyInRegionScrollStopped();
}


static int read_dialogue(ASSContext *ass, AVBPrint *dst, const uint8_t *p,

                         int64_t *start, int *duration)

{

    int pos;

    int64_t end;

    int hh1, mm1, ss1, ms1;

    int hh2, mm2, ss2, ms2;

    if (sscanf(p, "Dialogue: %*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d,%n",

               &hh1, &mm1, &ss1, &ms1,

               &hh2, &mm2, &ss2, &ms2, &pos) >= 8) {

        /* This is not part of the sscanf itself in order to handle an actual

         * number (which would be the Layer) or the form "Marked=N" (which is

         * the old SSA field, now replaced by Layer, and will be lead to Layer

         * being 0 here). */

        const int layer = atoi(p + 10);

        end    = (hh2*3600LL + mm2*60LL + ss2) * 100LL + ms2;

        *start = (hh1*3600LL + mm1*60LL + ss1) * 100LL + ms1;

        *duration = end - *start;

        av_bprint_clear(dst);

        av_bprintf(dst, "%u,%d,%s", ass->readorder++, layer, p + pos);

        /* right strip the buffer */

        while (dst->len > 0 &&

               dst->str[dst->len - 1] == '\r' ||

               dst->str[dst->len - 1] == '\n')

            dst->str[--dst->len] = 0;

        return 0;

    }

    return -1;

}


void ActiveStreamFilterBase::resetIdleTimer() {
  parent_.filter_manager_callbacks_.resetIdleTimer();
}


std::vector<uint8_t> WriteUpdatedTargetInfo(const std::vector<AvPair>& av_pairs,
                                            size_t updated_target_info_len) {
  bool result = true;
  NtlmBufferWriter writer(updated_target_info_len);
  for (const AvPair& pair : av_pairs) {
    result = writer.WriteAvPair(pair);
    DCHECK(result);
  }

  result = writer.WriteAvPairTerminator() && writer.IsEndOfBuffer();
  DCHECK(result);
  return writer.Pass();
}


void ChromeNetworkDelegate::OnResponseStarted(net::URLRequest* request) {
  TRACE_EVENT_ASYNC_STEP_PAST0("net", "URLRequest", request, "ResponseStarted");
  ExtensionWebRequestEventRouter::GetInstance()->OnResponseStarted(
      profile_, extension_info_map_.get(), request);
  ForwardProxyErrors(request, event_router_.get(), profile_);
}


static void clear_mi_border ( const VP9_COMMON * cm , MODE_INFO * mi ) {
 int i ;
 vpx_memset ( mi , 0 , sizeof ( * mi ) * cm -> mi_stride ) ;
 for ( i = 1 ;
 i < cm -> mi_rows + 1 ;
 ++ i ) vpx_memset ( & mi [ i * cm -> mi_stride ] , 0 , sizeof ( * mi ) ) ;
 }


void WebContentsImpl::NotifyDisconnected() {
  if (!notify_disconnection_)
    return;

  notify_disconnection_ = false;
  NotificationService::current()->Notify(
      NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
      Source<WebContents>(this),
      NotificationService::NoDetails());
}


SECURITY_STATUS SEC_ENTRY ImportSecurityContextW(SEC_WCHAR* pszPackage, PSecBuffer pPackedContext, HANDLE pToken, PCtxtHandle phContext)
{
	return SEC_E_OK;
}


static av_cold int encode_close(AVCodecContext* avc_context)

{

    TheoraContext *h = avc_context->priv_data;

    th_encode_free(h->t_state);

    av_freep(&h->stats);

    av_freep(&avc_context->coded_frame);

    av_freep(&avc_context->stats_out);

    av_freep(&avc_context->extradata);

    avc_context->extradata_size = 0;

    return 0;

}


inline void Floor(const RuntimeShape& input_shape, const float* input_data,
                  const RuntimeShape& output_shape, float* output_data) {
  ruy::profiler::ScopeLabel label("Floor");
  auto input_map = MapAsVector(input_data, input_shape);
  auto output_map = MapAsVector(output_data, output_shape);
  output_map.array() = Eigen::floor(input_map.array());
}


HTTPSession::commonEom(
    HTTPTransaction* txn,
    size_t encodedSize,
    bool piggybacked) noexcept {
  HTTPSessionBase::handleLastByteEvents(
    byteEventTracker_.get(), txn, encodedSize, sessionByteOffset(),
    piggybacked);
  onEgressMessageFinished(txn);
}


static int generic_init_net(struct net *net, u_int16_t proto)
{
	int ret;
	struct nf_generic_net *gn = generic_pernet(net);
	struct nf_proto_net *pn = &gn->pn;

	gn->timeout = nf_ct_generic_timeout;

	ret = generic_kmemdup_compat_sysctl_table(pn, gn);
	if (ret < 0)
		return ret;

	ret = generic_kmemdup_sysctl_table(pn, gn);
	if (ret < 0)
		nf_ct_kfree_compat_sysctl_table(pn);

	return ret;
}


int mod_alias_plugin_init(plugin *p) {
	p->version     = LIGHTTPD_VERSION_ID;
	p->name        = buffer_init_string("alias");

	p->init           = mod_alias_init;
	p->handle_physical= mod_alias_physical_handler;
	p->set_defaults   = mod_alias_set_defaults;
	p->cleanup        = mod_alias_free;

	p->data        = NULL;

	return 0;
}


static void replay_save_event(Event *event, int checkpoint)

{

    if (replay_mode != REPLAY_MODE_PLAY) {

        /* put the event into the file */

        replay_put_event(EVENT_ASYNC);

        replay_put_byte(checkpoint);

        replay_put_byte(event->event_kind);

        /* save event-specific data */

        switch (event->event_kind) {

        case REPLAY_ASYNC_EVENT_BH:

            replay_put_qword(event->id);

            break;

        case REPLAY_ASYNC_EVENT_INPUT:

            replay_save_input_event(event->opaque);

            break;

        case REPLAY_ASYNC_EVENT_INPUT_SYNC:

            break;

        case REPLAY_ASYNC_EVENT_CHAR_READ:

            replay_event_char_read_save(event->opaque);

            break;

        default:

            error_report("Unknown ID %d of replay event", read_event_kind);

            exit(1);

        }

    }

}


get_tabpage_arg(exarg_T *eap)
{
    int tab_number;
    int unaccept_arg0 = (eap->cmdidx == CMD_tabmove) ? 0 : 1;

    if (eap->arg && *eap->arg != NUL)
    {
	char_u *p = eap->arg;
	char_u *p_save;
	int    relative = 0; /* argument +N/-N means: go to N places to the
			      * right/left relative to the current position. */

	if (*p == '-')
	{
	    relative = -1;
	    p++;
	}
	else if (*p == '+')
	{
	    relative = 1;
	    p++;
	}

	p_save = p;
	tab_number = getdigits(&p);

	if (relative == 0)
	{
	    if (STRCMP(p, "$") == 0)
		tab_number = LAST_TAB_NR;
	    else if (p == p_save || *p_save == '-' || *p != NUL
		    || tab_number > LAST_TAB_NR)
	    {
		/* No numbers as argument. */
		eap->errmsg = e_invarg;
		goto theend;
	    }
	}
	else
	{
	    if (*p_save == NUL)
		tab_number = 1;
	    else if (p == p_save || *p_save == '-' || *p != NUL
		    || tab_number == 0)
	    {
		/* No numbers as argument. */
		eap->errmsg = e_invarg;
		goto theend;
	    }
	    tab_number = tab_number * relative + tabpage_index(curtab);
	    if (!unaccept_arg0 && relative == -1)
		--tab_number;
	}
	if (tab_number < unaccept_arg0 || tab_number > LAST_TAB_NR)
	    eap->errmsg = e_invarg;
    }
    else if (eap->addr_count > 0)
    {
	if (unaccept_arg0 && eap->line2 == 0)
	{
	    eap->errmsg = e_invrange;
	    tab_number = 0;
	}
	else
	{
	    tab_number = eap->line2;
	    if (!unaccept_arg0 && *skipwhite(*eap->cmdlinep) == '-')
	    {
		--tab_number;
		if (tab_number < unaccept_arg0)
		    eap->errmsg = e_invarg;
	    }
	}
    }
    else
    {
	switch (eap->cmdidx)
	{
	case CMD_tabnext:
	    tab_number = tabpage_index(curtab) + 1;
	    if (tab_number > LAST_TAB_NR)
		tab_number = 1;
	    break;
	case CMD_tabmove:
	    tab_number = LAST_TAB_NR;
	    break;
	default:
	    tab_number = tabpage_index(curtab);
	}
    }

theend:
    return tab_number;
}


tsize_t t2p_write_pdf_stream_end(TIFF* output){

	tsize_t written=0;

	written += t2pWriteFile(output, (tdata_t) "\nendstream\n", 11);

	return(written);
}


static BOOL update_send_scrblt(rdpContext* context, const SCRBLT_ORDER* scrblt)
{
	wStream* s;
	UINT32 offset;
	UINT32 headerLength;
	ORDER_INFO orderInfo;
	int inf;
	rdpUpdate* update = context->update;
	headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_SCRBLT);
	inf = update_approximate_scrblt_order(&orderInfo, scrblt);
	update_check_flush(context, headerLength + inf);
	s = update->us;

	if (!s)
		return TRUE;

	offset = Stream_GetPosition(s);

	if (!Stream_EnsureRemainingCapacity(s, headerLength))
		return FALSE;

	Stream_Seek(s, headerLength);
	update_write_scrblt_order(s, &orderInfo, scrblt);
	update_write_order_info(context, s, &orderInfo, offset);
	update->numberOrders++;
	return TRUE;
}


static inline void store_cpu_offset(TCGv var, int offset)

{

    tcg_gen_st_i32(var, cpu_env, offset);

    dead_tmp(var);

}


static int ext4_rename(struct inode *old_dir, struct dentry *old_dentry,
		       struct inode *new_dir, struct dentry *new_dentry)
{
	handle_t *handle;
	struct inode *old_inode, *new_inode;
	struct buffer_head *old_bh, *new_bh, *dir_bh;
	struct ext4_dir_entry_2 *old_de, *new_de;
	int retval, force_da_alloc = 0;

	dquot_initialize(old_dir);
	dquot_initialize(new_dir);

	old_bh = new_bh = dir_bh = NULL;

	/* Initialize quotas before so that eventual writes go
	 * in separate transaction */
	if (new_dentry->d_inode)
		dquot_initialize(new_dentry->d_inode);
	handle = ext4_journal_start(old_dir, 2 *
					EXT4_DATA_TRANS_BLOCKS(old_dir->i_sb) +
					EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2);
	if (IS_ERR(handle))
		return PTR_ERR(handle);

	if (IS_DIRSYNC(old_dir) || IS_DIRSYNC(new_dir))
		ext4_handle_sync(handle);

	old_bh = ext4_find_entry(old_dir, &old_dentry->d_name, &old_de);
	/*
	 *  Check for inode number is _not_ due to possible IO errors.
	 *  We might rmdir the source, keep it as pwd of some process
	 *  and merrily kill the link to whatever was created under the
	 *  same name. Goodbye sticky bit ;-<
	 */
	old_inode = old_dentry->d_inode;
	retval = -ENOENT;
	if (!old_bh || le32_to_cpu(old_de->inode) != old_inode->i_ino)
		goto end_rename;

	new_inode = new_dentry->d_inode;
	new_bh = ext4_find_entry(new_dir, &new_dentry->d_name, &new_de);
	if (new_bh) {
		if (!new_inode) {
			brelse(new_bh);
			new_bh = NULL;
		}
	}
	if (S_ISDIR(old_inode->i_mode)) {
		if (new_inode) {
			retval = -ENOTEMPTY;
			if (!empty_dir(new_inode))
				goto end_rename;
		}
		retval = -EIO;
		dir_bh = ext4_bread(handle, old_inode, 0, 0, &retval);
		if (!dir_bh)
			goto end_rename;
		if (!buffer_verified(dir_bh) &&
		    !ext4_dirent_csum_verify(old_inode,
				(struct ext4_dir_entry *)dir_bh->b_data))
			goto end_rename;
		set_buffer_verified(dir_bh);
		if (le32_to_cpu(PARENT_INO(dir_bh->b_data,
				old_dir->i_sb->s_blocksize)) != old_dir->i_ino)
			goto end_rename;
		retval = -EMLINK;
		if (!new_inode && new_dir != old_dir &&
		    EXT4_DIR_LINK_MAX(new_dir))
			goto end_rename;
		BUFFER_TRACE(dir_bh, "get_write_access");
		retval = ext4_journal_get_write_access(handle, dir_bh);
		if (retval)
			goto end_rename;
	}
	if (!new_bh) {
		retval = ext4_add_entry(handle, new_dentry, old_inode);
		if (retval)
			goto end_rename;
	} else {
		BUFFER_TRACE(new_bh, "get write access");
		retval = ext4_journal_get_write_access(handle, new_bh);
		if (retval)
			goto end_rename;
		new_de->inode = cpu_to_le32(old_inode->i_ino);
		if (EXT4_HAS_INCOMPAT_FEATURE(new_dir->i_sb,
					      EXT4_FEATURE_INCOMPAT_FILETYPE))
			new_de->file_type = old_de->file_type;
		new_dir->i_version++;
		new_dir->i_ctime = new_dir->i_mtime =
					ext4_current_time(new_dir);
		ext4_mark_inode_dirty(handle, new_dir);
		BUFFER_TRACE(new_bh, "call ext4_handle_dirty_metadata");
		retval = ext4_handle_dirty_dirent_node(handle, new_dir, new_bh);
		if (unlikely(retval)) {
			ext4_std_error(new_dir->i_sb, retval);
			goto end_rename;
		}
		brelse(new_bh);
		new_bh = NULL;
	}

	/*
	 * Like most other Unix systems, set the ctime for inodes on a
	 * rename.
	 */
	old_inode->i_ctime = ext4_current_time(old_inode);
	ext4_mark_inode_dirty(handle, old_inode);

	/*
	 * ok, that's it
	 */
	if (le32_to_cpu(old_de->inode) != old_inode->i_ino ||
	    old_de->name_len != old_dentry->d_name.len ||
	    strncmp(old_de->name, old_dentry->d_name.name, old_de->name_len) ||
	    (retval = ext4_delete_entry(handle, old_dir,
					old_de, old_bh)) == -ENOENT) {
		/* old_de could have moved from under us during htree split, so
		 * make sure that we are deleting the right entry.  We might
		 * also be pointing to a stale entry in the unused part of
		 * old_bh so just checking inum and the name isn't enough. */
		struct buffer_head *old_bh2;
		struct ext4_dir_entry_2 *old_de2;

		old_bh2 = ext4_find_entry(old_dir, &old_dentry->d_name, &old_de2);
		if (old_bh2) {
			retval = ext4_delete_entry(handle, old_dir,
						   old_de2, old_bh2);
			brelse(old_bh2);
		}
	}
	if (retval) {
		ext4_warning(old_dir->i_sb,
				"Deleting old file (%lu), %d, error=%d",
				old_dir->i_ino, old_dir->i_nlink, retval);
	}

	if (new_inode) {
		ext4_dec_count(handle, new_inode);
		new_inode->i_ctime = ext4_current_time(new_inode);
	}
	old_dir->i_ctime = old_dir->i_mtime = ext4_current_time(old_dir);
	ext4_update_dx_flag(old_dir);
	if (dir_bh) {
		PARENT_INO(dir_bh->b_data, new_dir->i_sb->s_blocksize) =
						cpu_to_le32(new_dir->i_ino);
		BUFFER_TRACE(dir_bh, "call ext4_handle_dirty_metadata");
		if (is_dx(old_inode)) {
			retval = ext4_handle_dirty_dx_node(handle,
							   old_inode,
							   dir_bh);
		} else {
			retval = ext4_handle_dirty_dirent_node(handle,
							       old_inode,
							       dir_bh);
		}
		if (retval) {
			ext4_std_error(old_dir->i_sb, retval);
			goto end_rename;
		}
		ext4_dec_count(handle, old_dir);
		if (new_inode) {
			/* checked empty_dir above, can't have another parent,
			 * ext4_dec_count() won't work for many-linked dirs */
			clear_nlink(new_inode);
		} else {
			ext4_inc_count(handle, new_dir);
			ext4_update_dx_flag(new_dir);
			ext4_mark_inode_dirty(handle, new_dir);
		}
	}
	ext4_mark_inode_dirty(handle, old_dir);
	if (new_inode) {
		ext4_mark_inode_dirty(handle, new_inode);
		if (!new_inode->i_nlink)
			ext4_orphan_add(handle, new_inode);
		if (!test_opt(new_dir->i_sb, NO_AUTO_DA_ALLOC))
			force_da_alloc = 1;
	}
	retval = 0;

end_rename:
	brelse(dir_bh);
	brelse(old_bh);
	brelse(new_bh);
	ext4_journal_stop(handle);
	if (retval == 0 && force_da_alloc)
		ext4_alloc_da_blocks(old_inode);
	return retval;
}


static int hexval(int c)
{
    if (c >= 'A' && c <= 'F')
        return c - 'A' + 10;
    else if (c >= 'a' && c <= 'f')
        return c - 'a' + 10;
    else if (c >= '0' && c <= '9')
        return c - '0';
    else
        return -1;
}


block_crypto_open_opts_init(QCryptoBlockFormat format,

                            QemuOpts *opts,

                            Error **errp)

{

    Visitor *v;

    QCryptoBlockOpenOptions *ret = NULL;

    Error *local_err = NULL;

    ret = g_new0(QCryptoBlockOpenOptions, 1);

    ret->format = format;

    v = opts_visitor_new(opts);

    visit_start_struct(v, NULL, NULL, 0, &local_err);

    if (local_err) {

        goto out;

    }

    switch (format) {

    case Q_CRYPTO_BLOCK_FORMAT_LUKS:

        visit_type_QCryptoBlockOptionsLUKS_members(

            v, &ret->u.luks, &local_err);

        break;

    default:

        error_setg(&local_err, "Unsupported block format %d", format);

        break;

    }

    if (!local_err) {

        visit_check_struct(v, &local_err);

    }

    visit_end_struct(v, NULL);

 out:

    if (local_err) {

        error_propagate(errp, local_err);

        qapi_free_QCryptoBlockOpenOptions(ret);

        ret = NULL;

    }

    visit_free(v);

    return ret;

}


static inline __u32 cookie_init_sequence(const struct tcp_request_sock_ops *ops,
					 const struct sock *sk, struct sk_buff *skb,
					 __u16 *mss)
{
	tcp_synq_overflow(sk);
	__NET_INC_STATS(sock_net(sk), LINUX_MIB_SYNCOOKIESSENT);
	return ops->cookie_init_seq(skb, mss);
}


const char* CMSEXPORT cmsIT8GetPropertyMulti(cmsHANDLE hIT8, const char* Key, const char *SubKey)
{
    cmsIT8* it8 = (cmsIT8*) hIT8;
    KEYVALUE* p;

    if (IsAvailableOnList(GetTable(it8) -> HeaderList, Key, SubKey, &p)) {
        return p -> Value;
    }
    return NULL;
}


ServerConnectionImpl::ServerConnectionImpl(Network::Connection& connection, Stats::Scope& stats,
                                           ServerConnectionCallbacks& callbacks,
                                           Http1Settings settings, uint32_t max_request_headers_kb)
    : ConnectionImpl(connection, stats, HTTP_REQUEST, max_request_headers_kb),
      callbacks_(callbacks), codec_settings_(settings) {}


static void ne2000_instance_init(Object *obj)
{
    PCIDevice *pci_dev = PCI_DEVICE(obj);
    PCINE2000State *d = DO_UPCAST(PCINE2000State, dev, pci_dev);
    NE2000State *s = &d->ne2000;

    device_add_bootindex_property(obj, &s->c.bootindex,
                                  "bootindex", "/ethernet-phy@0",
                                  &pci_dev->qdev, NULL);
}


void vncProperties::LoadFromIniFile()
{
	//if (m_dlgvisible)
	//{
	//	vnclog.Print(LL_INTWARN, VNCLOG("service helper invoked while Properties panel displayed\n"));
	//	return;
	//}

	char username[UNLEN+1];

	// Get the user name / service name
	if (!vncService::CurrentUser((char *)&username, sizeof(username)))
	{
		vnclog.Print(LL_INTINFO, VNCLOG("***** DBG - NO current user\n"));
		return;
	}

	// If there is no user logged on them default to SYSTEM
	if (strcmp(username, "") == 0)
	{
		//vnclog.Print(LL_INTINFO, VNCLOG("***** DBG - Force USER SYSTEM 2\n"));
		strcpy_s((char *)&username, UNLEN+1, "SYSTEM");
	}

	// Logging/debugging prefs
	vnclog.SetMode(myIniFile.ReadInt("admin", "DebugMode", 0));
	char temp[512];
	myIniFile.ReadString("admin", "path", temp,512);
	vnclog.SetPath(temp);
	vnclog.SetLevel(myIniFile.ReadInt("admin", "DebugLevel", 0));
	vnclog.SetVideo(myIniFile.ReadInt("admin", "Avilog", 0) ? true : false);

	// Disable Tray Icon
	m_server->SetDisableTrayIcon(myIniFile.ReadInt("admin", "DisableTrayIcon", false));
	m_server->SetRdpmode(myIniFile.ReadInt("admin", "rdpmode", 0));
	m_server->SetNoScreensaver(myIniFile.ReadInt("admin", "noscreensaver", 0));

	// Authentication required, loopback allowed, loopbackOnly

	m_server->SetLoopbackOnly(myIniFile.ReadInt("admin", "LoopbackOnly", false));

	m_pref_Secure = false;
	m_pref_Secure = myIniFile.ReadInt("admin", "Secure", m_pref_Secure);
	m_server->Secure(m_pref_Secure);

	m_pref_RequireMSLogon=false;
	m_pref_RequireMSLogon = myIniFile.ReadInt("admin", "MSLogonRequired", m_pref_RequireMSLogon);
	m_server->RequireMSLogon(m_pref_RequireMSLogon);

	// Marscha@2004 - authSSP: added NewMSLogon checkbox to admin props page
	m_pref_NewMSLogon = false;
	m_pref_NewMSLogon = myIniFile.ReadInt("admin", "NewMSLogon", m_pref_NewMSLogon);
	m_server->SetNewMSLogon(m_pref_NewMSLogon);

	// sf@2003 - Moved DSM params here
	m_pref_UseDSMPlugin=false;
	m_pref_UseDSMPlugin = myIniFile.ReadInt("admin", "UseDSMPlugin", m_pref_UseDSMPlugin);
	myIniFile.ReadString("admin", "DSMPlugin",m_pref_szDSMPlugin,128);

	m_pref_ReverseAuthRequired = true;
	m_pref_ReverseAuthRequired = myIniFile.ReadInt("admin", "ReverseAuthRequired", m_pref_ReverseAuthRequired);
	m_server->SetReverseAuthRequired(m_pref_ReverseAuthRequired);

	//adzm 2010-05-12 - dsmplugin config
	myIniFile.ReadString("admin", "DSMPluginConfig", m_pref_DSMPluginConfig, 512);
#ifdef IPV6V4
	m_server->SetIPV6(myIniFile.ReadInt("admin", "UseIpv6", false));
#endif
	if (m_server->LoopbackOnly()) m_server->SetLoopbackOk(true);
	else m_server->SetLoopbackOk(myIniFile.ReadInt("admin", "AllowLoopback", true));
	m_server->SetAuthRequired(myIniFile.ReadInt("admin", "AuthRequired", true));

	m_server->SetConnectPriority(myIniFile.ReadInt("admin", "ConnectPriority", 0));
	if (!m_server->LoopbackOnly())
	{
		char *authhosts=new char[150];
		myIniFile.ReadString("admin", "AuthHosts",authhosts,150);
		if (authhosts != 0) {
			m_server->SetAuthHosts(authhosts);
			delete [] authhosts;
		} else {
			m_server->SetAuthHosts(0);
		}
	} else {
		m_server->SetAuthHosts(0);
	}

	//vnclog.Print(LL_INTINFO, VNCLOG("***** DBG - Load User Preferences\n"));

	// Set the default user prefs
	vnclog.Print(LL_INTINFO, VNCLOG("clearing user settings\n"));
	m_pref_AutoPortSelect=TRUE;
    m_pref_HTTPConnect = TRUE;
	m_pref_PortNumber = RFB_PORT_OFFSET;
	m_pref_SockConnect=TRUE;
	{
	    vncPasswd::FromClear crypt(m_pref_Secure);
	    memcpy(m_pref_passwd, crypt, MAXPWLEN);
	}
	m_pref_QuerySetting=2;
	m_pref_QueryTimeout=10;
	m_pref_QueryDisableTime=0;
	m_pref_QueryAccept=0;
	m_pref_IdleTimeout=0;
	m_pref_MaxViewerSetting = 0;
	m_pref_MaxViewers = 128;
	m_pref_EnableRemoteInputs=TRUE;
	m_pref_DisableLocalInputs=FALSE;
	m_pref_EnableJapInput=FALSE;
	m_pref_EnableUnicodeInput=FALSE;
	m_pref_EnableWin8Helper=FALSE;
	m_pref_clearconsole=FALSE;
	m_pref_LockSettings=-1;
	m_pref_Collabo=false;

	m_pref_Frame = FALSE;
	m_pref_Notification = FALSE;
	m_pref_OSD = FALSE;
	m_pref_NotificationSelection = 0;

	m_pref_RemoveWallpaper=FALSE;
	// adzm - 2010-07 - Disable more effects or font smoothing
	m_pref_RemoveEffects=FALSE;
	m_pref_RemoveFontSmoothing=FALSE;
    m_alloweditclients = TRUE;
	m_allowshutdown = TRUE;
	m_allowproperties = TRUE;
	m_allowInjection = FALSE;

	// Modif sf@2002
	m_pref_SingleWindow = FALSE;
	m_pref_UseDSMPlugin = FALSE;
	*m_pref_szDSMPlugin = '\0';
	m_pref_DSMPluginConfig[0] = '\0';

	m_pref_EnableFileTransfer = TRUE;
	m_pref_FTUserImpersonation = TRUE;
	m_pref_EnableBlankMonitor = TRUE;
	m_pref_BlankInputsOnly = FALSE;
	m_pref_QueryIfNoLogon = FALSE;
	m_pref_DefaultScale = 1;

	LoadUserPrefsFromIniFile();
	m_allowshutdown = myIniFile.ReadInt("admin", "AllowShutdown", m_allowshutdown);
	m_allowproperties = myIniFile.ReadInt("admin", "AllowProperties", m_allowproperties);
	m_allowInjection = myIniFile.ReadInt("admin", "AllowInjection", m_allowInjection);
	m_alloweditclients = myIniFile.ReadInt("admin", "AllowEditClients", m_alloweditclients);

    m_ftTimeout = myIniFile.ReadInt("admin", "FileTransferTimeout", m_ftTimeout);
    if (m_ftTimeout > 600)
        m_ftTimeout = 600;

    m_keepAliveInterval = myIniFile.ReadInt("admin", "KeepAliveInterval", m_keepAliveInterval);
	m_IdleInputTimeout = myIniFile.ReadInt("admin", "IdleInputTimeout", m_IdleInputTimeout);

    if (m_keepAliveInterval >= (m_ftTimeout - KEEPALIVE_HEADROOM))
        m_keepAliveInterval = m_ftTimeout - KEEPALIVE_HEADROOM;

    m_server->SetFTTimeout(m_ftTimeout);
    m_server->SetKeepAliveInterval(m_keepAliveInterval);
	m_server->SetIdleInputTimeout(m_IdleInputTimeout);

	myIniFile.ReadString("admin", "service_commandline", service_commandline, 1024);
	myIniFile.ReadString("admin", "accept_reject_mesg", accept_reject_mesg, 512);

	ApplyUserPrefs();
}


    template<typename t>
    CImgList<T>& operator,(const CImgList<t>& list) const {
      return (+*this).insert(list);


static inline int crypto_set_driver_name(struct crypto_alg *alg)
{
	static const char suffix[] = "-generic";
	char *driver_name = alg->cra_driver_name;
	int len;

	if (*driver_name)
		return 0;

	len = strlcpy(driver_name, alg->cra_name, CRYPTO_MAX_ALG_NAME);
	if (len + sizeof(suffix) > CRYPTO_MAX_ALG_NAME)
		return -ENAMETOOLONG;

	memcpy(driver_name + len, suffix, sizeof(suffix));
	return 0;
}


 */
static void php_wddx_serialize_array(wddx_packet *packet, zval *arr)
{
	zval **ent;
	char *key;
	uint key_len;
	int is_struct = 0, ent_type;
	ulong idx;
	HashTable *target_hash;
	char tmp_buf[WDDX_BUF_LEN];
	ulong ind = 0;
	int type;
	TSRMLS_FETCH();

	target_hash = HASH_OF(arr);

	for (zend_hash_internal_pointer_reset(target_hash);
		 zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS;
		 zend_hash_move_forward(target_hash)) {

		type = zend_hash_get_current_key(target_hash, &key, &idx, 0);

		if (type == HASH_KEY_IS_STRING) {
			is_struct = 1;
			break;
		}

		if (idx != ind) {
			is_struct = 1;
			break;
		}

		ind++;
	}

	if (is_struct) {
		php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
	} else {
		snprintf(tmp_buf, sizeof(tmp_buf), WDDX_ARRAY_S, zend_hash_num_elements(target_hash));
		php_wddx_add_chunk(packet, tmp_buf);
	}

	for (zend_hash_internal_pointer_reset(target_hash);
		 zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS;
		 zend_hash_move_forward(target_hash)) {
		if (*ent == arr) {
			continue;
		}

		if (is_struct) {
			ent_type = zend_hash_get_current_key_ex(target_hash, &key, &key_len, &idx, 0, NULL);

			if (ent_type == HASH_KEY_IS_STRING) {
				php_wddx_serialize_var(packet, *ent, key, key_len TSRMLS_CC);
			} else {
				key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx);
				php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC);
			}
		} else {
			php_wddx_serialize_var(packet, *ent, NULL, 0 TSRMLS_CC);
		}
	}

	if (is_struct) {
		php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
	} else {
		php_wddx_add_chunk_static(packet, WDDX_ARRAY_E);
	}


static void voidMethodTreatNullAsNullStringTreatUndefinedAsNullStringStringArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    if (UNLIKELY(info.Length() < 1)) {
        throwTypeError(ExceptionMessages::failedToExecute("voidMethodTreatNullAsNullStringTreatUndefinedAsNullStringStringArg", "TestObjectPython", ExceptionMessages::notEnoughArguments(1, info.Length())), info.GetIsolate());
        return;
    }
    TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder());
    V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<WithUndefinedOrNullCheck>, treatNullAsNullStringStringArg, info[0]);
    imp->voidMethodTreatNullAsNullStringTreatUndefinedAsNullStringStringArg(treatNullAsNullStringStringArg);
}


static int get_dev_to_use(struct spk_synth *synth, dev_t *dev_no)
{
	/* use ser only when dev is not specified */
	if (strcmp(synth->dev_name, SYNTH_DEFAULT_DEV) ||
	    synth->ser == SYNTH_DEFAULT_SER)
		return tty_dev_name_to_number(synth->dev_name, dev_no);

	return ser_to_dev(synth->ser, dev_no);
}


static int sbr_make_f_derived ( AACContext * ac , SpectralBandReplication * sbr ) {
 int k , temp ;
 sbr -> n [ 1 ] = sbr -> n_master - sbr -> spectrum_params . bs_xover_band ;
 sbr -> n [ 0 ] = ( sbr -> n [ 1 ] + 1 ) >> 1 ;
 memcpy ( sbr -> f_tablehigh , & sbr -> f_master [ sbr -> spectrum_params . bs_xover_band ] , ( sbr -> n [ 1 ] + 1 ) * sizeof ( sbr -> f_master [ 0 ] ) ) ;
 sbr -> m [ 1 ] = sbr -> f_tablehigh [ sbr -> n [ 1 ] ] - sbr -> f_tablehigh [ 0 ] ;
 sbr -> kx [ 1 ] = sbr -> f_tablehigh [ 0 ] ;
 if ( sbr -> kx [ 1 ] + sbr -> m [ 1 ] > 64 ) {
 av_log ( ac -> avctx , AV_LOG_ERROR , "Stop frequency border too high: %d\n" , sbr -> kx [ 1 ] + sbr -> m [ 1 ] ) ;
 return - 1 ;
 }
 if ( sbr -> kx [ 1 ] > 32 ) {
 av_log ( ac -> avctx , AV_LOG_ERROR , "Start frequency border too high: %d\n" , sbr -> kx [ 1 ] ) ;
 return - 1 ;
 }
 sbr -> f_tablelow [ 0 ] = sbr -> f_tablehigh [ 0 ] ;
 temp = sbr -> n [ 1 ] & 1 ;
 for ( k = 1 ;
 k <= sbr -> n [ 0 ] ;
 k ++ ) sbr -> f_tablelow [ k ] = sbr -> f_tablehigh [ 2 * k - temp ] ;
 sbr -> n_q = FFMAX ( 1 , lrintf ( sbr -> spectrum_params . bs_noise_bands * log2f ( sbr -> k [ 2 ] / ( float ) sbr -> kx [ 1 ] ) ) ) ;
 if ( sbr -> n_q > 5 ) {
 av_log ( ac -> avctx , AV_LOG_ERROR , "Too many noise floor scale factors: %d\n" , sbr -> n_q ) ;
 return - 1 ;
 }
 sbr -> f_tablenoise [ 0 ] = sbr -> f_tablelow [ 0 ] ;
 temp = 0 ;
 for ( k = 1 ;
 k <= sbr -> n_q ;
 k ++ ) {
 temp += ( sbr -> n [ 0 ] - temp ) / ( sbr -> n_q + 1 - k ) ;
 sbr -> f_tablenoise [ k ] = sbr -> f_tablelow [ temp ] ;
 }
 if ( sbr_hf_calc_npatches ( ac , sbr ) < 0 ) return - 1 ;
 sbr_make_f_tablelim ( sbr ) ;
 sbr -> data [ 0 ] . f_indexnoise = 0 ;
 sbr -> data [ 1 ] . f_indexnoise = 0 ;
 return 0 ;
 }


static int crypto_ablkcipher_report(struct sk_buff *skb, struct crypto_alg *alg)
{
	struct crypto_report_blkcipher rblkcipher;

	snprintf(rblkcipher.type, CRYPTO_MAX_ALG_NAME, "%s", "ablkcipher");
	snprintf(rblkcipher.geniv, CRYPTO_MAX_ALG_NAME, "%s",
		 alg->cra_ablkcipher.geniv ?: "<default>");

	rblkcipher.blocksize = alg->cra_blocksize;
	rblkcipher.min_keysize = alg->cra_ablkcipher.min_keysize;
	rblkcipher.max_keysize = alg->cra_ablkcipher.max_keysize;
	rblkcipher.ivsize = alg->cra_ablkcipher.ivsize;

	if (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER,
		    sizeof(struct crypto_report_blkcipher), &rblkcipher))
		goto nla_put_failure;
	return 0;

nla_put_failure:
	return -EMSGSIZE;
}


void semaphore_post(semaphore_t *semaphore) {
  assert(semaphore != NULL);
  assert(semaphore->fd != INVALID_FD);

 if (eventfd_write(semaphore->fd, 1ULL) == -1)
    LOG_ERROR("%s unable to post to semaphore: %s", __func__, strerror(errno));
}


bool SupervisedUserService::ProfileIsSupervised() const {
  return profile_->IsSupervised();
}


   void Reset() {
     error_nframes_ = 0;
     droppable_nframes_ = 0;
   }


  void Config::assign(const Config * other) {
    *this = *(const Config *)(other);
  }


void StartupBrowserCreator::ProcessCommandLineOnProfileCreated(
    const base::CommandLine& command_line,
    const base::FilePath& cur_dir,
    Profile* profile,
    Profile::CreateStatus status) {
  if (status != Profile::CREATE_STATUS_INITIALIZED)
    return;
  StartupBrowserCreator startup_browser_creator;
  startup_browser_creator.ProcessCmdLineImpl(command_line, cur_dir, false,
                                             profile, Profiles());
}


  void TestDidNavigate(int page_id, const GURL& url) {
    ViewHostMsg_FrameNavigate_Params params;
    InitNavigateParams(&params, page_id, url, content::PAGE_TRANSITION_TYPED);
    DidNavigate(GetRenderViewHostForTesting(), params);
  }