void genericcostestimate ( PlannerInfo * root , IndexPath * path , double loop_count , List * qinfos , GenericCosts * costs ) {
 IndexOptInfo * index = path -> indexinfo ;
 List * indexQuals = path -> indexquals ;
 List * indexOrderBys = path -> indexorderbys ;
 Cost indexStartupCost ;
 Cost indexTotalCost ;
 Selectivity indexSelectivity ;
 double indexCorrelation ;
 double numIndexPages ;
 double numIndexTuples ;
 double spc_random_page_cost ;
 double num_sa_scans ;
 double num_outer_scans ;
 double num_scans ;
 double qual_op_cost ;
 double qual_arg_cost ;
 List * selectivityQuals ;
 ListCell * l ;
 selectivityQuals = add_predicate_to_quals ( index , indexQuals ) ;
 num_sa_scans = 1 ;
 foreach ( l , indexQuals ) {
 RestrictInfo * rinfo = ( RestrictInfo * ) lfirst ( l ) ;
 if ( IsA ( rinfo -> clause , ScalarArrayOpExpr ) ) {
 ScalarArrayOpExpr * saop = ( ScalarArrayOpExpr * ) rinfo -> clause ;
 int alength = estimate_array_length ( lsecond ( saop -> args ) ) ;
 if ( alength > 1 ) num_sa_scans *= alength ;
 }
 }
 indexSelectivity = clauselist_selectivity ( root , selectivityQuals , index -> rel -> relid , JOIN_INNER , NULL ) ;
 numIndexTuples = costs -> numIndexTuples ;
 if ( numIndexTuples <= 0.0 ) {
 numIndexTuples = indexSelectivity * index -> rel -> tuples ;
 numIndexTuples = rint ( numIndexTuples / num_sa_scans ) ;
 }
 if ( numIndexTuples > index -> tuples ) numIndexTuples = index -> tuples ;
 if ( numIndexTuples < 1.0 ) numIndexTuples = 1.0 ;
 if ( index -> pages > 1 && index -> tuples > 1 ) numIndexPages = ceil ( numIndexTuples * index -> pages / index -> tuples ) ;
 else numIndexPages = 1.0 ;
 get_tablespace_page_costs ( index -> reltablespace , & spc_random_page_cost , NULL ) ;
 num_outer_scans = loop_count ;
 num_scans = num_sa_scans * num_outer_scans ;
 if ( num_scans > 1 ) {
 double pages_fetched ;
 pages_fetched = numIndexPages * num_scans ;
 pages_fetched = index_pages_fetched ( pages_fetched , index -> pages , ( double ) index -> pages , root ) ;
 indexTotalCost = ( pages_fetched * spc_random_page_cost ) / num_outer_scans ;
 }
 else {
 indexTotalCost = numIndexPages * spc_random_page_cost ;
 }
 qual_arg_cost = other_operands_eval_cost ( root , qinfos ) + orderby_operands_eval_cost ( root , path ) ;
 qual_op_cost = cpu_operator_cost * ( list_length ( indexQuals ) + list_length ( indexOrderBys ) ) ;
 indexStartupCost = qual_arg_cost ;
 indexTotalCost += qual_arg_cost ;
 indexTotalCost += numIndexTuples * num_sa_scans * ( cpu_index_tuple_cost + qual_op_cost ) ;
 indexCorrelation = 0.0 ;
 costs -> indexStartupCost = indexStartupCost ;
 costs -> indexTotalCost = indexTotalCost ;
 costs -> indexSelectivity = indexSelectivity ;
 costs -> indexCorrelation = indexCorrelation ;
 costs -> numIndexPages = numIndexPages ;
 costs -> numIndexTuples = numIndexTuples ;
 costs -> spc_random_page_cost = spc_random_page_cost ;
 costs -> num_sa_scans = num_sa_scans ;
 }


syncable::ModelTypeSet MakeSet(syncable::ModelType type) {
  return syncable::ModelTypeSet(type);
}


static bool btif_av_state_started_handler(btif_sm_event_t event, void* p_data) {
  tBTA_AV* p_av = (tBTA_AV*)p_data;

  BTIF_TRACE_DEBUG("%s: event=%s flags=0x%x", __func__,
                   dump_av_sm_event_name((btif_av_sm_event_t)event),
                   btif_av_cb.flags);

 switch (event) {
 case BTIF_SM_ENTER_EVT:

 /* we are again in started state, clear any remote suspend flags */
      btif_av_cb.flags &= ~BTIF_AV_FLAG_REMOTE_SUSPEND;

 /**
       * Report to components above that we have entered the streaming
       * stage, this should usually be followed by focus grant.
       * see update_audio_focus_state()
       */
      btif_report_audio_state(BTAV_AUDIO_STATE_STARTED, &(btif_av_cb.peer_bda));
 break;

 case BTIF_SM_EXIT_EVT:
 break;

 case BTIF_AV_START_STREAM_REQ_EVT:
 /* we were remotely started, just ack back the local request */
 if (btif_av_cb.peer_sep == AVDT_TSEP_SNK)
        btif_a2dp_on_started(NULL, true);
 break;

 case BTIF_AV_SOURCE_CONFIG_REQ_EVT:
      btif_update_source_codec(p_data);
 break;

 case BTIF_AV_SOURCE_CONFIG_UPDATED_EVT:
      btif_report_source_codec_state(p_data);
 break;

 /* fixme -- use suspend = true always to work around issue with BTA AV */
 case BTIF_AV_STOP_STREAM_REQ_EVT:
 case BTIF_AV_SUSPEND_STREAM_REQ_EVT:
      BTIF_TRACE_WARNING("%s: event=%s flags=0x%x", __func__,
                         dump_av_sm_event_name((btif_av_sm_event_t)event),
                         btif_av_cb.flags);
 /* set pending flag to ensure btif task is not trying to restart
         stream while suspend is in progress */
      btif_av_cb.flags |= BTIF_AV_FLAG_LOCAL_SUSPEND_PENDING;

 /* if we were remotely suspended but suspend locally, local suspend
         always overrides */
      btif_av_cb.flags &= ~BTIF_AV_FLAG_REMOTE_SUSPEND;

 if (btif_av_cb.peer_sep == AVDT_TSEP_SNK) {
 /*
         * Immediately stop transmission of frames while suspend is
         * pending.
         */
        btif_a2dp_source_set_tx_flush(true);
 }

 if (btif_av_cb.peer_sep == AVDT_TSEP_SRC) {
        btif_a2dp_on_stopped(NULL);
 }

      BTA_AvStop(true);
 break;

 case BTIF_AV_DISCONNECT_REQ_EVT:
      BTIF_TRACE_WARNING("%s: event=%s flags=0x%x", __func__,
                         dump_av_sm_event_name((btif_av_sm_event_t)event),
                         btif_av_cb.flags);

 /* request avdtp to close */
      BTA_AvClose(btif_av_cb.bta_handle);
 if (btif_av_cb.peer_sep == AVDT_TSEP_SRC) {
        BTA_AvCloseRc(btif_av_cb.bta_handle);
 }

 /* inform the application that we are disconnecting */
      btif_report_connection_state(BTAV_CONNECTION_STATE_DISCONNECTING,
 &(btif_av_cb.peer_bda));

 /* wait in closing state until fully closed */
      btif_sm_change_state(btif_av_cb.sm_handle, BTIF_AV_STATE_CLOSING);
 break;

 case BTA_AV_SUSPEND_EVT:
      BTIF_TRACE_WARNING(
 "%s: BTA_AV_SUSPEND_EVT status=%d initiator=%d flags=0x%x", __func__,
          p_av->suspend.status, p_av->suspend.initiator, btif_av_cb.flags);

 /* a2dp suspended, stop media task until resumed */
      btif_a2dp_on_suspended(&p_av->suspend);

 /* if not successful, remain in current state */
 if (p_av->suspend.status != BTA_AV_SUCCESS) {
        btif_av_cb.flags &= ~BTIF_AV_FLAG_LOCAL_SUSPEND_PENDING;

 if (btif_av_cb.peer_sep == AVDT_TSEP_SNK) {
 /* suspend failed, reset back tx flush state */
          btif_a2dp_source_set_tx_flush(false);
 }
 return false;
 }

 if (p_av->suspend.initiator != true) {
 /* remote suspend, notify HAL and await audioflinger to
           suspend/stop stream */

 /* set remote suspend flag to block media task from restarting
           stream only if we did not already initiate a local suspend */
 if ((btif_av_cb.flags & BTIF_AV_FLAG_LOCAL_SUSPEND_PENDING) == 0)
          btif_av_cb.flags |= BTIF_AV_FLAG_REMOTE_SUSPEND;

        btif_report_audio_state(BTAV_AUDIO_STATE_REMOTE_SUSPEND,
 &(btif_av_cb.peer_bda));
 } else {
        btif_report_audio_state(BTAV_AUDIO_STATE_STOPPED,
 &(btif_av_cb.peer_bda));
 }

      btif_sm_change_state(btif_av_cb.sm_handle, BTIF_AV_STATE_OPENED);

 /* suspend completed and state changed, clear pending status */
      btif_av_cb.flags &= ~BTIF_AV_FLAG_LOCAL_SUSPEND_PENDING;
 break;

 case BTA_AV_STOP_EVT:
      BTIF_TRACE_WARNING("%s: event=%s flags=0x%x", __func__,
                         dump_av_sm_event_name((btif_av_sm_event_t)event),
                         btif_av_cb.flags);

      btif_av_cb.flags |= BTIF_AV_FLAG_PENDING_STOP;
      btif_a2dp_on_stopped(&p_av->suspend);

      btif_report_audio_state(BTAV_AUDIO_STATE_STOPPED, &(btif_av_cb.peer_bda));

 /* if stop was successful, change state to open */
 if (p_av->suspend.status == BTA_AV_SUCCESS)
        btif_sm_change_state(btif_av_cb.sm_handle, BTIF_AV_STATE_OPENED);

 break;

 case BTA_AV_CLOSE_EVT:
      BTIF_TRACE_WARNING("%s: event=%s flags=0x%x", __func__,
                         dump_av_sm_event_name((btif_av_sm_event_t)event),
                         btif_av_cb.flags);

      btif_av_cb.flags |= BTIF_AV_FLAG_PENDING_STOP;

 /* avdtp link is closed */
      btif_a2dp_on_stopped(NULL);

 /* inform the application that we are disconnected */
      btif_report_connection_state(BTAV_CONNECTION_STATE_DISCONNECTED,
 &(btif_av_cb.peer_bda));

      btif_sm_change_state(btif_av_cb.sm_handle, BTIF_AV_STATE_IDLE);
 break;

 case BTIF_AV_OFFLOAD_START_REQ_EVT:
      BTA_AvOffloadStart(btif_av_cb.bta_handle);
 break;

 case BTA_AV_OFFLOAD_START_RSP_EVT:
      btif_a2dp_on_offload_started(p_av->status);
 break;

      CHECK_RC_EVENT(event, (tBTA_AV*)p_data);

 default:
      BTIF_TRACE_WARNING("%s: unhandled event=%s", __func__,
                         dump_av_sm_event_name((btif_av_sm_event_t)event));
 return false;
 }

 return true;
}


void AutocompleteEditModel::PopupBoundsChangedTo(const gfx::Rect& bounds) {
  InstantController* instant = controller_->GetInstant();
  if (instant)
    instant->SetOmniboxBounds(bounds);
}


static inline void avg_tpel_pixels_mc12_c(uint8_t *dst, const uint8_t *src, int stride, int width, int height){
    int i,j;
    for (i=0; i < height; i++) {
      for (j=0; j < width; j++) {
        dst[j] = (dst[j] + ((2731*(3*src[j] + 2*src[j+1] + 4*src[j+stride] + 3*src[j+stride+1] + 6)) >> 15) + 1) >> 1;
      }
      src += stride;
      dst += stride;
    }
}


static int count_inuse(struct page *page)
{
	return page->inuse;
}


int object_property_get_enum(Object *obj, const char *name,

                             const char *typename, Error **errp)

{

    StringOutputVisitor *sov;

    StringInputVisitor *siv;

    char *str;

    int ret;

    ObjectProperty *prop = object_property_find(obj, name, errp);

    EnumProperty *enumprop;

    if (prop == NULL) {

        return 0;

    }

    if (!g_str_equal(prop->type, typename)) {

        error_setg(errp, "Property %s on %s is not '%s' enum type",

                   name, object_class_get_name(

                       object_get_class(obj)), typename);

        return 0;

    }

    enumprop = prop->opaque;

    sov = string_output_visitor_new(false);

    object_property_get(obj, string_output_get_visitor(sov), name, errp);

    str = string_output_get_string(sov);

    siv = string_input_visitor_new(str);

    string_output_visitor_cleanup(sov);

    visit_type_enum(string_input_get_visitor(siv),

                    &ret, enumprop->strings, NULL, name, errp);

    g_free(str);

    string_input_visitor_cleanup(siv);

    return ret;

}


void CopyFeatureSwitch(const base::CommandLine& src,
                       base::CommandLine* dest,
                       const char* switch_name) {
  std::vector<std::string> features = FeaturesFromSwitch(src, switch_name);
  if (!features.empty())
    dest->AppendSwitchASCII(switch_name, base::JoinString(features, ","));
}


TEST_F(CheckAuthTest, TestOKAuth) {
  // Step 1. Check auth requires open ID discovery and fetching public key.
  TestValidToken(kToken, kUserInfo_kSub2_kIss);

  EXPECT_TRUE(Mock::VerifyAndClearExpectations(raw_request_));
  EXPECT_TRUE(Mock::VerifyAndClearExpectations(raw_env_));

  // Step 2. Check auth with the same auth token. This time the token is cached.
  EXPECT_CALL(*raw_request_, FindHeader("x-goog-iap-jwt-assertion", _))
      .WillOnce(Invoke([](const std::string &, std::string *token) {
        *token = "";
        return false;
      }));
  EXPECT_CALL(*raw_request_, FindHeader(kAuthHeader, _))
      .WillOnce(Invoke([](const std::string &, std::string *token) {
        *token = std::string(kBearer) + std::string(kToken);
        return true;
      }));
  EXPECT_CALL(*raw_request_, SetAuthToken(kToken)).Times(1);
  EXPECT_CALL(*raw_env_, DoRunHTTPRequest(_)).Times(0);
  EXPECT_CALL(*raw_request_, AddHeaderToBackend(kEndpointApiUserInfo,
                                                kUserInfo_kSub_kIss, false))
      .WillOnce(Return(utils::Status::OK));

  CheckAuth(context_, [](Status status) { ASSERT_TRUE(status.ok()); });

  EXPECT_TRUE(Mock::VerifyAndClearExpectations(raw_request_));
  EXPECT_TRUE(Mock::VerifyAndClearExpectations(raw_env_));

  // Step 3. Check auth with a different token signed by the same issuer.
  // In this case, the token is not in the cache, but key is cached.
  EXPECT_CALL(*raw_request_, FindHeader("x-goog-iap-jwt-assertion", _))
      .WillOnce(Invoke([](const std::string &, std::string *token) {
        *token = "";
        return false;
      }));
  EXPECT_CALL(*raw_request_, FindHeader(kAuthHeader, _))
      .WillOnce(Invoke([](const std::string &, std::string *token) {
        *token = std::string(kToken2);
        return true;
      }));
  EXPECT_CALL(*raw_request_, SetAuthToken(kToken2)).Times(1);
  EXPECT_CALL(*raw_env_, DoRunHTTPRequest(_)).Times(0);
  EXPECT_CALL(*raw_request_, AddHeaderToBackend(kEndpointApiUserInfo,
                                                kUserInfo_kSub2_kIss2, false))
      .WillOnce(Return(utils::Status::OK));

  CheckAuth(context_, [](Status status) { ASSERT_TRUE(status.ok()); });
}


static apr_status_t php_server_context_cleanup(void *data_)
{
	void **data = data_;
	*data = NULL;
	return APR_SUCCESS;
}


bool vgacon_text_force(void)
{
	return vgacon_text_mode_force;
}


static struct ext4_dir_entry_2 *do_split(handle_t *handle, struct inode *dir,
			struct buffer_head **bh,struct dx_frame *frame,
			struct dx_hash_info *hinfo, int *error)
{
	unsigned blocksize = dir->i_sb->s_blocksize;
	unsigned count, continued;
	struct buffer_head *bh2;
	ext4_lblk_t newblock;
	u32 hash2;
	struct dx_map_entry *map;
	char *data1 = (*bh)->b_data, *data2;
	unsigned split, move, size;
	struct ext4_dir_entry_2 *de = NULL, *de2;
	struct ext4_dir_entry_tail *t;
	int	csum_size = 0;
	int	err = 0, i;

	if (EXT4_HAS_RO_COMPAT_FEATURE(dir->i_sb,
				       EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
		csum_size = sizeof(struct ext4_dir_entry_tail);

	bh2 = ext4_append (handle, dir, &newblock, &err);
	if (!(bh2)) {
		brelse(*bh);
		*bh = NULL;
		goto errout;
	}

	BUFFER_TRACE(*bh, "get_write_access");
	err = ext4_journal_get_write_access(handle, *bh);
	if (err)
		goto journal_error;

	BUFFER_TRACE(frame->bh, "get_write_access");
	err = ext4_journal_get_write_access(handle, frame->bh);
	if (err)
		goto journal_error;

	data2 = bh2->b_data;

	/* create map in the end of data2 block */
	map = (struct dx_map_entry *) (data2 + blocksize);
	count = dx_make_map((struct ext4_dir_entry_2 *) data1,
			     blocksize, hinfo, map);
	map -= count;
	dx_sort_map(map, count);
	/* Split the existing block in the middle, size-wise */
	size = 0;
	move = 0;
	for (i = count-1; i >= 0; i--) {
		/* is more than half of this entry in 2nd half of the block? */
		if (size + map[i].size/2 > blocksize/2)
			break;
		size += map[i].size;
		move++;
	}
	/* map index at which we will split */
	split = count - move;
	hash2 = map[split].hash;
	continued = hash2 == map[split - 1].hash;
	dxtrace(printk(KERN_INFO "Split block %lu at %x, %i/%i\n",
			(unsigned long)dx_get_block(frame->at),
					hash2, split, count-split));

	/* Fancy dance to stay within two buffers */
	de2 = dx_move_dirents(data1, data2, map + split, count - split, blocksize);
	de = dx_pack_dirents(data1, blocksize);
	de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
					   (char *) de,
					   blocksize);
	de2->rec_len = ext4_rec_len_to_disk(data2 + (blocksize - csum_size) -
					    (char *) de2,
					    blocksize);
	if (csum_size) {
		t = EXT4_DIRENT_TAIL(data2, blocksize);
		initialize_dirent_tail(t, blocksize);

		t = EXT4_DIRENT_TAIL(data1, blocksize);
		initialize_dirent_tail(t, blocksize);
	}

	dxtrace(dx_show_leaf (hinfo, (struct ext4_dir_entry_2 *) data1, blocksize, 1));
	dxtrace(dx_show_leaf (hinfo, (struct ext4_dir_entry_2 *) data2, blocksize, 1));

	/* Which block gets the new entry? */
	if (hinfo->hash >= hash2)
	{
		swap(*bh, bh2);
		de = de2;
	}
	dx_insert_block(frame, hash2 + continued, newblock);
	err = ext4_handle_dirty_dirent_node(handle, dir, bh2);
	if (err)
		goto journal_error;
	err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
	if (err)
		goto journal_error;
	brelse(bh2);
	dxtrace(dx_show_index("frame", frame->entries));
	return de;

journal_error:
	brelse(*bh);
	brelse(bh2);
	*bh = NULL;
	ext4_std_error(dir->i_sb, err);
errout:
	*error = err;
	return NULL;
}


  void AcceptMojoConnection(base::ScopedFD handle) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(host_->sequence_checker_);
    DCHECK(pending_token_);
    pending_token_ = {};
    mojo_connection_delegate_->AcceptMojoConnection(std::move(handle));
  }


bool LayerWebKitThread::filtersCanBeComposited(const FilterOperations& filters)
{
    if (!filters.size())
        return false;

    for (unsigned i = 0; i < filters.size(); ++i) {
        const FilterOperation* filterOperation = filters.at(i);
        switch (filterOperation->getOperationType()) {
        case FilterOperation::REFERENCE:
#if ENABLE(CSS_SHADERS)
        case FilterOperation::CUSTOM:
#endif
            return false;
        default:
            break;
        }
    }

    return true;
}


void virtio_device_set_child_bus_name(VirtIODevice *vdev, char *bus_name)
{
    g_free(vdev->bus_name);
    vdev->bus_name = g_strdup(bus_name);
}


void WebGLRenderingContextBase::vertexAttrib2fv(
    GLuint index,
    MaybeShared<const DOMFloat32Array> v) {
  if (isContextLost())
    return;
  if (!v.View() || v.View()->length() < 2) {
    SynthesizeGLError(GL_INVALID_VALUE, "vertexAttrib2fv", "invalid array");
    return;
  }
  ContextGL()->VertexAttrib2fv(index, v.View()->DataMaybeShared());
  SetVertexAttribType(index, kFloat32ArrayType);
}


SProcRenderQueryVersion (ClientPtr client)
{
    register int n;
    REQUEST(xRenderQueryVersionReq);

    swaps(&stuff->length, n);
    swapl(&stuff->majorVersion, n);
    swapl(&stuff->minorVersion, n);
    return (*ProcRenderVector[stuff->renderReqType])(client);
}


bool is_connected() override { return false; }


bool find_numa_distance(int distance)
{
	int i;

	if (distance == node_distance(0, 0))
		return true;

	for (i = 0; i < sched_domains_numa_levels; i++) {
		if (sched_domains_numa_distance[i] == distance)
			return true;
	}

	return false;
}


PHP_FUNCTION(gd_info)
{
	if (zend_parse_parameters_none() == FAILURE) {
		RETURN_FALSE;
	}

	array_init(return_value);

	add_assoc_string(return_value, "GD Version", PHP_GD_VERSION_STRING, 1);

#ifdef ENABLE_GD_TTF
	add_assoc_bool(return_value, "FreeType Support", 1);
#if HAVE_LIBFREETYPE
	add_assoc_string(return_value, "FreeType Linkage", "with freetype", 1);
#else
	add_assoc_string(return_value, "FreeType Linkage", "with unknown library", 1);
#endif
#else
	add_assoc_bool(return_value, "FreeType Support", 0);
#endif

#ifdef HAVE_LIBT1
	add_assoc_bool(return_value, "T1Lib Support", 1);
#else
	add_assoc_bool(return_value, "T1Lib Support", 0);
#endif
	add_assoc_bool(return_value, "GIF Read Support", 1);
	add_assoc_bool(return_value, "GIF Create Support", 1);
#ifdef HAVE_GD_JPG
	add_assoc_bool(return_value, "JPEG Support", 1);
#else
	add_assoc_bool(return_value, "JPEG Support", 0);
#endif
#ifdef HAVE_GD_PNG
	add_assoc_bool(return_value, "PNG Support", 1);
#else
	add_assoc_bool(return_value, "PNG Support", 0);
#endif
	add_assoc_bool(return_value, "WBMP Support", 1);
#if defined(HAVE_GD_XPM)
	add_assoc_bool(return_value, "XPM Support", 1);
#else
	add_assoc_bool(return_value, "XPM Support", 0);
#endif
	add_assoc_bool(return_value, "XBM Support", 1);
#if defined(USE_GD_JISX0208)
	add_assoc_bool(return_value, "JIS-mapped Japanese Font Support", 1);
#else
	add_assoc_bool(return_value, "JIS-mapped Japanese Font Support", 0);
#endif
}


 void SetupMacroblock(MACROBLOCKD *mbptr,
                       MODE_INFO *miptr,
 uint8_t *data,
 int block_size,
 int stride,
 int num_planes) {
    mbptr_ = mbptr;
    miptr_ = miptr;
    mbptr_->up_available = 1;
    mbptr_->left_available = 1;
    mbptr_->mode_info_context = miptr_;
    stride_ = stride;
    block_size_ = block_size;
    num_planes_ = num_planes;
 for (int p = 0; p < num_planes; p++)
      data_ptr_[p] = data + stride * (block_size + 1) * p +
                     stride + block_size;
 }


R_API RCore *r_core_ncast(ut64 p) {
	return (RCore*)(size_t)p;
}


static gboolean webkit_web_view_draw(GtkWidget* widget, cairo_t* cr)
{
    WebKitWebView* webView = WEBKIT_WEB_VIEW(widget);
    WebKitWebViewPrivate* priv = webView->priv;
    GdkRectangle clipRect;

    if (!gdk_cairo_get_clip_rectangle(cr, &clipRect))
        return FALSE;

    Frame* frame = core(webView)->mainFrame();
    if (frame->contentRenderer() && frame->view()) {
        GraphicsContext gc(cr);
        IntRect rect = clipRect;
        cairo_rectangle_list_t* rectList = cairo_copy_clip_rectangle_list(cr);

        frame->view()->updateLayoutAndStyleIfNeededRecursive();

        Vector<IntRect> rects;
        if (!rectList->status && rectList->num_rectangles > 0) {
            for (int i = 0; i < rectList->num_rectangles; i++)
                rects.append(enclosingIntRect(FloatRect(rectList->rectangles[i])));
        }
        paintWebView(frame, priv->transparent, gc, rect, rects);

        cairo_rectangle_list_destroy(rectList);
    }

    return FALSE;
}


int genl_unregister_family(const struct genl_family *family)
{
	genl_lock_all();

	if (!genl_family_find_byid(family->id)) {
		genl_unlock_all();
		return -ENOENT;
	}

	genl_unregister_mc_groups(family);

	idr_remove(&genl_fam_idr, family->id);

	up_write(&cb_lock);
	wait_event(genl_sk_destructing_waitq,
		   atomic_read(&genl_sk_destructing_cnt) == 0);
	genl_unlock();

	kfree(family->attrbuf);

	genl_ctrl_event(CTRL_CMD_DELFAMILY, family, NULL, 0);

	return 0;
}


filepos_t KaxBlockVirtual::ReadData(IOCallback & input, ScopeMode /* ReadFully */)
{
  input.setFilePointer(SizePosition + CodedSizeLength(Size, SizeLength, bSizeIsFinite) + Size, seek_beginning);
  return GetSize();
}


SYSCALL_DEFINE4(prlimit64, pid_t, pid, unsigned int, resource,
		const struct rlimit64 __user *, new_rlim,
		struct rlimit64 __user *, old_rlim)
{
	struct rlimit64 old64, new64;
	struct rlimit old, new;
	struct task_struct *tsk;
	int ret;

	if (new_rlim) {
		if (copy_from_user(&new64, new_rlim, sizeof(new64)))
			return -EFAULT;
		rlim64_to_rlim(&new64, &new);
	}

	rcu_read_lock();
	tsk = pid ? find_task_by_vpid(pid) : current;
	if (!tsk) {
		rcu_read_unlock();
		return -ESRCH;
	}
	ret = check_prlimit_permission(tsk);
	if (ret) {
		rcu_read_unlock();
		return ret;
	}
	get_task_struct(tsk);
	rcu_read_unlock();

	ret = do_prlimit(tsk, resource, new_rlim ? &new : NULL,
			old_rlim ? &old : NULL);

	if (!ret && old_rlim) {
		rlim_to_rlim64(&old, &old64);
		if (copy_to_user(old_rlim, &old64, sizeof(old64)))
			ret = -EFAULT;
	}

	put_task_struct(tsk);
	return ret;
}


static void restore_pirqs(void)
{
	int pirq, rc, irq, gsi;
	struct physdev_map_pirq map_irq;
	struct irq_info *info;

	list_for_each_entry(info, &xen_irq_list_head, list) {
		if (info->type != IRQT_PIRQ)
			continue;

		pirq = info->u.pirq.pirq;
		gsi = info->u.pirq.gsi;
		irq = info->irq;

		/* save/restore of PT devices doesn't work, so at this point the
		 * only devices present are GSI based emulated devices */
		if (!gsi)
			continue;

		map_irq.domid = DOMID_SELF;
		map_irq.type = MAP_PIRQ_TYPE_GSI;
		map_irq.index = gsi;
		map_irq.pirq = pirq;

		rc = HYPERVISOR_physdev_op(PHYSDEVOP_map_pirq, &map_irq);
		if (rc) {
			pr_warn("xen map irq failed gsi=%d irq=%d pirq=%d rc=%d\n",
				gsi, irq, pirq, rc);
			xen_free_irq(irq);
			continue;
		}

		printk(KERN_DEBUG "xen: --> irq=%d, pirq=%d\n", irq, map_irq.pirq);

		__startup_pirq(irq);
	}
}


PHPAPI PHP_FUNCTION(fwrite)
{
	zval *arg1;
	char *arg2;
	int arg2len;
	int ret;
	int num_bytes;
	long arg3 = 0;
	char *buffer = NULL;
	php_stream *stream;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|l", &arg1, &arg2, &arg2len, &arg3) == FAILURE) {
		RETURN_FALSE;
	}

	if (ZEND_NUM_ARGS() == 2) {
		num_bytes = arg2len;
	} else {
		num_bytes = MAX(0, MIN((int)arg3, arg2len));
	}

	if (!num_bytes) {
		RETURN_LONG(0);
	}

	PHP_STREAM_TO_ZVAL(stream, &arg1);

	ret = php_stream_write(stream, buffer ? buffer : arg2, num_bytes);
	if (buffer) {
		efree(buffer);
	}

	RETURN_LONG(ret);
}


const char *FS_LoadedPakChecksums( void ) {
	static char	info[BIG_INFO_STRING];
	searchpath_t	*search;

	info[0] = 0;

	for ( search = fs_searchpaths ; search ; search = search->next ) {
		if ( !search->pack ) {
			continue;
		}

		Q_strcat( info, sizeof( info ), va("%i ", search->pack->checksum ) );
	}

	return info;
}


xmlParseCharData(xmlParserCtxtPtr ctxt, int cdata) {
    const xmlChar *in;
    int nbchar = 0;
    int line = ctxt->input->line;
    int col = ctxt->input->col;
    int ccol;

    SHRINK;
    GROW;
    /*
     * Accelerated common case where input don't need to be
     * modified before passing it to the handler.
     */
    if (!cdata) {
	in = ctxt->input->cur;
	do {
get_more_space:
	    while (*in == 0x20) { in++; ctxt->input->col++; }
	    if (*in == 0xA) {
		do {
		    ctxt->input->line++; ctxt->input->col = 1;
		    in++;
		} while (*in == 0xA);
		goto get_more_space;
	    }
	    if (*in == '<') {
		nbchar = in - ctxt->input->cur;
		if (nbchar > 0) {
		    const xmlChar *tmp = ctxt->input->cur;
		    ctxt->input->cur = in;

		    if ((ctxt->sax != NULL) &&
		        (ctxt->sax->ignorableWhitespace !=
		         ctxt->sax->characters)) {
			if (areBlanks(ctxt, tmp, nbchar, 1)) {
			    if (ctxt->sax->ignorableWhitespace != NULL)
				ctxt->sax->ignorableWhitespace(ctxt->userData,
						       tmp, nbchar);
			} else {
			    if (ctxt->sax->characters != NULL)
				ctxt->sax->characters(ctxt->userData,
						      tmp, nbchar);
			    if (*ctxt->space == -1)
			        *ctxt->space = -2;
			}
		    } else if ((ctxt->sax != NULL) &&
		               (ctxt->sax->characters != NULL)) {
			ctxt->sax->characters(ctxt->userData,
					      tmp, nbchar);
		    }
		}
		return;
	    }

get_more:
            ccol = ctxt->input->col;
	    while (test_char_data[*in]) {
		in++;
		ccol++;
	    }
	    ctxt->input->col = ccol;
	    if (*in == 0xA) {
		do {
		    ctxt->input->line++; ctxt->input->col = 1;
		    in++;
		} while (*in == 0xA);
		goto get_more;
	    }
	    if (*in == ']') {
		if ((in[1] == ']') && (in[2] == '>')) {
		    xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL);
		    ctxt->input->cur = in;
		    return;
		}
		in++;
		ctxt->input->col++;
		goto get_more;
	    }
	    nbchar = in - ctxt->input->cur;
	    if (nbchar > 0) {
		if ((ctxt->sax != NULL) &&
		    (ctxt->sax->ignorableWhitespace !=
		     ctxt->sax->characters) &&
		    (IS_BLANK_CH(*ctxt->input->cur))) {
		    const xmlChar *tmp = ctxt->input->cur;
		    ctxt->input->cur = in;

		    if (areBlanks(ctxt, tmp, nbchar, 0)) {
		        if (ctxt->sax->ignorableWhitespace != NULL)
			    ctxt->sax->ignorableWhitespace(ctxt->userData,
							   tmp, nbchar);
		    } else {
		        if (ctxt->sax->characters != NULL)
			    ctxt->sax->characters(ctxt->userData,
						  tmp, nbchar);
			if (*ctxt->space == -1)
			    *ctxt->space = -2;
		    }
                    line = ctxt->input->line;
                    col = ctxt->input->col;
		} else if (ctxt->sax != NULL) {
		    if (ctxt->sax->characters != NULL)
			ctxt->sax->characters(ctxt->userData,
					      ctxt->input->cur, nbchar);
                    line = ctxt->input->line;
                    col = ctxt->input->col;
		}
                /* something really bad happened in the SAX callback */
                if (ctxt->instate != XML_PARSER_CONTENT)
                    return;
	    }
	    ctxt->input->cur = in;
	    if (*in == 0xD) {
		in++;
		if (*in == 0xA) {
		    ctxt->input->cur = in;
		    in++;
		    ctxt->input->line++; ctxt->input->col = 1;
		    continue; /* while */
		}
		in--;
	    }
	    if (*in == '<') {
		return;
	    }
	    if (*in == '&') {
		return;
 	    }
 	    SHRINK;
 	    GROW;
 	    in = ctxt->input->cur;
 	} while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09));
 	nbchar = 0;
    }
    ctxt->input->line = line;
    ctxt->input->col = col;
    xmlParseCharDataComplex(ctxt, cdata);
}


int64_t vp9_rd_pick_inter_mode_sb_seg_skip ( VP9_COMP * cpi , MACROBLOCK * x , int * returnrate , int64_t * returndistortion , BLOCK_SIZE bsize , PICK_MODE_CONTEXT * ctx , int64_t best_rd_so_far ) {
 VP9_COMMON * const cm = & cpi -> common ;
 RD_OPT * const rd_opt = & cpi -> rd ;
 MACROBLOCKD * const xd = & x -> e_mbd ;
 MB_MODE_INFO * const mbmi = & xd -> mi [ 0 ] . src_mi -> mbmi ;
 unsigned char segment_id = mbmi -> segment_id ;
 const int comp_pred = 0 ;
 int i ;
 int64_t best_tx_diff [ TX_MODES ] ;
 int64_t best_pred_diff [ REFERENCE_MODES ] ;
 int64_t best_filter_diff [ SWITCHABLE_FILTER_CONTEXTS ] ;
 unsigned int ref_costs_single [ MAX_REF_FRAMES ] , ref_costs_comp [ MAX_REF_FRAMES ] ;
 vp9_prob comp_mode_p ;
 INTERP_FILTER best_filter = SWITCHABLE ;
 int64_t this_rd = INT64_MAX ;
 int rate2 = 0 ;
 const int64_t distortion2 = 0 ;
 x -> skip_encode = cpi -> sf . skip_encode_frame && x -> q_index < QIDX_SKIP_THRESH ;
 estimate_ref_frame_costs ( cm , xd , segment_id , ref_costs_single , ref_costs_comp , & comp_mode_p ) ;
 for ( i = 0 ;
 i < MAX_REF_FRAMES ;
 ++ i ) x -> pred_sse [ i ] = INT_MAX ;
 for ( i = LAST_FRAME ;
 i < MAX_REF_FRAMES ;
 ++ i ) x -> pred_mv_sad [ i ] = INT_MAX ;
 * returnrate = INT_MAX ;
 assert ( vp9_segfeature_active ( & cm -> seg , segment_id , SEG_LVL_SKIP ) ) ;
 mbmi -> mode = ZEROMV ;
 mbmi -> uv_mode = DC_PRED ;
 mbmi -> ref_frame [ 0 ] = LAST_FRAME ;
 mbmi -> ref_frame [ 1 ] = NONE ;
 mbmi -> mv [ 0 ] . as_int = 0 ;
 x -> skip = 1 ;
 rd_opt -> mask_filter = 0 ;
 for ( i = 0 ;
 i < SWITCHABLE_FILTER_CONTEXTS ;
 ++ i ) rd_opt -> filter_cache [ i ] = INT64_MAX ;
 if ( cm -> interp_filter != BILINEAR ) {
 best_filter = EIGHTTAP ;
 if ( cm -> interp_filter == SWITCHABLE && x -> source_variance >= cpi -> sf . disable_filter_search_var_thresh ) {
 int rs ;
 int best_rs = INT_MAX ;
 for ( i = 0 ;
 i < SWITCHABLE_FILTERS ;
 ++ i ) {
 mbmi -> interp_filter = i ;
 rs = vp9_get_switchable_rate ( cpi ) ;
 if ( rs < best_rs ) {
 best_rs = rs ;
 best_filter = mbmi -> interp_filter ;
 }
 }
 }
 }
 if ( cm -> interp_filter == SWITCHABLE ) {
 mbmi -> interp_filter = best_filter ;
 rate2 += vp9_get_switchable_rate ( cpi ) ;
 }
 else {
 mbmi -> interp_filter = cm -> interp_filter ;
 }
 if ( cm -> reference_mode == REFERENCE_MODE_SELECT ) rate2 += vp9_cost_bit ( comp_mode_p , comp_pred ) ;
 rate2 += ref_costs_single [ LAST_FRAME ] ;
 this_rd = RDCOST ( x -> rdmult , x -> rddiv , rate2 , distortion2 ) ;
 * returnrate = rate2 ;
 * returndistortion = distortion2 ;
 if ( this_rd >= best_rd_so_far ) return INT64_MAX ;
 assert ( ( cm -> interp_filter == SWITCHABLE ) || ( cm -> interp_filter == mbmi -> interp_filter ) ) ;
 update_rd_thresh_fact ( cpi , bsize , THR_ZEROMV ) ;
 vp9_zero ( best_pred_diff ) ;
 vp9_zero ( best_filter_diff ) ;
 vp9_zero ( best_tx_diff ) ;
 if ( ! x -> select_tx_size ) swap_block_ptr ( x , ctx , 1 , 0 , 0 , MAX_MB_PLANE ) ;
 store_coding_context ( x , ctx , THR_ZEROMV , best_pred_diff , best_tx_diff , best_filter_diff , 0 ) ;
 return this_rd ;
 }


static int qesd_init_out (HWVoiceOut *hw, audsettings_t *as)

{

    ESDVoiceOut *esd = (ESDVoiceOut *) hw;

    audsettings_t obt_as = *as;

    int esdfmt = ESD_STREAM | ESD_PLAY;

    int err;

    sigset_t set, old_set;

    sigfillset (&set);

    esdfmt |= (as->nchannels == 2) ? ESD_STEREO : ESD_MONO;

    switch (as->fmt) {

    case AUD_FMT_S8:

    case AUD_FMT_U8:

        esdfmt |= ESD_BITS8;

        obt_as.fmt = AUD_FMT_U8;

        break;

    case AUD_FMT_S32:

    case AUD_FMT_U32:

        dolog ("Will use 16 instead of 32 bit samples\n");

    case AUD_FMT_S16:

    case AUD_FMT_U16:

    deffmt:

        esdfmt |= ESD_BITS16;

        obt_as.fmt = AUD_FMT_S16;

        break;

    default:

        dolog ("Internal logic error: Bad audio format %d\n", as->fmt);

        goto deffmt;

    }

    obt_as.endianness = AUDIO_HOST_ENDIANNESS;

    audio_pcm_init_info (&hw->info, &obt_as);

    hw->samples = conf.samples;

    esd->pcm_buf = audio_calloc (AUDIO_FUNC, hw->samples, 1 << hw->info.shift);

    if (!esd->pcm_buf) {

        dolog ("Could not allocate buffer (%d bytes)\n",

               hw->samples << hw->info.shift);

        return -1;

    }

    esd->fd = -1;

    err = pthread_sigmask (SIG_BLOCK, &set, &old_set);

    if (err) {

        qesd_logerr (err, "pthread_sigmask failed\n");

        goto fail1;

    }

    esd->fd = esd_play_stream (esdfmt, as->freq, conf.dac_host, NULL);

    if (esd->fd < 0) {

        qesd_logerr (errno, "esd_play_stream failed\n");

        goto fail2;

    }

    if (audio_pt_init (&esd->pt, qesd_thread_out, esd, AUDIO_CAP, AUDIO_FUNC)) {

        goto fail3;

    }

    err = pthread_sigmask (SIG_SETMASK, &old_set, NULL);

    if (err) {

        qesd_logerr (err, "pthread_sigmask(restore) failed\n");

    }

    return 0;

 fail3:

    if (close (esd->fd)) {

        qesd_logerr (errno, "%s: close on esd socket(%d) failed\n",

                     AUDIO_FUNC, esd->fd);

    }

    esd->fd = -1;

 fail2:

    err = pthread_sigmask (SIG_SETMASK, &old_set, NULL);

    if (err) {

        qesd_logerr (err, "pthread_sigmask(restore) failed\n");

    }

 fail1:

    qemu_free (esd->pcm_buf);

    esd->pcm_buf = NULL;

    return -1;

}


nfsd_lookup_dentry(struct svc_rqst *rqstp, struct svc_fh *fhp,
		   const char *name, unsigned int len,
		   struct svc_export **exp_ret, struct dentry **dentry_ret)
{
	struct svc_export	*exp;
	struct dentry		*dparent;
	struct dentry		*dentry;
	int			host_err;

	dprintk("nfsd: nfsd_lookup(fh %s, %.*s)\n", SVCFH_fmt(fhp), len,name);

	dparent = fhp->fh_dentry;
	exp = exp_get(fhp->fh_export);

	/* Lookup the name, but don't follow links */
	if (isdotent(name, len)) {
		if (len==1)
			dentry = dget(dparent);
		else if (dparent != exp->ex_path.dentry)
			dentry = dget_parent(dparent);
		else if (!EX_NOHIDE(exp) && !nfsd_v4client(rqstp))
			dentry = dget(dparent); /* .. == . just like at / */
		else {
			/* checking mountpoint crossing is very different when stepping up */
			host_err = nfsd_lookup_parent(rqstp, dparent, &exp, &dentry);
			if (host_err)
				goto out_nfserr;
		}
	} else {
		/*
		 * In the nfsd4_open() case, this may be held across
		 * subsequent open and delegation acquisition which may
		 * need to take the child's i_mutex:
		 */
		fh_lock_nested(fhp, I_MUTEX_PARENT);
		dentry = lookup_one_len(name, dparent, len);
		host_err = PTR_ERR(dentry);
		if (IS_ERR(dentry))
			goto out_nfserr;
		if (nfsd_mountpoint(dentry, exp)) {
			/*
			 * We don't need the i_mutex after all.  It's
			 * still possible we could open this (regular
			 * files can be mountpoints too), but the
			 * i_mutex is just there to prevent renames of
			 * something that we might be about to delegate,
			 * and a mountpoint won't be renamed:
			 */
			fh_unlock(fhp);
			if ((host_err = nfsd_cross_mnt(rqstp, &dentry, &exp))) {
				dput(dentry);
				goto out_nfserr;
			}
		}
	}
	*dentry_ret = dentry;
	*exp_ret = exp;
	return 0;

out_nfserr:
	exp_put(exp);
	return nfserrno(host_err);
}


void init_cfs_rq(struct cfs_rq *cfs_rq)
{
	cfs_rq->tasks_timeline = RB_ROOT_CACHED;
	cfs_rq->min_vruntime = (u64)(-(1LL << 20));
#ifndef CONFIG_64BIT
	cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
#endif
#ifdef CONFIG_SMP
	raw_spin_lock_init(&cfs_rq->removed.lock);
#endif
}


static bool has_unmap_ctx(struct userfaultfd_ctx *ctx, struct list_head *unmaps,
			  unsigned long start, unsigned long end)
{
	struct userfaultfd_unmap_ctx *unmap_ctx;

	list_for_each_entry(unmap_ctx, unmaps, list)
		if (unmap_ctx->ctx == ctx && unmap_ctx->start == start &&
		    unmap_ctx->end == end)
			return true;

	return false;
}


bool MaybeSavedModelDirectory(const string& export_dir) {
  const string saved_model_pb_path =
      io::JoinPath(export_dir, kSavedModelFilenamePb);
  const string saved_model_pbtxt_path =
      io::JoinPath(export_dir, kSavedModelFilenamePbTxt);
  return Env::Default()->FileExists(saved_model_pb_path).ok() ||
         Env::Default()->FileExists(saved_model_pbtxt_path).ok();
}


const ResourceLoaderOptions& ResourceFetcher::DefaultResourceOptions() {
  DEFINE_STATIC_LOCAL(
      ResourceLoaderOptions, options,
      (kBufferData, kAllowStoredCredentials, kClientRequestedCredentials,
       kCheckContentSecurityPolicy, kDocumentContext));
  return options;
}


int yr_re_ast_split_at_chaining_point(
    RE_AST* re_ast,
    RE_AST** result_re_ast,
    RE_AST** remainder_re_ast,
    int32_t* min_gap,
    int32_t* max_gap)
{
  RE_NODE* node = re_ast->root_node;
  RE_NODE* child = re_ast->root_node->left;
  RE_NODE* parent = NULL;

  int result;

  *result_re_ast = re_ast;
  *remainder_re_ast = NULL;
  *min_gap = 0;
  *max_gap = 0;

  while (child != NULL && child->type == RE_NODE_CONCAT)
  {
    if (child->right != NULL &&
        child->right->type == RE_NODE_RANGE_ANY &&
        child->right->greedy == FALSE &&
        (child->right->start > STRING_CHAINING_THRESHOLD ||
         child->right->end > STRING_CHAINING_THRESHOLD))
    {
      result = yr_re_ast_create(remainder_re_ast);

      if (result != ERROR_SUCCESS)
        return result;

      (*remainder_re_ast)->root_node = child->left;
      (*remainder_re_ast)->flags = re_ast->flags;

      child->left = NULL;

      if (parent != NULL)
        parent->left = node->right;
      else
        (*result_re_ast)->root_node = node->right;

      node->right = NULL;

      *min_gap = child->right->start;
      *max_gap = child->right->end;

      yr_re_node_destroy(node);

      return ERROR_SUCCESS;
    }

    parent = node;
    node = child;
    child = child->left;
  }

  return ERROR_SUCCESS;
}


bool GpuProcessHost::software_rendering() {
  return software_rendering_;
}


static void * kq_init ( struct event_base * base ) {
 int i , kq ;
 struct kqop * kqueueop ;
 if ( evutil_getenv ( "EVENT_NOKQUEUE" ) ) return ( NULL ) ;
 if ( ! ( kqueueop = calloc ( 1 , sizeof ( struct kqop ) ) ) ) return ( NULL ) ;
 if ( ( kq = kqueue ( ) ) == - 1 ) {
 event_warn ( "kqueue" ) ;
 free ( kqueueop ) ;
 return ( NULL ) ;
 }
 kqueueop -> kq = kq ;
 kqueueop -> pid = getpid ( ) ;
 kqueueop -> changes = malloc ( NEVENT * sizeof ( struct kevent ) ) ;
 if ( kqueueop -> changes == NULL ) {
 free ( kqueueop ) ;
 return ( NULL ) ;
 }
 kqueueop -> events = malloc ( NEVENT * sizeof ( struct kevent ) ) ;
 if ( kqueueop -> events == NULL ) {
 free ( kqueueop -> changes ) ;
 free ( kqueueop ) ;
 return ( NULL ) ;
 }
 kqueueop -> nevents = NEVENT ;
 for ( i = 0 ;
 i < NSIG ;
 ++ i ) {
 TAILQ_INIT ( & kqueueop -> evsigevents [ i ] ) ;
 }
 memset ( & kqueueop -> changes [ 0 ] , 0 , sizeof kqueueop -> changes [ 0 ] ) ;
 kqueueop -> changes [ 0 ] . ident = - 1 ;
 kqueueop -> changes [ 0 ] . filter = EVFILT_READ ;
 kqueueop -> changes [ 0 ] . flags = EV_ADD ;
 if ( kevent ( kq , kqueueop -> changes , 1 , kqueueop -> events , NEVENT , NULL ) != 1 || kqueueop -> events [ 0 ] . ident != - 1 || kqueueop -> events [ 0 ] . flags != EV_ERROR ) {
 event_warn ( "%s: detected broken kqueue;
 not using." , __func__ ) ;
 free ( kqueueop -> changes ) ;
 free ( kqueueop -> events ) ;
 free ( kqueueop ) ;
 close ( kq ) ;
 return ( NULL ) ;
 }
 return ( kqueueop ) ;
 }


flatpak_str_is_integer (const char *s)
{
  if (s == NULL || *s == '\0')
    return FALSE;

  for (; *s != '\0'; s++)
    {
      if (!g_ascii_isdigit (*s))
        return FALSE;
    }

  return TRUE;
}


static OPJ_BOOL opj_j2k_setup_decoding_validation (opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager)
{
        /* preconditions*/
        assert(p_j2k != 00);
        assert(p_manager != 00);

        if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,(opj_procedure)opj_j2k_build_decoder, p_manager)) {
                return OPJ_FALSE;
        }
        if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,(opj_procedure)opj_j2k_decoding_validation, p_manager)) {
                return OPJ_FALSE;
        }

        /* DEVELOPER CORNER, add your custom validation procedure */
        return OPJ_TRUE;
}


static void *single_next(struct seq_file *p, void *v, loff_t *pos)
{
	++*pos;
	return NULL;
}


void Box_ipma::add_property_for_item_ID(heif_item_id itemID,
                                        PropertyAssociation assoc)
{
  size_t idx;
  for (idx=0; idx<m_entries.size(); idx++) {
    if (m_entries[idx].item_ID == itemID) {
      break;
    }
  }

  // if itemID does not exist, add a new entry
  if (idx == m_entries.size()) {
    Entry entry;
    entry.item_ID = itemID;
    m_entries.push_back(entry);
  }

  // add the property association
  m_entries[idx].associations.push_back(assoc);
}


void readEmoji(YAML::Node node, string_array &dest, bool scope_limit = true)
{
    YAML::Node object;
    std::string script, url, match, rep, strLine;

    for(unsigned i = 0; i < node.size(); i++)
    {
        object = node[i];
        object["script"] >>= script;
        if(script.size())
        {
            dest.emplace_back("!!script:" + script);
            continue;
        }
        object["import"] >>= url;
        if(url.size())
        {
            url = "!!import:" + url;
            dest.emplace_back(url);
            continue;
        }
        object["match"] >>= match;
        object["emoji"] >>= rep;
        if(match.size() && rep.size())
            strLine = match + "," + rep;
        else
            continue;
        dest.emplace_back(std::move(strLine));
    }
    importItems(dest, scope_limit);
}


void WebContentsImpl::ClearDeviceEmulationSize() {
  RenderWidgetHostView* rwhv = GetMainFrame()->GetView();
  if (!view_size_before_emulation_.IsEmpty() && rwhv &&
      rwhv->GetViewBounds().size() == device_emulation_size_) {
    rwhv->SetSize(view_size_before_emulation_);
  }
  device_emulation_size_ = gfx::Size();
  view_size_before_emulation_ = gfx::Size();
}


void ServerWrapper::Send500(int connection_id,
                            const std::string& message) {
  server_->Send500(connection_id, message,
                   kDevtoolsHttpHandlerTrafficAnnotation);
}


struct dce_aux *dce112_aux_engine_create(
	struct dc_context *ctx,
	uint32_t inst)
{
	struct aux_engine_dce110 *aux_engine =
		kzalloc(sizeof(struct aux_engine_dce110), GFP_KERNEL);

	if (!aux_engine)
		return NULL;

	dce110_aux_engine_construct(aux_engine, ctx, inst,
				    SW_AUX_TIMEOUT_PERIOD_MULTIPLIER * AUX_TIMEOUT_PERIOD,
				    &aux_engine_regs[inst]);

	return &aux_engine->base;
}


DrawingBuffer::DrawingBuffer(
    std::unique_ptr<WebGraphicsContext3DProvider> context_provider,
    std::unique_ptr<Extensions3DUtil> extensions_util,
    Client* client,
    bool discard_framebuffer_supported,
     bool want_alpha_channel,
     bool premultiplied_alpha,
     PreserveDrawingBuffer preserve,
    WebGLVersion web_gl_version,
     bool want_depth,
     bool want_stencil,
     ChromiumImageUsage chromium_image_usage,
     const CanvasColorParams& color_params)
     : client_(client),
       preserve_drawing_buffer_(preserve),
      web_gl_version_(web_gl_version),
       context_provider_(WTF::WrapUnique(new WebGraphicsContext3DProviderWrapper(
           std::move(context_provider)))),
       gl_(this->ContextProvider()->ContextGL()),
      extensions_util_(std::move(extensions_util)),
      discard_framebuffer_supported_(discard_framebuffer_supported),
      want_alpha_channel_(want_alpha_channel),
      premultiplied_alpha_(premultiplied_alpha),
      software_rendering_(this->ContextProvider()->IsSoftwareRendering()),
      want_depth_(want_depth),
      want_stencil_(want_stencil),
      color_space_(color_params.GetGfxColorSpace()),
      chromium_image_usage_(chromium_image_usage) {
  TRACE_EVENT_INSTANT0("test_gpu", "DrawingBufferCreation",
                       TRACE_EVENT_SCOPE_GLOBAL);
}


LRESULT HWNDMessageHandler::OnNCUAHDrawFrame(UINT message,
                                             WPARAM w_param,
                                             LPARAM l_param) {
  SetMsgHandled(delegate_->IsUsingCustomFrame());
  return 0;
}


static void virLogResetFilters ( void ) {
 virLogFilterListFree ( virLogFilters , virLogNbFilters ) ;
 virLogFilters = NULL ;
 virLogNbFilters = 0 ;
 virLogFiltersSerial ++ ;
 }


ftrace_profile_read(struct file *filp, char __user *ubuf,
		     size_t cnt, loff_t *ppos)
{
	char buf[64];		/* big enough to hold a number */
	int r;

	r = sprintf(buf, "%u\n", ftrace_profile_enabled);
	return simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
}


static int decrypt_init(AVFormatContext *s, ID3v2ExtraMeta *em, uint8_t *header)

{

    OMAContext *oc = s->priv_data;

    ID3v2ExtraMetaGEOB *geob = NULL;

    uint8_t *gdata;

    oc->encrypted = 1;

    av_log(s, AV_LOG_INFO, "File is encrypted\n");

    /* find GEOB metadata */

    while (em) {

        if (!strcmp(em->tag, "GEOB") &&

            (geob = em->data) &&

            (!strcmp(geob->description, "OMG_LSI") ||

             !strcmp(geob->description, "OMG_BKLSI"))) {

            break;

        }

        em = em->next;

    }

    if (!em) {

        av_log(s, AV_LOG_ERROR, "No encryption header found\n");

        return AVERROR_INVALIDDATA;

    }

    if (geob->datasize < 64) {

        av_log(s, AV_LOG_ERROR,

               "Invalid GEOB data size: %u\n", geob->datasize);

        return AVERROR_INVALIDDATA;

    }

    gdata = geob->data;

    if (AV_RB16(gdata) != 1)

        av_log(s, AV_LOG_WARNING, "Unknown version in encryption header\n");

    oc->k_size = AV_RB16(&gdata[2]);

    oc->e_size = AV_RB16(&gdata[4]);

    oc->i_size = AV_RB16(&gdata[6]);

    oc->s_size = AV_RB16(&gdata[8]);

    if (memcmp(&gdata[OMA_ENC_HEADER_SIZE], "KEYRING     ", 12)) {

        av_log(s, AV_LOG_ERROR, "Invalid encryption header\n");

        return AVERROR_INVALIDDATA;

    }

    oc->rid = AV_RB32(&gdata[OMA_ENC_HEADER_SIZE + 28]);

    av_log(s, AV_LOG_DEBUG, "RID: %.8x\n", oc->rid);

    memcpy(oc->iv, &header[0x58], 8);

    hex_log(s, AV_LOG_DEBUG, "IV", oc->iv, 8);

    hex_log(s, AV_LOG_DEBUG, "CBC-MAC",

            &gdata[OMA_ENC_HEADER_SIZE + oc->k_size + oc->e_size + oc->i_size],

            8);

    if (s->keylen > 0) {

        kset(s, s->key, s->key, s->keylen);

    }

    if (!memcmp(oc->r_val, (const uint8_t[8]){0}, 8) ||

        rprobe(s, gdata, oc->r_val) < 0 &&

        nprobe(s, gdata, geob->datasize, oc->n_val) < 0) {

        int i;

        for (i = 0; i < FF_ARRAY_ELEMS(leaf_table); i += 2) {

            uint8_t buf[16];

            AV_WL64(buf,     leaf_table[i]);

            AV_WL64(&buf[8], leaf_table[i + 1]);

            kset(s, buf, buf, 16);

            if (!rprobe(s, gdata, oc->r_val) ||

                !nprobe(s, gdata, geob->datasize, oc->n_val))

                break;

        }

        if (i >= sizeof(leaf_table)) {

            av_log(s, AV_LOG_ERROR, "Invalid key\n");

            return AVERROR_INVALIDDATA;

        }

    }

    /* e_val */

    av_des_init(&oc->av_des, oc->m_val, 64, 0);

    av_des_crypt(&oc->av_des, oc->e_val,

                 &gdata[OMA_ENC_HEADER_SIZE + 40], 1, NULL, 0);

    hex_log(s, AV_LOG_DEBUG, "EK", oc->e_val, 8);

    /* init e_val */

    av_des_init(&oc->av_des, oc->e_val, 64, 1);

    return 0;

}


GahpServer::command_commands()
{
	write_line("COMMANDS");
	Gahp_Args result;
	read_argv(result);
	if ( result.argc == 0 || result.argv[0][0] != 'S' ) {
		dprintf(D_ALWAYS,"GAHP command 'COMMANDS' failed\n");
		return false;
	}

	if ( m_commands_supported ) {
		delete m_commands_supported;
		m_commands_supported = NULL;
	}
	m_commands_supported = new StringList();
	ASSERT(m_commands_supported);
	for ( int i = 1; i < result.argc; i++ ) {
		m_commands_supported->append(result.argv[i]);
	}

	return true;
}


void WebFrameLoaderClient::didDisplayInsecureContent() {
  if (webframe_->client())
    webframe_->client()->didDisplayInsecureContent(webframe_);
}


void WebGLRenderingContextBase::RestoreScissorEnabled() {
  if (isContextLost())
    return;

  if (scissor_enabled_) {
    ContextGL()->Enable(GL_SCISSOR_TEST);
  } else {
    ContextGL()->Disable(GL_SCISSOR_TEST);
  }
}


static void OverloadedMethodJMethod(const v8::FunctionCallbackInfo<v8::Value>& info) {
  scheduler::CooperativeSchedulingManager::Instance()->Safepoint();

  bool is_arity_error = false;

  switch (std::min(1, info.Length())) {
    case 1:
      if (IsUndefinedOrNull(info[0])) {
        OverloadedMethodJ2Method(info);
        return;
      }
      if (info[0]->IsObject()) {
        OverloadedMethodJ2Method(info);
        return;
      }
      if (true) {
        OverloadedMethodJ1Method(info);
        return;
      }
      break;
    default:
      is_arity_error = true;
  }

  ExceptionState exception_state(info.GetIsolate(), ExceptionState::kExecutionContext, "TestObject", "overloadedMethodJ");
  if (is_arity_error) {
    if (info.Length() < 1) {
      exception_state.ThrowTypeError(ExceptionMessages::NotEnoughArguments(1, info.Length()));
      return;
    }
  }
  exception_state.ThrowTypeError("No function was found that matched the signature provided.");
}


static int apng_encode_frame(AVCodecContext *avctx, const AVFrame *pict,

                             APNGFctlChunk *best_fctl_chunk, APNGFctlChunk *best_last_fctl_chunk)

{

    PNGEncContext *s = avctx->priv_data;

    int ret;

    unsigned int y;

    AVFrame* diffFrame;

    uint8_t bpp = (s->bits_per_pixel + 7) >> 3;

    uint8_t *original_bytestream, *original_bytestream_end;

    uint8_t *temp_bytestream = 0, *temp_bytestream_end;

    uint32_t best_sequence_number;

    uint8_t *best_bytestream;

    size_t best_bytestream_size = SIZE_MAX;

    APNGFctlChunk last_fctl_chunk = *best_last_fctl_chunk;

    APNGFctlChunk fctl_chunk = *best_fctl_chunk;

    if (avctx->frame_number == 0) {

        best_fctl_chunk->width = pict->width;

        best_fctl_chunk->height = pict->height;

        best_fctl_chunk->x_offset = 0;

        best_fctl_chunk->y_offset = 0;

        best_fctl_chunk->blend_op = APNG_BLEND_OP_SOURCE;

        return encode_frame(avctx, pict);

    }

    diffFrame = av_frame_alloc();

    if (!diffFrame)

        return AVERROR(ENOMEM);

    diffFrame->format = pict->format;

    diffFrame->width = pict->width;

    diffFrame->height = pict->height;

    if ((ret = av_frame_get_buffer(diffFrame, 32)) < 0)

        goto fail;

    original_bytestream = s->bytestream;

    original_bytestream_end = s->bytestream_end;

    temp_bytestream = av_malloc(original_bytestream_end - original_bytestream);

    temp_bytestream_end = temp_bytestream + (original_bytestream_end - original_bytestream);

    if (!temp_bytestream) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    for (last_fctl_chunk.dispose_op = 0; last_fctl_chunk.dispose_op < 3; ++last_fctl_chunk.dispose_op) {

        // 0: APNG_DISPOSE_OP_NONE

        // 1: APNG_DISPOSE_OP_BACKGROUND

        // 2: APNG_DISPOSE_OP_PREVIOUS

        for (fctl_chunk.blend_op = 0; fctl_chunk.blend_op < 2; ++fctl_chunk.blend_op) {

            // 0: APNG_BLEND_OP_SOURCE

            // 1: APNG_BLEND_OP_OVER

            uint32_t original_sequence_number = s->sequence_number, sequence_number;

            uint8_t *bytestream_start = s->bytestream;

            size_t bytestream_size;

            // Do disposal

            if (last_fctl_chunk.dispose_op != APNG_DISPOSE_OP_PREVIOUS) {

                diffFrame->width = pict->width;

                diffFrame->height = pict->height;

                av_frame_copy(diffFrame, s->last_frame);

                if (last_fctl_chunk.dispose_op == APNG_DISPOSE_OP_BACKGROUND) {

                    for (y = last_fctl_chunk.y_offset; y < last_fctl_chunk.y_offset + last_fctl_chunk.height; ++y) {

                        size_t row_start = diffFrame->linesize[0] * y + bpp * last_fctl_chunk.x_offset;

                        memset(diffFrame->data[0] + row_start, 0, bpp * last_fctl_chunk.width);

                    }

                }

            } else {

                if (!s->prev_frame)

                    continue;

                diffFrame->width = pict->width;

                diffFrame->height = pict->height;

                av_frame_copy(diffFrame, s->prev_frame);

            }

            // Do inverse blending

            if (apng_do_inverse_blend(diffFrame, pict, &fctl_chunk, bpp) < 0)

                continue;

            // Do encoding

            ret = encode_frame(avctx, diffFrame);

            sequence_number = s->sequence_number;

            s->sequence_number = original_sequence_number;

            bytestream_size = s->bytestream - bytestream_start;

            s->bytestream = bytestream_start;

            if (ret < 0)

                goto fail;

            if (bytestream_size < best_bytestream_size) {

                *best_fctl_chunk = fctl_chunk;

                *best_last_fctl_chunk = last_fctl_chunk;

                best_sequence_number = sequence_number;

                best_bytestream = s->bytestream;

                best_bytestream_size = bytestream_size;

                if (best_bytestream == original_bytestream) {

                    s->bytestream = temp_bytestream;

                    s->bytestream_end = temp_bytestream_end;

                } else {

                    s->bytestream = original_bytestream;

                    s->bytestream_end = original_bytestream_end;

                }

            }

        }

    }

    s->sequence_number = best_sequence_number;

    s->bytestream = original_bytestream + best_bytestream_size;

    s->bytestream_end = original_bytestream_end;

    if (best_bytestream != original_bytestream)

        memcpy(original_bytestream, best_bytestream, best_bytestream_size);

    ret = 0;

fail:

    av_freep(&temp_bytestream);

    av_frame_free(&diffFrame);

    return ret;

}


  static void  Ins_FLIPOFF( INS_ARG )
  { (void)args;
    CUR.GS.auto_flip = FALSE;
  }


  RenderViewImpl* view() {
    return static_cast<RenderViewImpl*>(view_);
  }


static inline void code_gen_alloc(size_t tb_size)

{

    code_gen_buffer_size = size_code_gen_buffer(tb_size);

    code_gen_buffer = alloc_code_gen_buffer();

    if (code_gen_buffer == NULL) {

        fprintf(stderr, "Could not allocate dynamic translator buffer\n");

        exit(1);

    }

    map_exec(code_gen_prologue, sizeof(code_gen_prologue));

    code_gen_buffer_max_size = code_gen_buffer_size -

        (TCG_MAX_OP_SIZE * OPC_BUF_SIZE);

    code_gen_max_blocks = code_gen_buffer_size / CODE_GEN_AVG_BLOCK_SIZE;

    tbs = g_malloc(code_gen_max_blocks * sizeof(TranslationBlock));

}


vim_isblankline(char_u *lbuf)
{
    char_u	*p;

    p = skipwhite(lbuf);
    return (*p == NUL || *p == '\r' || *p == '\n');
}


AccessibilityUIElement::AccessibilityUIElement(const AccessibilityUIElement& other)
    : JSWrappable()
    , m_element(other.m_element)
{
}


ofputil_protocol_set_tid(enum ofputil_protocol protocol, bool enable)
{
    switch (protocol) {
    case OFPUTIL_P_OF10_STD:
    case OFPUTIL_P_OF10_STD_TID:
        return enable ? OFPUTIL_P_OF10_STD_TID : OFPUTIL_P_OF10_STD;

    case OFPUTIL_P_OF10_NXM:
    case OFPUTIL_P_OF10_NXM_TID:
        return enable ? OFPUTIL_P_OF10_NXM_TID : OFPUTIL_P_OF10_NXM;

    case OFPUTIL_P_OF11_STD:
        return OFPUTIL_P_OF11_STD;

    case OFPUTIL_P_OF12_OXM:
        return OFPUTIL_P_OF12_OXM;

    case OFPUTIL_P_OF13_OXM:
        return OFPUTIL_P_OF13_OXM;

    case OFPUTIL_P_OF14_OXM:
        return OFPUTIL_P_OF14_OXM;

    case OFPUTIL_P_OF15_OXM:
        return OFPUTIL_P_OF15_OXM;

    case OFPUTIL_P_OF16_OXM:
        return OFPUTIL_P_OF16_OXM;

    default:
        OVS_NOT_REACHED();
    }
}


virtual void ms_handle_accept(Connection *con) { };


void tlb_gather_mmu(struct mmu_gather *tlb, struct mm_struct *mm, bool fullmm)
{
	tlb->mm = mm;

	tlb->fullmm     = fullmm;
	tlb->need_flush = 0;
	tlb->fast_mode  = (num_possible_cpus() == 1);
	tlb->local.next = NULL;
	tlb->local.nr   = 0;
	tlb->local.max  = ARRAY_SIZE(tlb->__pages);
	tlb->active     = &tlb->local;

#ifdef CONFIG_HAVE_RCU_TABLE_FREE
	tlb->batch = NULL;
#endif
}


static struct pdf_object *pdf_get_object(struct pdf_doc *pdf, int index)
{
    return flexarray_get(&pdf->objects, index);
}


void LoginPromptBrowserTestObserver::AddHandler(LoginHandler* handler) {
  std::list<LoginHandler*>::iterator i = std::find(handlers_.begin(),
                                                   handlers_.end(),
                                                   handler);
  EXPECT_TRUE(i == handlers_.end());
  if (i == handlers_.end())
    handlers_.push_back(handler);
}


static void init_sched_groups_power(int cpu, struct sched_domain *sd)
{
	struct sched_group *sg = sd->groups;

	WARN_ON(!sg);

	do {
		sg->group_weight = cpumask_weight(sched_group_cpus(sg));
		sg = sg->next;
	} while (sg != sd->groups);

	if (cpu != group_balance_cpu(sg))
		return;

	update_group_power(sd, cpu);
	atomic_set(&sg->sgp->nr_busy_cpus, sg->group_weight);
}


static char *append_newline(char *text, size_t len) {
    /* Try to append a newline; this is a big hack to work */
    /* around the fact that lenses generally break if the  */
    /* file does not end with a newline. */
    if (len == 0 || text[len-1] != '\n') {
        if (REALLOC_N(text, len+2) == 0) {
            text[len] = '\n';
            text[len+1] = '\0';
        }
    }
    return text;
}


static void cmp_and_merge_page(struct page *page, struct rmap_item *rmap_item)
{
	struct rmap_item *tree_rmap_item;
	struct page *tree_page = NULL;
	struct stable_node *stable_node;
	struct page *kpage;
	unsigned int checksum;
	int err;

	remove_rmap_item_from_tree(rmap_item);

	/* We first start with searching the page inside the stable tree */
	kpage = stable_tree_search(page);
	if (kpage) {
		err = try_to_merge_with_ksm_page(rmap_item, page, kpage);
		if (!err) {
			/*
			 * The page was successfully merged:
			 * add its rmap_item to the stable tree.
			 */
			lock_page(kpage);
			stable_tree_append(rmap_item, page_stable_node(kpage));
			unlock_page(kpage);
		}
		put_page(kpage);
		return;
	}

	/*
	 * If the hash value of the page has changed from the last time
	 * we calculated it, this page is changing frequently: therefore we
	 * don't want to insert it in the unstable tree, and we don't want
	 * to waste our time searching for something identical to it there.
	 */
	checksum = calc_checksum(page);
	if (rmap_item->oldchecksum != checksum) {
		rmap_item->oldchecksum = checksum;
		return;
	}

	tree_rmap_item =
		unstable_tree_search_insert(rmap_item, page, &tree_page);
	if (tree_rmap_item) {
		kpage = try_to_merge_two_pages(rmap_item, page,
						tree_rmap_item, tree_page);
		put_page(tree_page);
		/*
		 * As soon as we merge this page, we want to remove the
		 * rmap_item of the page we have merged with from the unstable
		 * tree, and insert it instead as new node in the stable tree.
		 */
		if (kpage) {
			remove_rmap_item_from_tree(tree_rmap_item);

			lock_page(kpage);
			stable_node = stable_tree_insert(kpage);
			if (stable_node) {
				stable_tree_append(tree_rmap_item, stable_node);
				stable_tree_append(rmap_item, stable_node);
			}
			unlock_page(kpage);

			/*
			 * If we fail to insert the page into the stable tree,
			 * we will have 2 virtual addresses that are pointing
			 * to a ksm page left outside the stable tree,
			 * in which case we need to break_cow on both.
			 */
			if (!stable_node) {
				break_cow(tree_rmap_item);
				break_cow(rmap_item);
			}
		}
	}
}


static int shmem_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
{
	int error;

	if ((error = shmem_mknod(dir, dentry, mode | S_IFDIR, 0)))
		return error;
	inc_nlink(dir);
	return 0;
}


sds *sdssplitlen(const char *s, ssize_t len, const char *sep, int seplen, int *count) {
    int elements = 0, slots = 5;
    long start = 0, j;
    sds *tokens;

    if (seplen < 1 || len < 0) return NULL;

    tokens = s_malloc(sizeof(sds)*slots);
    if (tokens == NULL) return NULL;

    if (len == 0) {
        *count = 0;
        return tokens;
    }
    for (j = 0; j < (len-(seplen-1)); j++) {
        /* make sure there is room for the next element and the final one */
        if (slots < elements+2) {
            sds *newtokens;

            slots *= 2;
            newtokens = s_realloc(tokens,sizeof(sds)*slots);
            if (newtokens == NULL) goto cleanup;
            tokens = newtokens;
        }
        /* search the separator */
        if ((seplen == 1 && *(s+j) == sep[0]) || (memcmp(s+j,sep,seplen) == 0)) {
            tokens[elements] = sdsnewlen(s+start,j-start);
            if (tokens[elements] == NULL) goto cleanup;
            elements++;
            start = j+seplen;
            j = j+seplen-1; /* skip the separator */
        }
    }
    /* Add the final element. We are sure there is room in the tokens array. */
    tokens[elements] = sdsnewlen(s+start,len-start);
    if (tokens[elements] == NULL) goto cleanup;
    elements++;
    *count = elements;
    return tokens;

cleanup:
    {
        int i;
        for (i = 0; i < elements; i++) sdsfree(tokens[i]);
        s_free(tokens);
        *count = 0;
        return NULL;
    }
}


TSAction TSCacheScan ( TSCont contp , TSCacheKey key , int KB_per_second ) {
 sdk_assert ( sdk_sanity_check_iocore_structure ( contp ) == TS_SUCCESS ) ;
 FORCE_PLUGIN_SCOPED_MUTEX ( contp ) ;
 INKContInternal * i = ( INKContInternal * ) contp ;
 if ( key ) {
 CacheInfo * info = ( CacheInfo * ) key ;
 return ( TSAction ) cacheProcessor . scan ( i , info -> hostname , info -> len , KB_per_second ) ;
 }
 return reinterpret_cast < TSAction > ( cacheProcessor . scan ( i , nullptr , 0 , KB_per_second ) ) ;
 }


bool Extension::LoadDescription(string16* error) {
  if (manifest_->HasKey(keys::kDescription) &&
      !manifest_->GetString(keys::kDescription, &description_)) {
    *error = ASCIIToUTF16(errors::kInvalidDescription);
    return false;
  }
  return true;
}


static int pfkey_spddelete(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
{
	struct net *net = sock_net(sk);
	int err;
	struct sadb_address *sa;
	struct sadb_x_policy *pol;
	struct xfrm_policy *xp;
	struct xfrm_selector sel;
	struct km_event c;
	struct sadb_x_sec_ctx *sec_ctx;
	struct xfrm_sec_ctx *pol_ctx = NULL;

	if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
				     ext_hdrs[SADB_EXT_ADDRESS_DST-1]) ||
	    !ext_hdrs[SADB_X_EXT_POLICY-1])
		return -EINVAL;

	pol = ext_hdrs[SADB_X_EXT_POLICY-1];
	if (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir >= IPSEC_DIR_MAX)
		return -EINVAL;

	memset(&sel, 0, sizeof(sel));

	sa = ext_hdrs[SADB_EXT_ADDRESS_SRC-1];
	sel.family = pfkey_sadb_addr2xfrm_addr(sa, &sel.saddr);
	sel.prefixlen_s = sa->sadb_address_prefixlen;
	sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
	sel.sport = ((struct sockaddr_in *)(sa+1))->sin_port;
	if (sel.sport)
		sel.sport_mask = htons(0xffff);

	sa = ext_hdrs[SADB_EXT_ADDRESS_DST-1];
	pfkey_sadb_addr2xfrm_addr(sa, &sel.daddr);
	sel.prefixlen_d = sa->sadb_address_prefixlen;
	sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
	sel.dport = ((struct sockaddr_in *)(sa+1))->sin_port;
	if (sel.dport)
		sel.dport_mask = htons(0xffff);

	sec_ctx = ext_hdrs[SADB_X_EXT_SEC_CTX - 1];
	if (sec_ctx != NULL) {
		struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx);

		if (!uctx)
			return -ENOMEM;

		err = security_xfrm_policy_alloc(&pol_ctx, uctx);
		kfree(uctx);
		if (err)
			return err;
	}

	xp = xfrm_policy_bysel_ctx(net, DUMMY_MARK, XFRM_POLICY_TYPE_MAIN,
				   pol->sadb_x_policy_dir - 1, &sel, pol_ctx,
				   1, &err);
	security_xfrm_policy_free(pol_ctx);
	if (xp == NULL)
		return -ENOENT;

	xfrm_audit_policy_delete(xp, err ? 0 : 1,
				 audit_get_loginuid(current),
				 audit_get_sessionid(current), 0);

	if (err)
		goto out;

	c.seq = hdr->sadb_msg_seq;
	c.portid = hdr->sadb_msg_pid;
	c.data.byid = 0;
	c.event = XFRM_MSG_DELPOLICY;
	km_policy_notify(xp, pol->sadb_x_policy_dir-1, &c);

out:
	xfrm_pol_put(xp);
	if (err == 0)
		xfrm_garbage_collect(net);
	return err;
}


bool ParseRequestInfo(const struct mg_request_info* const request_info,
                      std::string* method,
                      std::vector<std::string>* path_segments,
                      DictionaryValue** parameters,
                      Response* const response) {
  *method = request_info->request_method;
  if (*method == "HEAD")
    *method = "GET";
  else if (*method == "PUT")
    *method = "POST";

  std::string uri(request_info->uri);
  SessionManager* manager = SessionManager::GetInstance();
  uri = uri.substr(manager->url_base().length());

   base::SplitString(uri, '/', path_segments);

   if (*method == "POST" && request_info->post_data_len > 0) {
     std::string json(request_info->post_data, request_info->post_data_len);
    std::string error_msg;
    scoped_ptr<Value> params(base::JSONReader::ReadAndReturnError(
        json, true, NULL, &error_msg));
    if (!params.get()) {
       response->SetError(new Error(
           kBadRequest,
          "Failed to parse command data: " + error_msg + "\n  Data: " + json));
       return false;
     }
    if (!params->IsType(Value::TYPE_DICTIONARY)) {
      response->SetError(new Error(
          kBadRequest,
          "Data passed in URL must be a dictionary. Data: " + json));
      return false;
    }
    *parameters = static_cast<DictionaryValue*>(params.release());
   }
   return true;
 }


void RenderViewImpl::focusPrevious() {
  Send(new ViewHostMsg_TakeFocus(routing_id_, true));
}


void WebContentsImpl::EnsureOpenerProxiesExist(RenderFrameHost* source_rfh) {
  WebContentsImpl* source_web_contents = static_cast<WebContentsImpl*>(
      WebContents::FromRenderFrameHost(source_rfh));

  if (source_web_contents) {
    if (GetBrowserPluginEmbedder() &&
        GuestMode::IsCrossProcessFrameGuest(source_web_contents)) {
      return;
    }

    if (this != source_web_contents && GetBrowserPluginGuest()) {
      source_web_contents->GetRenderManager()->CreateRenderFrameProxy(
          GetSiteInstance());
    } else {
      RenderFrameHostImpl* source_rfhi =
          static_cast<RenderFrameHostImpl*>(source_rfh);
      source_rfhi->frame_tree_node()->render_manager()->CreateOpenerProxies(
          GetSiteInstance(), nullptr);
    }
  }
}


static int __init tun_init(void)
{
	int ret = 0;

	pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
	pr_info("%s\n", DRV_COPYRIGHT);

	ret = rtnl_link_register(&tun_link_ops);
	if (ret) {
		pr_err("Can't register link_ops\n");
		goto err_linkops;
	}

	ret = misc_register(&tun_miscdev);
	if (ret) {
		pr_err("Can't register misc device %d\n", TUN_MINOR);
		goto err_misc;
	}
	return  0;
err_misc:
	rtnl_link_unregister(&tun_link_ops);
err_linkops:
	return ret;
}


gpg_err_code_t _gcry_ecc_ecdsa_sign ( gcry_mpi_t input , ECC_secret_key * skey , gcry_mpi_t r , gcry_mpi_t s , int flags , int hashalgo ) {
 gpg_err_code_t rc = 0 ;
 int extraloops = 0 ;
 gcry_mpi_t k , dr , sum , k_1 , x ;
 mpi_point_struct I ;
 gcry_mpi_t hash ;
 const void * abuf ;
 unsigned int abits , qbits ;
 mpi_ec_t ctx ;
 if ( DBG_CIPHER ) log_mpidump ( "ecdsa sign hash " , input ) ;
 qbits = mpi_get_nbits ( skey -> E . n ) ;
 rc = _gcry_dsa_normalize_hash ( input , & hash , qbits ) ;
 if ( rc ) return rc ;
 k = NULL ;
 dr = mpi_alloc ( 0 ) ;
 sum = mpi_alloc ( 0 ) ;
 k_1 = mpi_alloc ( 0 ) ;
 x = mpi_alloc ( 0 ) ;
 point_init ( & I ) ;
 ctx = _gcry_mpi_ec_p_internal_new ( skey -> E . model , skey -> E . dialect , 0 , skey -> E . p , skey -> E . a , skey -> E . b ) ;
 do {
 do {
 mpi_free ( k ) ;
 k = NULL ;
 if ( ( flags & PUBKEY_FLAG_RFC6979 ) && hashalgo ) {
 if ( ! mpi_is_opaque ( input ) ) {
 rc = GPG_ERR_CONFLICT ;
 goto leave ;
 }
 abuf = mpi_get_opaque ( input , & abits ) ;
 rc = _gcry_dsa_gen_rfc6979_k ( & k , skey -> E . n , skey -> d , abuf , ( abits + 7 ) / 8 , hashalgo , extraloops ) ;
 if ( rc ) goto leave ;
 extraloops ++ ;
 }
 else k = _gcry_dsa_gen_k ( skey -> E . n , GCRY_STRONG_RANDOM ) ;
 _gcry_mpi_ec_mul_point ( & I , k , & skey -> E . G , ctx ) ;
 if ( _gcry_mpi_ec_get_affine ( x , NULL , & I , ctx ) ) {
 if ( DBG_CIPHER ) log_debug ( "ecc sign: Failed to get affine coordinates\n" ) ;
 rc = GPG_ERR_BAD_SIGNATURE ;
 goto leave ;
 }
 mpi_mod ( r , x , skey -> E . n ) ;
 }
 while ( ! mpi_cmp_ui ( r , 0 ) ) ;
 mpi_mulm ( dr , skey -> d , r , skey -> E . n ) ;
 mpi_addm ( sum , hash , dr , skey -> E . n ) ;
 mpi_invm ( k_1 , k , skey -> E . n ) ;
 mpi_mulm ( s , k_1 , sum , skey -> E . n ) ;
 }
 while ( ! mpi_cmp_ui ( s , 0 ) ) ;
 if ( DBG_CIPHER ) {
 log_mpidump ( "ecdsa sign result r " , r ) ;
 log_mpidump ( "ecdsa sign result s " , s ) ;
 }
 leave : _gcry_mpi_ec_free ( ctx ) ;
 point_free ( & I ) ;
 mpi_free ( x ) ;
 mpi_free ( k_1 ) ;
 mpi_free ( sum ) ;
 mpi_free ( dr ) ;
 mpi_free ( k ) ;
 if ( hash != input ) mpi_free ( hash ) ;
 return rc ;
 }


int MSADPCM::decodeBlock(const uint8_t *encoded, int16_t *decoded)
{
	ms_adpcm_state decoderState[2];
	ms_adpcm_state *state[2];

	int channelCount = m_track->f.channelCount;

	// Calculate the number of bytes needed for decoded data.
	int outputLength = m_framesPerPacket * sizeof (int16_t) * channelCount;

	state[0] = &decoderState[0];
	if (channelCount == 2)
		state[1] = &decoderState[1];
	else
		state[1] = &decoderState[0];

	// Initialize block predictor.
	for (int i=0; i<channelCount; i++)
	{
		state[i]->predictorIndex = *encoded++;
		assert(state[i]->predictorIndex < m_numCoefficients);
	}

	// Initialize delta.
	for (int i=0; i<channelCount; i++)
	{
		state[i]->delta = (encoded[1]<<8) | encoded[0];
		encoded += sizeof (uint16_t);
	}

	// Initialize first two samples.
	for (int i=0; i<channelCount; i++)
	{
		state[i]->sample1 = (encoded[1]<<8) | encoded[0];
		encoded += sizeof (uint16_t);
	}

	for (int i=0; i<channelCount; i++)
	{
		state[i]->sample2 = (encoded[1]<<8) | encoded[0];
		encoded += sizeof (uint16_t);
	}

	const int16_t *coefficient[2] =
	{
		m_coefficients[state[0]->predictorIndex],
		m_coefficients[state[1]->predictorIndex]
	};

	for (int i=0; i<channelCount; i++)
		*decoded++ = state[i]->sample2;

	for (int i=0; i<channelCount; i++)
		*decoded++ = state[i]->sample1;

	/*
		The first two samples have already been 'decoded' in
		the block header.
	*/
	int samplesRemaining = (m_framesPerPacket - 2) * m_track->f.channelCount;

	while (samplesRemaining > 0)
	{
		uint8_t code;
		int16_t newSample;
		bool ok;

		code = *encoded >> 4;
		newSample = decodeSample(*state[0], code, coefficient[0], &ok);
		if (!ok) return 0;
		*decoded++ = newSample;

		code = *encoded & 0x0f;
		newSample = decodeSample(*state[1], code, coefficient[1], &ok);
		if (!ok) return 0;
		*decoded++ = newSample;

		encoded++;
		samplesRemaining -= 2;
	}

	return outputLength;
}


ves_icall_System_Array_GetLongLength (MonoArray *this, gint32 dimension)
{
	gint32 rank = ((MonoObject *)this)->vtable->klass->rank;

	MONO_ARCH_SAVE_REGS;

	if ((dimension < 0) || (dimension >= rank))
		mono_raise_exception (mono_get_exception_index_out_of_range ());

	if (this->bounds == NULL)
 		return this->max_length;

 	return this->bounds [dimension].length;
}


jbig2_get_uint16(const byte *bptr)
{
    return get_uint16(bptr);
}


static int mig_save_device_bulk(Monitor *mon, QEMUFile *f,

                                BlkMigDevState *bmds)

{

    int64_t total_sectors = bmds->total_sectors;

    int64_t cur_sector = bmds->cur_sector;

    BlockDriverState *bs = bmds->bs;

    BlkMigBlock *blk;

    int nr_sectors;

    if (bmds->shared_base) {

        while (cur_sector < total_sectors &&

               !bdrv_is_allocated(bs, cur_sector, MAX_IS_ALLOCATED_SEARCH,

                                  &nr_sectors)) {

            cur_sector += nr_sectors;

        }

    }

    if (cur_sector >= total_sectors) {

        bmds->cur_sector = bmds->completed_sectors = total_sectors;

        return 1;

    }

    bmds->completed_sectors = cur_sector;

    cur_sector &= ~((int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK - 1);

    /* we are going to transfer a full block even if it is not allocated */

    nr_sectors = BDRV_SECTORS_PER_DIRTY_CHUNK;

    if (total_sectors - cur_sector < BDRV_SECTORS_PER_DIRTY_CHUNK) {

        nr_sectors = total_sectors - cur_sector;

    }

    blk = g_malloc(sizeof(BlkMigBlock));

    blk->buf = g_malloc(BLOCK_SIZE);

    blk->bmds = bmds;

    blk->sector = cur_sector;

    blk->nr_sectors = nr_sectors;

    blk->iov.iov_base = blk->buf;

    blk->iov.iov_len = nr_sectors * BDRV_SECTOR_SIZE;

    qemu_iovec_init_external(&blk->qiov, &blk->iov, 1);

    if (block_mig_state.submitted == 0) {

        block_mig_state.prev_time_offset = qemu_get_clock_ns(rt_clock);

    }

    blk->aiocb = bdrv_aio_readv(bs, cur_sector, &blk->qiov,

                                nr_sectors, blk_mig_read_cb, blk);

    block_mig_state.submitted++;

    bdrv_reset_dirty(bs, cur_sector, nr_sectors);

    bmds->cur_sector = cur_sector + nr_sectors;

    return (bmds->cur_sector >= total_sectors);

}


give_warning2(char_u *message, char_u *a1, int hl)
{
    if (IObuff == NULL)
    {
	// Very early in initialisation and already something wrong, just give
	// the raw message so the user at least gets a hint.
	give_warning((char_u *)message, hl);
    }
    else
    {
	vim_snprintf((char *)IObuff, IOSIZE, (char *)message, a1);
	give_warning(IObuff, hl);
    }
}


 void MakeUsernameForAccount(const base::DictionaryValue* result,
                             base::string16* gaia_id,
                             wchar_t* username,
                             DWORD username_length,
                             wchar_t* domain,
                             DWORD domain_length,
                             wchar_t* sid,
                            DWORD sid_length,
                            bool* is_consumer_account) {
   DCHECK(gaia_id);
   DCHECK(username);
   DCHECK(domain);
   DCHECK(sid);
  DCHECK(is_consumer_account);

  // Determine if the email is a consumer domain (gmail.com or googlemail.com).
  base::string16 email = GetDictString(result, kKeyEmail);
  std::transform(email.begin(), email.end(), email.begin(), ::tolower);
  base::string16::size_type consumer_domain_pos = email.find(L"@gmail.com");
  if (consumer_domain_pos == base::string16::npos)
    consumer_domain_pos = email.find(L"@googlemail.com");

  *is_consumer_account = consumer_domain_pos != base::string16::npos;

   *gaia_id = GetDictString(result, kKeyId);
  HRESULT hr = GetSidFromId(*gaia_id, sid, sid_length);
  if (SUCCEEDED(hr)) {
    hr = OSUserManager::Get()->FindUserBySID(sid, username, username_length,
                                             domain, domain_length);
    if (SUCCEEDED(hr))
      return;
  }
  LOGFN(INFO) << "No existing user found associated to gaia id:" << *gaia_id;
  wcscpy_s(domain, domain_length, OSUserManager::GetLocalDomain().c_str());
  username[0] = 0;
  sid[0] = 0;

  base::string16 os_username = email;

  // If the email is a consumer domain, strip it.
  if (consumer_domain_pos != base::string16::npos) {
    os_username.resize(consumer_domain_pos);
   } else {
     std::string username_utf8 =
        gaia::SanitizeEmail(base::UTF16ToUTF8(os_username));

    size_t tld_length =
        net::registry_controlled_domains::GetCanonicalHostRegistryLength(
            gaia::ExtractDomainName(username_utf8),
            net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES,
            net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);

    if (tld_length > 0) {
      username_utf8.resize(username_utf8.length() - tld_length - 1);
      os_username = base::UTF8ToUTF16(username_utf8);
    }
  }

  if (os_username.size() > kWindowsUsernameBufferLength - 1)
    os_username.resize(kWindowsUsernameBufferLength - 1);

  for (auto& c : os_username) {
    if (wcschr(L"@\\[]:|<>+=;?*", c) != nullptr || c < 32)
      c = L'_';
  }

  wcscpy_s(username, username_length, os_username.c_str());
}


f_screenpos(typval_T *argvars UNUSED, typval_T *rettv)
{
    dict_T	*dict;
    win_T	*wp;
    pos_T	pos;
    int		row = 0;
    int		scol = 0, ccol = 0, ecol = 0;

    if (rettv_dict_alloc(rettv) != OK)
	return;
    dict = rettv->vval.v_dict;

    if (in_vim9script()
	    && (check_for_number_arg(argvars, 0) == FAIL
		|| check_for_number_arg(argvars, 1) == FAIL
		|| check_for_number_arg(argvars, 2) == FAIL))
	return;

    wp = find_win_by_nr_or_id(&argvars[0]);
    if (wp == NULL)
	return;

    pos.lnum = tv_get_number(&argvars[1]);
    pos.col = tv_get_number(&argvars[2]) - 1;
    pos.coladd = 0;
    textpos2screenpos(wp, &pos, &row, &scol, &ccol, &ecol);

    dict_add_number(dict, "row", row);
    dict_add_number(dict, "col", scol);
    dict_add_number(dict, "curscol", ccol);
    dict_add_number(dict, "endcol", ecol);
}


base::android::ScopedJavaLocalRef<jbyteArray> AwContents::GetCertificate(
    JNIEnv* env,
    jobject obj) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  content::NavigationEntry* entry =
      web_contents_->GetController().GetLastCommittedEntry();
  if (!entry)
    return ScopedJavaLocalRef<jbyteArray>();
  int cert_id = entry->GetSSL().cert_id;
  scoped_refptr<net::X509Certificate> cert;
  bool ok = content::CertStore::GetInstance()->RetrieveCert(cert_id, &cert);
  if (!ok)
    return ScopedJavaLocalRef<jbyteArray>();

  std::string der_string;
  net::X509Certificate::GetDEREncoded(cert->os_cert_handle(), &der_string);
  return base::android::ToJavaByteArray(env,
      reinterpret_cast<const uint8*>(der_string.data()), der_string.length());
}


int tls_get_message_header(SSL *s, int *mt)
{
    /* s->init_num < SSL3_HM_HEADER_LENGTH */
    int skip_message, i, recvd_type, al;
    unsigned char *p;
    unsigned long l;

    p = (unsigned char *)s->init_buf->data;

    do {
        while (s->init_num < SSL3_HM_HEADER_LENGTH) {
            i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type,
                                          &p[s->init_num],
                                          SSL3_HM_HEADER_LENGTH - s->init_num,
                                          0);
            if (i <= 0) {
                s->rwstate = SSL_READING;
                return 0;
            }
            if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
                /*
                 * A ChangeCipherSpec must be a single byte and may not occur
                 * in the middle of a handshake message.
                 */
                if (s->init_num != 0 || i != 1 || p[0] != SSL3_MT_CCS) {
                    al = SSL_AD_UNEXPECTED_MESSAGE;
                    SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER,
                           SSL_R_BAD_CHANGE_CIPHER_SPEC);
                    goto f_err;
                }
                s->s3->tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
                s->init_num = i - 1;
                s->s3->tmp.message_size = i;
                return 1;
            } else if (recvd_type != SSL3_RT_HANDSHAKE) {
                al = SSL_AD_UNEXPECTED_MESSAGE;
                SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_CCS_RECEIVED_EARLY);
                goto f_err;
            }
            s->init_num += i;
        }

        skip_message = 0;
        if (!s->server)
            if (p[0] == SSL3_MT_HELLO_REQUEST)
                /*
                 * The server may always send 'Hello Request' messages --
                 * we are doing a handshake anyway now, so ignore them if
                 * their format is correct. Does not count for 'Finished'
                 * MAC.
                 */
                if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
                    s->init_num = 0;
                    skip_message = 1;

                    if (s->msg_callback)
                        s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
                                        p, SSL3_HM_HEADER_LENGTH, s,
                                        s->msg_callback_arg);
                }
    } while (skip_message);
    /* s->init_num == SSL3_HM_HEADER_LENGTH */

    *mt = *p;
    s->s3->tmp.message_type = *(p++);

    if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
        /*
         * Only happens with SSLv3+ in an SSLv2 backward compatible
         * ClientHello
         *
         * Total message size is the remaining record bytes to read
         * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
         */
        l = RECORD_LAYER_get_rrec_length(&s->rlayer)
            + SSL3_HM_HEADER_LENGTH;
        if (l && !BUF_MEM_grow_clean(s->init_buf, (int)l)) {
            SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, ERR_R_BUF_LIB);
            goto err;
        }
        s->s3->tmp.message_size = l;

        s->init_msg = s->init_buf->data;
        s->init_num = SSL3_HM_HEADER_LENGTH;
    } else {
        n2l3(p, l);
        /* BUF_MEM_grow takes an 'int' parameter */
        if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
            al = SSL_AD_ILLEGAL_PARAMETER;
            SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
            goto f_err;
        }
        if (l && !BUF_MEM_grow_clean(s->init_buf,
                                     (int)l + SSL3_HM_HEADER_LENGTH)) {
            SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, ERR_R_BUF_LIB);
            goto err;
        }
        s->s3->tmp.message_size = l;

        s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
        s->init_num = 0;
    }

    return 1;
 f_err:
    ssl3_send_alert(s, SSL3_AL_FATAL, al);
 err:
    return 0;
}


static DownloadManager* DownloadManagerForBrowser(Browser* browser) {
  return BrowserContext::GetDownloadManager(browser->profile());
}


void TextAutosizer::setMultiplier(RenderObject* renderer, float multiplier)
{
    RefPtr<RenderStyle> newStyle = RenderStyle::clone(renderer->style());
    newStyle->setTextAutosizingMultiplier(multiplier);
    renderer->setStyle(newStyle.release());
}


static void bt_hid_interrupt_sdu(void *opaque, const uint8_t *data, int len)

{

    struct bt_hid_device_s *hid = opaque;

    if (len > BT_HID_MTU || len < 1)

        goto bad;

    if ((data[0] & 3) != BT_DATA_OUTPUT)

        goto bad;

    if ((data[0] >> 4) == BT_DATA) {

        if (hid->intr_state)

            goto bad;

        hid->data_type = BT_DATA_OUTPUT;

        hid->intrdataout.len = 0;

    } else if ((data[0] >> 4) == BT_DATC) {

        if (!hid->intr_state)

            goto bad;

    } else

        goto bad;

    memcpy(hid->intrdataout.buffer + hid->intrdataout.len, data + 1, len - 1);

    hid->intrdataout.len += len - 1;

    hid->intr_state = (len == BT_HID_MTU);

    if (!hid->intr_state) {

        memcpy(hid->dataout.buffer, hid->intrdataout.buffer,

                        hid->dataout.len = hid->intrdataout.len);

        bt_hid_out(hid);

    }

    return;

bad:

    fprintf(stderr, "%s: bad transaction on Interrupt channel.\n",

                    __func__);

}


cmsTagTypeSignature DecideLUTtypeB2A(cmsFloat64Number ICCVersion, const void *Data)
{
    cmsPipeline* Lut = (cmsPipeline*) Data;

    if (ICCVersion < 4.0) {
        if (Lut ->SaveAs8Bits) return cmsSigLut8Type;
        return cmsSigLut16Type;
    }
    else {
         return cmsSigLutBtoAType;
    }
}


static int replace ( DYNAMIC_STRING * ds_str , const char * search_str , ulong search_len , const char * replace_str , ulong replace_len ) {
 DYNAMIC_STRING ds_tmp ;
 const char * start = strstr ( ds_str -> str , search_str ) ;
 if ( ! start ) return 1 ;
 init_dynamic_string ( & ds_tmp , "" , ds_str -> length + replace_len , 256 ) ;
 dynstr_append_mem ( & ds_tmp , ds_str -> str , start - ds_str -> str ) ;
 dynstr_append_mem ( & ds_tmp , replace_str , replace_len ) ;
 dynstr_append ( & ds_tmp , start + search_len ) ;
 dynstr_set ( ds_str , ds_tmp . str ) ;
 dynstr_free ( & ds_tmp ) ;
 return 0 ;
 }


static PHP_INI_MH(OnUpdateTransSid) /* {{{ */
{
	SESSION_CHECK_ACTIVE_STATE;

	if (!strncasecmp(new_value, "on", sizeof("on"))) {
		PS(use_trans_sid) = (zend_bool) 1;
	} else {
		PS(use_trans_sid) = (zend_bool) atoi(new_value);
	}

	return SUCCESS;
}


void ProfileSyncService::OnBackendInitialized(
    const WeakHandle<JsBackend>& js_backend, bool success) {
  if (!HasSyncSetupCompleted()) {
    UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeFirstTimeSuccess", success);
  } else {
    UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeRestoreSuccess", success);
  }

  if (!success) {
    OnUnrecoverableErrorImpl(FROM_HERE, "BackendInitialize failure", false);
    return;
  }

  backend_initialized_ = true;

  sync_js_controller_.AttachJsBackend(js_backend);

  ConsumeCachedPassphraseIfPossible();

  if (last_synced_time_.is_null()) {
    UpdateLastSyncedTime();
  }
  NotifyObservers();

  if (auto_start_enabled_ && !FirstSetupInProgress()) {
    SetSyncSetupCompleted();
    NotifyObservers();
  }

  if (HasSyncSetupCompleted()) {
    ConfigureDataTypeManager();
  } else {
    DCHECK(FirstSetupInProgress());
  }
}


format_NAT(const struct ofpact_nat *a, struct ds *ds)
{
    ds_put_format(ds, "%snat%s", colors.paren, colors.end);

    if (a->flags & (NX_NAT_F_SRC | NX_NAT_F_DST)) {
        ds_put_format(ds, "%s(%s", colors.paren, colors.end);
        ds_put_format(ds, a->flags & NX_NAT_F_SRC ? "%ssrc%s" : "%sdst%s",
                      colors.param, colors.end);

        if (a->range_af != AF_UNSPEC) {
            ds_put_format(ds, "%s=%s", colors.param, colors.end);

            if (a->range_af == AF_INET) {
                ds_put_format(ds, IP_FMT, IP_ARGS(a->range.addr.ipv4.min));

                if (a->range.addr.ipv4.max
                    && a->range.addr.ipv4.max != a->range.addr.ipv4.min) {
                    ds_put_format(ds, "-"IP_FMT,
                                  IP_ARGS(a->range.addr.ipv4.max));
                }
            } else if (a->range_af == AF_INET6) {
                ipv6_format_addr_bracket(&a->range.addr.ipv6.min, ds,
                                        a->range.proto.min);

                if (!ipv6_mask_is_any(&a->range.addr.ipv6.max)
                    && memcmp(&a->range.addr.ipv6.max, &a->range.addr.ipv6.min,
                              sizeof(struct in6_addr)) != 0) {
                    ds_put_char(ds, '-');
                    ipv6_format_addr_bracket(&a->range.addr.ipv6.max, ds,
                                            a->range.proto.min);
                }
            }
            if (a->range.proto.min) {
                ds_put_char(ds, ':');
                ds_put_format(ds, "%"PRIu16, a->range.proto.min);

                if (a->range.proto.max
                    && a->range.proto.max != a->range.proto.min) {
                    ds_put_format(ds, "-%"PRIu16, a->range.proto.max);
                }
            }
            ds_put_char(ds, ',');

            if (a->flags & NX_NAT_F_PERSISTENT) {
                ds_put_format(ds, "%spersistent%s,",
                              colors.value, colors.end);
            }
            if (a->flags & NX_NAT_F_PROTO_HASH) {
                ds_put_format(ds, "%shash%s,", colors.value, colors.end);
            }
            if (a->flags & NX_NAT_F_PROTO_RANDOM) {
                ds_put_format(ds, "%srandom%s,", colors.value, colors.end);
            }
        }
        ds_chomp(ds, ',');
        ds_put_format(ds, "%s)%s", colors.paren, colors.end);
    }
}


softusb_write(void *opaque, target_phys_addr_t addr, uint64_t value,

              unsigned size)

{

    MilkymistSoftUsbState *s = opaque;

    trace_milkymist_softusb_memory_write(addr, value);

    addr >>= 2;

    switch (addr) {

    case R_CTRL:

        s->regs[addr] = value;

        break;

    default:

        error_report("milkymist_softusb: write access to unknown register 0x"

                TARGET_FMT_plx, addr << 2);

        break;

    }

}


void helper_store_fpcr (uint64_t val)

{

#ifdef CONFIG_SOFTFLOAT

    set_float_exception_flags((val >> 52) & 0x3F, &FP_STATUS);

#endif

    switch ((val >> 58) & 3) {

    case 0:

        set_float_rounding_mode(float_round_to_zero, &FP_STATUS);

        break;

    case 1:

        set_float_rounding_mode(float_round_down, &FP_STATUS);

        break;

    case 2:

        set_float_rounding_mode(float_round_nearest_even, &FP_STATUS);

        break;

    case 3:

        set_float_rounding_mode(float_round_up, &FP_STATUS);

        break;

    }

}


static void unkeep_all_packs(void)
{
	static char name[PATH_MAX];
	int k;

	for (k = 0; k < pack_id; k++) {
		struct packed_git *p = all_packs[k];
		snprintf(name, sizeof(name), "%s/pack/pack-%s.keep",
			 get_object_directory(), sha1_to_hex(p->sha1));
		unlink_or_warn(name);
	}
}


void WebPagePrivate::enterFullScreenForElement(Element* element)
{
#if ENABLE(VIDEO)
    if (!element || (!element->hasTagName(HTMLNames::videoTag) && !containsVideoTags(element)))
        return;
    if (m_webSettings->fullScreenVideoCapable()) {
        enterFullscreenForNode(element);
    } else {
        if (transformedActualVisibleSize() != transformedViewportSize()) {
            m_scaleBeforeFullScreen = currentScale();

            m_scrollPositionBeforeFullScreen = m_mainFrame->view()->scrollPosition();
        }

        client()->fullscreenStart();
        m_fullscreenVideoNode = element;
    }
#endif
}


static int ext4_write_begin(struct file *file, struct address_space *mapping,
			    loff_t pos, unsigned len, unsigned flags,
			    struct page **pagep, void **fsdata)
{
	struct inode *inode = mapping->host;
	int ret, needed_blocks;
	handle_t *handle;
	int retries = 0;
	struct page *page;
	pgoff_t index;
	unsigned from, to;

	trace_ext4_write_begin(inode, pos, len, flags);
	/*
	 * Reserve one block more for addition to orphan list in case
	 * we allocate blocks but write fails for some reason
	 */
	needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
	index = pos >> PAGE_CACHE_SHIFT;
	from = pos & (PAGE_CACHE_SIZE - 1);
	to = from + len;

retry:
	handle = ext4_journal_start(inode, needed_blocks);
	if (IS_ERR(handle)) {
		ret = PTR_ERR(handle);
		goto out;
	}

	/* We cannot recurse into the filesystem as the transaction is already
	 * started */
	flags |= AOP_FLAG_NOFS;

	page = grab_cache_page_write_begin(mapping, index, flags);
	if (!page) {
		ext4_journal_stop(handle);
		ret = -ENOMEM;
		goto out;
	}
	*pagep = page;

	if (ext4_should_dioread_nolock(inode))
		ret = block_write_begin(file, mapping, pos, len, flags, pagep,
				fsdata, ext4_get_block_write);
	else
		ret = block_write_begin(file, mapping, pos, len, flags, pagep,
				fsdata, ext4_get_block);

	if (!ret && ext4_should_journal_data(inode)) {
		ret = walk_page_buffers(handle, page_buffers(page),
				from, to, NULL, do_journal_get_write_access);
	}

	if (ret) {
		unlock_page(page);
		page_cache_release(page);
		/*
		 * block_write_begin may have instantiated a few blocks
		 * outside i_size.  Trim these off again. Don't need
		 * i_size_read because we hold i_mutex.
		 *
		 * Add inode to orphan list in case we crash before
		 * truncate finishes
		 */
		if (pos + len > inode->i_size && ext4_can_truncate(inode))
			ext4_orphan_add(handle, inode);

		ext4_journal_stop(handle);
		if (pos + len > inode->i_size) {
			ext4_truncate_failed_write(inode);
			/*
			 * If truncate failed early the inode might
			 * still be on the orphan list; we need to
			 * make sure the inode is removed from the
			 * orphan list in that case.
			 */
			if (inode->i_nlink)
				ext4_orphan_del(NULL, inode);
		}
	}

	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
		goto retry;
out:
	return ret;
}


void HTTP2Codec::generateContinuation(folly::IOBufQueue& writeBuf,
                                      folly::IOBufQueue& queue,
                                      StreamID stream,
                                      size_t maxFrameSize) {
  bool endHeaders = false;
  while (!endHeaders) {
    auto chunk = queue.split(std::min(maxFrameSize, queue.chainLength()));
    endHeaders = (queue.chainLength() == 0);
    VLOG(4) << "generating CONTINUATION for stream=" << stream;
    generateHeaderCallbackWrapper(
        stream,
        http2::FrameType::CONTINUATION,
        http2::writeContinuation(
            writeBuf, stream, endHeaders, std::move(chunk)));
  }
}


static char *load_text_file(const char *path, unsigned flags)
{
    int fd = open(path, O_RDONLY | ((flags & DD_OPEN_FOLLOW) ? 0 : O_NOFOLLOW));
    if (fd == -1)
    {
        if (!(flags & DD_FAIL_QUIETLY_ENOENT))
            perror_msg("Can't open file '%s'", path);
        return (flags & DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE ? NULL : xstrdup(""));
    }

    /* Why? Because half a million read syscalls of one byte each isn't fun.
     * FILE-based IO buffers reads.
     */
    FILE *fp = fdopen(fd, "r");
    if (!fp)
        die_out_of_memory();

    struct strbuf *buf_content = strbuf_new();
    int oneline = 0;
    int ch;
    while ((ch = fgetc(fp)) != EOF)
    {
//TODO? \r -> \n?
//TODO? strip trailing spaces/tabs?
        if (ch == '\n')
            oneline = (oneline << 1) | 1;
        if (ch == '\0')
            ch = ' ';
        if (isspace(ch) || ch >= ' ') /* used !iscntrl, but it failed on unicode */
            strbuf_append_char(buf_content, ch);
    }
    fclose(fp); /* this also closes fd */

    char last = oneline != 0 ? buf_content->buf[buf_content->len - 1] : 0;
    if (last == '\n')
    {
        /* If file contains exactly one '\n' and it is at the end, remove it.
         * This enables users to use simple "echo blah >file" in order to create
         * short string items in dump dirs.
         */
        if (oneline == 1)
            buf_content->buf[--buf_content->len] = '\0';
    }
    else /* last != '\n' */
    {
        /* Last line is unterminated, fix it */
        /* Cases: */
        /* oneline=0: "qwe" - DONT fix this! */
        /* oneline=1: "qwe\nrty" - two lines in fact */
        /* oneline>1: "qwe\nrty\uio" */
        if (oneline >= 1)
            strbuf_append_char(buf_content, '\n');
    }

    return strbuf_free_nobuf(buf_content);
}


static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
                                             unsigned len, const char *key)
{
    char buf[16];

    short current, total = 0;
    avio_rb16(pb); // unknown
    current = avio_rb16(pb);
    if (len >= 6)
        total = avio_rb16(pb);
    if (!total)
        snprintf(buf, sizeof(buf), "%d", current);
    else
        snprintf(buf, sizeof(buf), "%d/%d", current, total);
    c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
    av_dict_set(&c->fc->metadata, key, buf, 0);

    return 0;
}


static int kvm_irqchip_get_virq(KVMState *s)

{

    uint32_t *word = s->used_gsi_bitmap;

    int max_words = ALIGN(s->gsi_count, 32) / 32;

    int i, bit;

    bool retry = true;

again:

    /* Return the lowest unused GSI in the bitmap */

    for (i = 0; i < max_words; i++) {

        bit = ffs(~word[i]);

        if (!bit) {

            continue;

        }

        return bit - 1 + i * 32;

    }

    if (retry) {

        retry = false;

        kvm_flush_dynamic_msi_routes(s);

        goto again;

    }

    return -ENOSPC;

}


WebString WebLocalFrameImpl::SelectionAsText() const {
  DCHECK(GetFrame());
  WebPluginContainerImpl* plugin_container =
      GetFrame()->GetWebPluginContainer();
  if (plugin_container)
    return plugin_container->Plugin()->SelectionAsText();

  GetFrame()->GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets();

  String text = GetFrame()->Selection().SelectedText(
      TextIteratorBehavior::EmitsObjectReplacementCharacterBehavior());
#if defined(OS_WIN)
  ReplaceNewlinesWithWindowsStyleNewlines(text);
#endif
  ReplaceNBSPWithSpace(text);
  return text;
}


TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
  TFLITE_DCHECK(node->user_data != nullptr);
  OpData* data = static_cast<OpData*>(node->user_data);

  const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
  const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);

  if (input1->type == kTfLiteUInt8 || input1->type == kTfLiteInt8) {
    auto input1_offset = -input1->params.zero_point;
    auto input2_offset = -input2->params.zero_point;
    const int kLeftShift = 8;

    int32_t input1_multiplier;
    int input1_shift;
    QuantizeMultiplierSmallerThanOneExp(
        static_cast<double>(input1->params.scale), &input1_multiplier,
        &input1_shift);
    int32_t input2_multiplier;
    int input2_shift;
    QuantizeMultiplierSmallerThanOneExp(
        static_cast<double>(input2->params.scale), &input2_multiplier,
        &input2_shift);

    data->params.left_shift = kLeftShift;
    data->params.input1_offset = input1_offset;
    data->params.input1_multiplier = input1_multiplier;
    data->params.input1_shift = input1_shift;
    data->params.input2_offset = input2_offset;
    data->params.input2_multiplier = input2_multiplier;
    data->params.input2_shift = input2_shift;
  }

  return kTfLiteOk;
}


net::Error NavigationRequest::CheckContentSecurityPolicy(
    bool has_followed_redirect,
    bool url_upgraded_after_redirect,
    bool is_response_check) {
  if (common_params_.url.SchemeIs(url::kAboutScheme))
    return net::OK;

  if (common_params_.initiator_csp_info.should_check_main_world_csp ==
      CSPDisposition::DO_NOT_CHECK) {
    return net::OK;
  }

  FrameTreeNode* parent_ftn = frame_tree_node()->parent();
  RenderFrameHostImpl* parent =
      parent_ftn ? parent_ftn->current_frame_host() : nullptr;

  initiator_csp_context_->SetReportingRenderFrameHost(
      frame_tree_node()->current_frame_host());

  net::Error report_only_csp_status = CheckCSPDirectives(
      parent, has_followed_redirect, url_upgraded_after_redirect,
      is_response_check, CSPContext::CHECK_REPORT_ONLY_CSP);

  if (!has_followed_redirect && !frame_tree_node()->IsMainFrame()) {
    if (parent &&
        parent->ShouldModifyRequestUrlForCsp(true /* is subresource */)) {
      upgrade_if_insecure_ = true;
      parent->ModifyRequestUrlForCsp(&common_params_.url);
      commit_params_.original_url = common_params_.url;
    }
  }

  net::Error enforced_csp_status = CheckCSPDirectives(
      parent, has_followed_redirect, url_upgraded_after_redirect,
      is_response_check, CSPContext::CHECK_ENFORCED_CSP);
  if (enforced_csp_status != net::OK)
    return enforced_csp_status;
  return report_only_csp_status;
}


static void cpu_x86_dump_state(FILE *f)

{

    int eflags;

    char cc_op_name[32];

    eflags = cc_table[CC_OP].compute_all();

    eflags |= (DF & DF_MASK);

    if ((unsigned)env->cc_op < CC_OP_NB)

        strcpy(cc_op_name, cc_op_str[env->cc_op]);

    else

        snprintf(cc_op_name, sizeof(cc_op_name), "[%d]", env->cc_op);

    fprintf(f,

            "EAX=%08x EBX=%08X ECX=%08x EDX=%08x\n"

            "ESI=%08x EDI=%08X EBP=%08x ESP=%08x\n"

            "CCS=%08x CCD=%08x CCO=%-8s EFL=%c%c%c%c%c%c%c\n"

            "EIP=%08x\n",

            env->regs[R_EAX], env->regs[R_EBX], env->regs[R_ECX], env->regs[R_EDX],

            env->regs[R_ESI], env->regs[R_EDI], env->regs[R_EBP], env->regs[R_ESP],

            env->cc_src, env->cc_dst, cc_op_name,

            eflags & DF_MASK ? 'D' : '-',

            eflags & CC_O ? 'O' : '-',

            eflags & CC_S ? 'S' : '-',

            eflags & CC_Z ? 'Z' : '-',

            eflags & CC_A ? 'A' : '-',

            eflags & CC_P ? 'P' : '-',

            eflags & CC_C ? 'C' : '-',

            env->eip);

#if 1

    fprintf(f, "ST0=%f ST1=%f ST2=%f ST3=%f\n",

            (double)ST0, (double)ST1, (double)ST(2), (double)ST(3));

#endif

}