text:
package trademark

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// InsertTmMonitorRule invokes the trademark.InsertTmMonitorRule API synchronously
// api document: https://help.aliyun.com/api/trademark/inserttmmonitorrule.html
func (client *Client) InsertTmMonitorRule(request *InsertTmMonitorRuleRequest) (response *InsertTmMonitorRuleResponse, err error) {
	response = CreateInsertTmMonitorRuleResponse()
	err = client.DoAction(request, response)
	return
}

// InsertTmMonitorRuleWithChan invokes the trademark.InsertTmMonitorRule API asynchronously
// api document: https://help.aliyun.com/api/trademark/inserttmmonitorrule.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) InsertTmMonitorRuleWithChan(request *InsertTmMonitorRuleRequest) (<-chan *InsertTmMonitorRuleResponse, <-chan error) {
	responseChan := make(chan *InsertTmMonitorRuleResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.InsertTmMonitorRule(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// InsertTmMonitorRuleWithCallback invokes the trademark.InsertTmMonitorRule API asynchronously
// api document: https://help.aliyun.com/api/trademark/inserttmmonitorrule.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) InsertTmMonitorRuleWithCallback(request *InsertTmMonitorRuleRequest, callback func(response *InsertTmMonitorRuleResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *InsertTmMonitorRuleResponse
		var err error
		defer close(result)
		response, err = client.InsertTmMonitorRule(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// InsertTmMonitorRuleRequest is the request struct for api InsertTmMonitorRule
type InsertTmMonitorRuleRequest struct {
	*requests.RpcRequest
	StartApplyDate string           `position:"Query" name:"StartApplyDate"`
	NotifyStatus   string           `position:"Query" name:"NotifyStatus"`
	RuleType       requests.Integer `position:"Query" name:"RuleType"`
	RuleSource     string           `position:"Query" name:"RuleSource"`
	RuleName       string           `position:"Query" name:"RuleName"`
	EndApplyDate   string           `position:"Query" name:"EndApplyDate"`
	Classification string           `position:"Query" name:"Classification"`
	RuleKeyword    string           `position:"Query" name:"RuleKeyword"`
}

// InsertTmMonitorRuleResponse is the response struct for api InsertTmMonitorRule
type InsertTmMonitorRuleResponse struct {
	*responses.BaseResponse
	RequestId string `json:"RequestId" xml:"RequestId"`
	Success   bool   `json:"Success" xml:"Success"`
	ErrorMsg  string `json:"ErrorMsg" xml:"ErrorMsg"`
	ErrorCode string `json:"ErrorCode" xml:"ErrorCode"`
}

// CreateInsertTmMonitorRuleRequest creates a request to invoke InsertTmMonitorRule API
func CreateInsertTmMonitorRuleRequest() (request *InsertTmMonitorRuleRequest) {
	request = &InsertTmMonitorRuleRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("Trademark", "2018-07-24", "InsertTmMonitorRule", "trademark", "openAPI")
	return
}

// CreateInsertTmMonitorRuleResponse creates a response to parse from InsertTmMonitorRule response
func CreateInsertTmMonitorRuleResponse() (response *InsertTmMonitorRuleResponse) {
	response = &InsertTmMonitorRuleResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
namespace spvtools {
namespace opt {

uint32_t InstBuffAddrCheckPass::CloneOriginalReference(
    Instruction* ref_inst, InstructionBuilder* builder) {
  // Clone original ref with new result id (if load)
  assert(
      (ref_inst->opcode() == SpvOpLoad || ref_inst->opcode() == SpvOpStore) &&
      "unexpected ref");
  std::unique_ptr<Instruction> new_ref_inst(ref_inst->Clone(context()));
  uint32_t ref_result_id = ref_inst->result_id();
  uint32_t new_ref_id = 0;
  if (ref_result_id != 0) {
    new_ref_id = TakeNextId();
    new_ref_inst->SetResultId(new_ref_id);
  }
  // Register new reference and add to new block
  Instruction* added_inst = builder->AddInstruction(std::move(new_ref_inst));
  uid2offset_[added_inst->unique_id()] = uid2offset_[ref_inst->unique_id()];
  if (new_ref_id != 0)
    get_decoration_mgr()->CloneDecorations(ref_result_id, new_ref_id);
  return new_ref_id;
}

bool InstBuffAddrCheckPass::IsPhysicalBuffAddrReference(Instruction* ref_inst) {
  if (ref_inst->opcode() != SpvOpLoad && ref_inst->opcode() != SpvOpStore)
    return false;
  uint32_t ptr_id = ref_inst->GetSingleWordInOperand(0);
  analysis::DefUseManager* du_mgr = get_def_use_mgr();
  Instruction* ptr_inst = du_mgr->GetDef(ptr_id);
  if (ptr_inst->opcode() != SpvOpAccessChain) return false;
  uint32_t ptr_ty_id = ptr_inst->type_id();
  Instruction* ptr_ty_inst = du_mgr->GetDef(ptr_ty_id);
  if (ptr_ty_inst->GetSingleWordInOperand(0) !=
      SpvStorageClassPhysicalStorageBufferEXT)
    return false;
  return true;
}

// TODO(greg-lunarg): Refactor with InstBindlessCheckPass::GenCheckCode() ??
void InstBuffAddrCheckPass::GenCheckCode(
    uint32_t check_id, uint32_t error_id, uint32_t ref_uptr_id,
    uint32_t stage_idx, Instruction* ref_inst,
    std::vector<std::unique_ptr<BasicBlock>>* new_blocks) {
  BasicBlock* back_blk_ptr = &*new_blocks->back();
  InstructionBuilder builder(
      context(), back_blk_ptr,
      IRContext::kAnalysisDefUse | IRContext::kAnalysisInstrToBlockMapping);
  // Gen conditional branch on check_id. Valid branch generates original
  // reference. Invalid generates debug output and zero result (if needed).
  uint32_t merge_blk_id = TakeNextId();
  uint32_t valid_blk_id = TakeNextId();
  uint32_t invalid_blk_id = TakeNextId();
  std::unique_ptr<Instruction> merge_label(NewLabel(merge_blk_id));
  std::unique_ptr<Instruction> valid_label(NewLabel(valid_blk_id));
  std::unique_ptr<Instruction> invalid_label(NewLabel(invalid_blk_id));
  (void)builder.AddConditionalBranch(check_id, valid_blk_id, invalid_blk_id,
                                     merge_blk_id, SpvSelectionControlMaskNone);
  // Gen valid branch
  std::unique_ptr<BasicBlock> new_blk_ptr(
      new BasicBlock(std::move(valid_label)));
  builder.SetInsertPoint(&*new_blk_ptr);
  uint32_t new_ref_id = CloneOriginalReference(ref_inst, &builder);
  (void)builder.AddBranch(merge_blk_id);
  new_blocks->push_back(std::move(new_blk_ptr));
  // Gen invalid block
  new_blk_ptr.reset(new BasicBlock(std::move(invalid_label)));
  builder.SetInsertPoint(&*new_blk_ptr);
  // Convert uptr from uint64 to 2 uint32
  Instruction* lo_uptr_inst =
      builder.AddUnaryOp(GetUintId(), SpvOpUConvert, ref_uptr_id);
  Instruction* rshift_uptr_inst =
      builder.AddBinaryOp(GetUint64Id(), SpvOpShiftRightLogical, ref_uptr_id,
                          builder.GetUintConstantId(32));
  Instruction* hi_uptr_inst = builder.AddUnaryOp(GetUintId(), SpvOpUConvert,
                                                 rshift_uptr_inst->result_id());
  GenDebugStreamWrite(
      uid2offset_[ref_inst->unique_id()], stage_idx,
      {error_id, lo_uptr_inst->result_id(), hi_uptr_inst->result_id()},
      &builder);
  // Gen zero for invalid load. If pointer type, need to convert uint64
  // zero to pointer; cannot create ConstantNull of pointer type.
  uint32_t null_id = 0;
  if (new_ref_id != 0) {
    uint32_t ref_type_id = ref_inst->type_id();
    analysis::TypeManager* type_mgr = context()->get_type_mgr();
    analysis::Type* ref_type = type_mgr->GetType(ref_type_id);
    if (ref_type->AsPointer() != nullptr) {
      uint32_t null_u64_id = GetNullId(GetUint64Id());
      Instruction* null_ptr_inst =
          builder.AddUnaryOp(ref_type_id, SpvOpConvertUToPtr, null_u64_id);
      null_id = null_ptr_inst->result_id();
    } else {
      null_id = GetNullId(ref_type_id);
    }
  }
  (void)builder.AddBranch(merge_blk_id);
  new_blocks->push_back(std::move(new_blk_ptr));
  // Gen merge block
  new_blk_ptr.reset(new BasicBlock(std::move(merge_label)));
  builder.SetInsertPoint(&*new_blk_ptr);
  // Gen phi of new reference and zero, if necessary, and replace the
  // result id of the original reference with that of the Phi. Kill original
  // reference.
  if (new_ref_id != 0) {
    Instruction* phi_inst =
        builder.AddPhi(ref_inst->type_id(),
                       {new_ref_id, valid_blk_id, null_id, invalid_blk_id});
    context()->ReplaceAllUsesWith(ref_inst->result_id(), phi_inst->result_id());
  }
  new_blocks->push_back(std::move(new_blk_ptr));
  context()->KillInst(ref_inst);
}

uint32_t InstBuffAddrCheckPass::GetTypeLength(uint32_t type_id) {
  Instruction* type_inst = get_def_use_mgr()->GetDef(type_id);
  switch (type_inst->opcode()) {
    case SpvOpTypeFloat:
    case SpvOpTypeInt:
      return type_inst->GetSingleWordInOperand(0) / 8u;
    case SpvOpTypeVector:
    case SpvOpTypeMatrix:
      return type_inst->GetSingleWordInOperand(1) *
             GetTypeLength(type_inst->GetSingleWordInOperand(0));
    case SpvOpTypePointer:
      assert(type_inst->GetSingleWordInOperand(0) ==
                 SpvStorageClassPhysicalStorageBufferEXT &&
             "unexpected pointer type");
      return 8u;
    default:
      assert(false && "unexpected buffer reference type");
      return 0;
  }
}

void InstBuffAddrCheckPass::AddParam(uint32_t type_id,
                                     std::vector<uint32_t>* param_vec,
                                     std::unique_ptr<Function>* input_func) {
  uint32_t pid = TakeNextId();
  param_vec->push_back(pid);
  std::unique_ptr<Instruction> param_inst(new Instruction(
      get_module()->context(), SpvOpFunctionParameter, type_id, pid, {}));
  get_def_use_mgr()->AnalyzeInstDefUse(&*param_inst);
  (*input_func)->AddParameter(std::move(param_inst));
}

uint32_t InstBuffAddrCheckPass::GetSearchAndTestFuncId() {
  if (search_test_func_id_ == 0) {
    // Generate function "bool search_and_test(uint64_t ref_ptr, uint32_t len)"
    // which searches input buffer for buffer which most likely contains the
    // pointer value |ref_ptr| and verifies that the entire reference of
    // length |len| bytes is contained in the buffer.
    search_test_func_id_ = TakeNextId();
    analysis::TypeManager* type_mgr = context()->get_type_mgr();
    std::vector<const analysis::Type*> param_types = {
        type_mgr->GetType(GetUint64Id()), type_mgr->GetType(GetUintId())};
    analysis::Function func_ty(type_mgr->GetType(GetBoolId()), param_types);
    analysis::Type* reg_func_ty = type_mgr->GetRegisteredType(&func_ty);
    std::unique_ptr<Instruction> func_inst(
        new Instruction(get_module()->context(), SpvOpFunction, GetBoolId(),
                        search_test_func_id_,
                        {{spv_operand_type_t::SPV_OPERAND_TYPE_LITERAL_INTEGER,
                          {SpvFunctionControlMaskNone}},
                         {spv_operand_type_t::SPV_OPERAND_TYPE_ID,
                          {type_mgr->GetTypeInstruction(reg_func_ty)}}}));
    get_def_use_mgr()->AnalyzeInstDefUse(&*func_inst);
    std::unique_ptr<Function> input_func =
        MakeUnique<Function>(std::move(func_inst));
    std::vector<uint32_t> param_vec;
    // Add ref_ptr and length parameters
    AddParam(GetUint64Id(), &param_vec, &input_func);
    AddParam(GetUintId(), &param_vec, &input_func);
    // Empty first block.
    uint32_t first_blk_id = TakeNextId();
    std::unique_ptr<Instruction> first_blk_label(NewLabel(first_blk_id));
    std::unique_ptr<BasicBlock> first_blk_ptr =
        MakeUnique<BasicBlock>(std::move(first_blk_label));
    InstructionBuilder builder(
        context(), &*first_blk_ptr,
        IRContext::kAnalysisDefUse | IRContext::kAnalysisInstrToBlockMapping);
    uint32_t hdr_blk_id = TakeNextId();
    // Branch to search loop header
    std::unique_ptr<Instruction> hdr_blk_label(NewLabel(hdr_blk_id));
    (void)builder.AddInstruction(MakeUnique<Instruction>(
        context(), SpvOpBranch, 0, 0,
        std::initializer_list<Operand>{{SPV_OPERAND_TYPE_ID, {hdr_blk_id}}}));
    input_func->AddBasicBlock(std::move(first_blk_ptr));
    // Linear search loop header block
    // TODO(greg-lunarg): Implement binary search
    std::unique_ptr<BasicBlock> hdr_blk_ptr =
        MakeUnique<BasicBlock>(std::move(hdr_blk_label));
    builder.SetInsertPoint(&*hdr_blk_ptr);
    // Phi for search index. Starts with 1.
    uint32_t cont_blk_id = TakeNextId();
    std::unique_ptr<Instruction> cont_blk_label(NewLabel(cont_blk_id));
    // Deal with def-use cycle caused by search loop index computation.
    // Create Add and Phi instructions first, then do Def analysis on Add.
    // Add Phi and Add instructions and do Use analysis later.
    uint32_t idx_phi_id = TakeNextId();
    uint32_t idx_inc_id = TakeNextId();
    std::unique_ptr<Instruction> idx_inc_inst(new Instruction(
        context(), SpvOpIAdd, GetUintId(), idx_inc_id,
        {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {idx_phi_id}},
         {spv_operand_type_t::SPV_OPERAND_TYPE_ID,
          {builder.GetUintConstantId(1u)}}}));
    std::unique_ptr<Instruction> idx_phi_inst(new Instruction(
        context(), SpvOpPhi, GetUintId(), idx_phi_id,
        {{spv_operand_type_t::SPV_OPERAND_TYPE_ID,
          {builder.GetUintConstantId(1u)}},
         {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {first_blk_id}},
         {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {idx_inc_id}},
         {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {cont_blk_id}}}));
    get_def_use_mgr()->AnalyzeInstDef(&*idx_inc_inst);
    // Add (previously created) search index phi
    (void)builder.AddInstruction(std::move(idx_phi_inst));
    // LoopMerge
    uint32_t bound_test_blk_id = TakeNextId();
    std::unique_ptr<Instruction> bound_test_blk_label(
        NewLabel(bound_test_blk_id));
    (void)builder.AddInstruction(MakeUnique<Instruction>(
        context(), SpvOpLoopMerge, 0, 0,
        std::initializer_list<Operand>{
            {SPV_OPERAND_TYPE_ID, {bound_test_blk_id}},
            {SPV_OPERAND_TYPE_ID, {cont_blk_id}},
            {SPV_OPERAND_TYPE_LITERAL_INTEGER, {SpvLoopControlMaskNone}}}));
    // Branch to continue/work block
    (void)builder.AddInstruction(MakeUnique<Instruction>(
        context(), SpvOpBranch, 0, 0,
        std::initializer_list<Operand>{{SPV_OPERAND_TYPE_ID, {cont_blk_id}}}));
    input_func->AddBasicBlock(std::move(hdr_blk_ptr));
    // Continue/Work Block. Read next buffer pointer and break if greater
    // than ref_ptr arg.
    std::unique_ptr<BasicBlock> cont_blk_ptr =
        MakeUnique<BasicBlock>(std::move(cont_blk_label));
    builder.SetInsertPoint(&*cont_blk_ptr);
    // Add (previously created) search index increment now.
    (void)builder.AddInstruction(std::move(idx_inc_inst));
    // Load next buffer address from debug input buffer
    uint32_t ibuf_id = GetInputBufferId();
    uint32_t ibuf_ptr_id = GetInputBufferPtrId();
    Instruction* uptr_ac_inst = builder.AddTernaryOp(
        ibuf_ptr_id, SpvOpAccessChain, ibuf_id,
        builder.GetUintConstantId(kDebugInputDataOffset), idx_inc_id);
    uint32_t ibuf_type_id = GetInputBufferTypeId();
    Instruction* uptr_load_inst =
        builder.AddUnaryOp(ibuf_type_id, SpvOpLoad, uptr_ac_inst->result_id());
    // If loaded address greater than ref_ptr arg, break, else branch back to
    // loop header
    Instruction* uptr_test_inst =
        builder.AddBinaryOp(GetBoolId(), SpvOpUGreaterThan,
                            uptr_load_inst->result_id(), param_vec[0]);
    (void)builder.AddConditionalBranch(uptr_test_inst->result_id(),
                                       bound_test_blk_id, hdr_blk_id,
                                       kInvalidId, SpvSelectionControlMaskNone);
    input_func->AddBasicBlock(std::move(cont_blk_ptr));
    // Bounds test block. Read length of selected buffer and test that
    // all len arg bytes are in buffer.
    std::unique_ptr<BasicBlock> bound_test_blk_ptr =
        MakeUnique<BasicBlock>(std::move(bound_test_blk_label));
    builder.SetInsertPoint(&*bound_test_blk_ptr);
    // Decrement index to point to previous/candidate buffer address
    Instruction* cand_idx_inst = builder.AddBinaryOp(
        GetUintId(), SpvOpISub, idx_inc_id, builder.GetUintConstantId(1u));
    // Load candidate buffer address
    Instruction* cand_ac_inst =
        builder.AddTernaryOp(ibuf_ptr_id, SpvOpAccessChain, ibuf_id,
                             builder.GetUintConstantId(kDebugInputDataOffset),
                             cand_idx_inst->result_id());
    Instruction* cand_load_inst =
        builder.AddUnaryOp(ibuf_type_id, SpvOpLoad, cand_ac_inst->result_id());
    // Compute offset of ref_ptr from candidate buffer address
    Instruction* offset_inst = builder.AddBinaryOp(
        ibuf_type_id, SpvOpISub, param_vec[0], cand_load_inst->result_id());
    // Convert ref length to uint64
    Instruction* ref_len_64_inst =
        builder.AddUnaryOp(ibuf_type_id, SpvOpUConvert, param_vec[1]);
    // Add ref length to ref offset to compute end of reference
    Instruction* ref_end_inst =
        builder.AddBinaryOp(ibuf_type_id, SpvOpIAdd, offset_inst->result_id(),
                            ref_len_64_inst->result_id());
    // Load starting index of lengths in input buffer and convert to uint32
    Instruction* len_start_ac_inst =
        builder.AddTernaryOp(ibuf_ptr_id, SpvOpAccessChain, ibuf_id,
                             builder.GetUintConstantId(kDebugInputDataOffset),
                             builder.GetUintConstantId(0u));
    Instruction* len_start_load_inst = builder.AddUnaryOp(
        ibuf_type_id, SpvOpLoad, len_start_ac_inst->result_id());
    Instruction* len_start_32_inst = builder.AddUnaryOp(
        GetUintId(), SpvOpUConvert, len_start_load_inst->result_id());
    // Decrement search index to get candidate buffer length index
    Instruction* cand_len_idx_inst =
        builder.AddBinaryOp(GetUintId(), SpvOpISub, cand_idx_inst->result_id(),
                            builder.GetUintConstantId(1u));
    // Add candidate length index to start index
    Instruction* len_idx_inst = builder.AddBinaryOp(
        GetUintId(), SpvOpIAdd, cand_len_idx_inst->result_id(),
        len_start_32_inst->result_id());
    // Load candidate buffer length
    Instruction* len_ac_inst =
        builder.AddTernaryOp(ibuf_ptr_id, SpvOpAccessChain, ibuf_id,
                             builder.GetUintConstantId(kDebugInputDataOffset),
                             len_idx_inst->result_id());
    Instruction* len_load_inst =
        builder.AddUnaryOp(ibuf_type_id, SpvOpLoad, len_ac_inst->result_id());
    // Test if reference end within candidate buffer length
    Instruction* len_test_inst = builder.AddBinaryOp(
        GetBoolId(), SpvOpULessThanEqual, ref_end_inst->result_id(),
        len_load_inst->result_id());
    // Return test result
    (void)builder.AddInstruction(MakeUnique<Instruction>(
        context(), SpvOpReturnValue, 0, 0,
        std::initializer_list<Operand>{
            {SPV_OPERAND_TYPE_ID, {len_test_inst->result_id()}}}));
    // Close block
    input_func->AddBasicBlock(std::move(bound_test_blk_ptr));
    // Close function and add function to module
    std::unique_ptr<Instruction> func_end_inst(
        new Instruction(get_module()->context(), SpvOpFunctionEnd, 0, 0, {}));
    get_def_use_mgr()->AnalyzeInstDefUse(&*func_end_inst);
    input_func->SetFunctionEnd(std::move(func_end_inst));
    context()->AddFunction(std::move(input_func));
  }
  return search_test_func_id_;
}

uint32_t InstBuffAddrCheckPass::GenSearchAndTest(Instruction* ref_inst,
                                                 InstructionBuilder* builder,
                                                 uint32_t* ref_uptr_id) {
  // Enable Int64 if necessary
  if (!get_feature_mgr()->HasCapability(SpvCapabilityInt64)) {
    std::unique_ptr<Instruction> cap_int64_inst(new Instruction(
        context(), SpvOpCapability, 0, 0,
        std::initializer_list<Operand>{
            {SPV_OPERAND_TYPE_CAPABILITY, {SpvCapabilityInt64}}}));
    get_def_use_mgr()->AnalyzeInstDefUse(&*cap_int64_inst);
    context()->AddCapability(std::move(cap_int64_inst));
  }
  // Convert reference pointer to uint64
  uint32_t ref_ptr_id = ref_inst->GetSingleWordInOperand(0);
  Instruction* ref_uptr_inst =
      builder->AddUnaryOp(GetUint64Id(), SpvOpConvertPtrToU, ref_ptr_id);
  *ref_uptr_id = ref_uptr_inst->result_id();
  // Compute reference length in bytes
  analysis::DefUseManager* du_mgr = get_def_use_mgr();
  Instruction* ref_ptr_inst = du_mgr->GetDef(ref_ptr_id);
  uint32_t ref_ptr_ty_id = ref_ptr_inst->type_id();
  Instruction* ref_ptr_ty_inst = du_mgr->GetDef(ref_ptr_ty_id);
  uint32_t ref_len = GetTypeLength(ref_ptr_ty_inst->GetSingleWordInOperand(1));
  uint32_t ref_len_id = builder->GetUintConstantId(ref_len);
  // Gen call to search and test function
  const std::vector<uint32_t> args = {GetSearchAndTestFuncId(), *ref_uptr_id,
                                      ref_len_id};
  Instruction* call_inst =
      builder->AddNaryOp(GetBoolId(), SpvOpFunctionCall, args);
  uint32_t retval = call_inst->result_id();
  return retval;
}

void InstBuffAddrCheckPass::GenBuffAddrCheckCode(
    BasicBlock::iterator ref_inst_itr,
    UptrVectorIterator<BasicBlock> ref_block_itr, uint32_t stage_idx,
    std::vector<std::unique_ptr<BasicBlock>>* new_blocks) {
  // Look for reference through indexed descriptor. If found, analyze and
  // save components. If not, return.
  Instruction* ref_inst = &*ref_inst_itr;
  if (!IsPhysicalBuffAddrReference(ref_inst)) return;
  // Move original block's preceding instructions into first new block
  std::unique_ptr<BasicBlock> new_blk_ptr;
  MovePreludeCode(ref_inst_itr, ref_block_itr, &new_blk_ptr);
  InstructionBuilder builder(
      context(), &*new_blk_ptr,
      IRContext::kAnalysisDefUse | IRContext::kAnalysisInstrToBlockMapping);
  new_blocks->push_back(std::move(new_blk_ptr));
  uint32_t error_id = builder.GetUintConstantId(kInstErrorBuffAddrUnallocRef);
  // Generate code to do search and test if all bytes of reference
  // are within a listed buffer. Return reference pointer converted to uint64.
  uint32_t ref_uptr_id;
  uint32_t valid_id = GenSearchAndTest(ref_inst, &builder, &ref_uptr_id);
  // Generate test of search results with true branch
  // being full reference and false branch being debug output and zero
  // for the referenced value.
  GenCheckCode(valid_id, error_id, ref_uptr_id, stage_idx, ref_inst,
               new_blocks);
  // Move original block's remaining code into remainder/merge block and add
  // to new blocks
  BasicBlock* back_blk_ptr = &*new_blocks->back();
  MovePostludeCode(ref_block_itr, back_blk_ptr);
}

void InstBuffAddrCheckPass::InitInstBuffAddrCheck() {
  // Initialize base class
  InitializeInstrument();
  // Initialize class
  search_test_func_id_ = 0;
}

Pass::Status InstBuffAddrCheckPass::ProcessImpl() {
  // Perform bindless bounds check on each entry point function in module
  InstProcessFunction pfn =
      [this](BasicBlock::iterator ref_inst_itr,
             UptrVectorIterator<BasicBlock> ref_block_itr, uint32_t stage_idx,
             std::vector<std::unique_ptr<BasicBlock>>* new_blocks) {
        return GenBuffAddrCheckCode(ref_inst_itr, ref_block_itr, stage_idx,
                                    new_blocks);
      };
  bool modified = InstProcessEntryPointCallTree(pfn);
  return modified ? Status::SuccessWithChange : Status::SuccessWithoutChange;
}

Pass::Status InstBuffAddrCheckPass::Process() {
  if (!get_feature_mgr()->HasCapability(
          SpvCapabilityPhysicalStorageBufferAddressesEXT))
    return Status::SuccessWithoutChange;
  InitInstBuffAddrCheck();
  return ProcessImpl();
}

}  // namespace opt
}  // namespace spvtools

redpajama_set_name: RedPajamaGithub


text:
import { ILogService, LogLevel, AbstractLogService } from 'vs/platform/log/common/log';
import { ExtHostLogServiceShape, MainThreadLogShape, MainContext } from 'vs/workbench/api/common/extHost.protocol';
import { IExtHostInitDataService } from 'vs/workbench/api/common/extHostInitDataService';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { UriComponents } from 'vs/base/common/uri';

export class ExtHostLogService extends AbstractLogService implements ILogService, ExtHostLogServiceShape {

	declare readonly _serviceBrand: undefined;

	private readonly _proxy: MainThreadLogShape;
	private readonly _logFile: UriComponents;

	constructor(
		@IExtHostRpcService rpc: IExtHostRpcService,
		@IExtHostInitDataService initData: IExtHostInitDataService,
	) {
		super();
		this._proxy = rpc.getProxy(MainContext.MainThreadLog);
		this._logFile = initData.logFile.toJSON();
		this.setLevel(initData.logLevel);
	}

	$setLevel(level: LogLevel): void {
		this.setLevel(level);
	}

	trace(_message: string, ..._args: any[]): void {
		if (this.getLevel() <= LogLevel.Trace) {
			this._proxy.$log(this._logFile, LogLevel.Trace, Array.from(arguments));
		}
	}

	debug(_message: string, ..._args: any[]): void {
		if (this.getLevel() <= LogLevel.Debug) {
			this._proxy.$log(this._logFile, LogLevel.Debug, Array.from(arguments));
		}
	}

	info(_message: string, ..._args: any[]): void {
		if (this.getLevel() <= LogLevel.Info) {
			this._proxy.$log(this._logFile, LogLevel.Info, Array.from(arguments));
		}
	}

	warn(_message: string, ..._args: any[]): void {
		if (this.getLevel() <= LogLevel.Warning) {
			this._proxy.$log(this._logFile, LogLevel.Warning, Array.from(arguments));
		}
	}

	error(_message: string | Error, ..._args: any[]): void {
		if (this.getLevel() <= LogLevel.Error) {
			this._proxy.$log(this._logFile, LogLevel.Error, Array.from(arguments));
		}
	}

	critical(_message: string | Error, ..._args: any[]): void {
		if (this.getLevel() <= LogLevel.Critical) {
			this._proxy.$log(this._logFile, LogLevel.Critical, Array.from(arguments));
		}
	}

	flush(): void { }
}


text:
namespace Rock.Logging
{
    public interface ILogEntryFactory
    {
        ILogEntry CreateLogEntry();
    }
}


text:
package fetch

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"

	"github.com/rakyll/gom/internal/plugin"
	"github.com/rakyll/gom/internal/profile"
)

// FetchProfile reads from a data source (network, file) and generates a
// profile.
func FetchProfile(source string, timeout time.Duration) (*profile.Profile, error) {
	return Fetcher(source, timeout, plugin.StandardUI())
}

// Fetcher is the plugin.Fetcher version of FetchProfile.
func Fetcher(source string, timeout time.Duration, ui plugin.UI) (*profile.Profile, error) {
	var f io.ReadCloser
	var err error

	url, err := url.Parse(source)
	if err == nil && url.Host != "" {
		f, err = FetchURL(source, timeout)
	} else {
		f, err = os.Open(source)
	}
	if err != nil {
		return nil, err
	}
	defer f.Close()
	return profile.Parse(f)
}

// FetchURL fetches a profile from a URL using HTTP.
func FetchURL(source string, timeout time.Duration) (io.ReadCloser, error) {
	resp, err := httpGet(source, timeout)
	if err != nil {
		return nil, fmt.Errorf("http fetch %s: %v", source, err)
	}
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("server response: %s", resp.Status)
	}

	return resp.Body, nil
}

// PostURL issues a POST to a URL over HTTP.
func PostURL(source, post string) ([]byte, error) {
	resp, err := http.Post(source, "application/octet-stream", strings.NewReader(post))
	if err != nil {
		return nil, fmt.Errorf("http post %s: %v", source, err)
	}
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("server response: %s", resp.Status)
	}
	defer resp.Body.Close()
	return ioutil.ReadAll(resp.Body)
}

// httpGet is a wrapper around http.Get; it is defined as a variable
// so it can be redefined during for testing.
var httpGet = func(url string, timeout time.Duration) (*http.Response, error) {
	client := &http.Client{
		Transport: &http.Transport{
			ResponseHeaderTimeout: timeout + 5*time.Second,
		},
	}
	return client.Get(url)
}


text:
/* Remove margin from selects in webkit browsers, same for textareas, and remove spinners */
select {
    margin: 0px;
}
textarea {
    margin: 0px;
}
input[type='number']::-webkit-inner-spin-button,
input[type='number']::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

/* Layout CSS */
div.sheet-section {
    border-radius: 15px;
    border: 1px solid black;
    padding: 4px;
}
div.sheet-column-1of1 {
    margin-bottom: 1%;
    width: 100%;
}
div.sheet-column-1of2 {
    margin-right: 0.5%;
    margin-bottom: 1%;
    width: 49.5%;
    float: left;
}
div.sheet-column-2of2 {
    margin-left: 0.5%;
    margin-bottom: 1%;
    float: left;
    width: 49.5%;
}

div.sheet-column-1of3 {
    margin-right: 0.5%;
    margin-bottom: 1%;
    float: left;
    width: 32.666666%;
}
div.sheet-column-1n2of3 {
    margin-right: 0.5%;
    margin-bottom: 1%;
    float: left;
    width: 66.333333%;
}
div.sheet-column-2of3 {
    margin-left: 0.5%;
    margin-right: 0.5%
    margin-bottom: 1%;
    float: left;
    width: 32.666666%;
}
div.sheet-column-2n3of3 {
    margin-left: 0.5%;
    margin-bottom: 1%;
    float: left;
    width: 66.333333%;
}
div.sheet-column-3of3 {
    margin-left: 0.5%;
    margin-bottom: 1%;
    float: left;
    width: 32.666666%;
}

/* Generic CSS */
.sheet-autocalc {
    cursor: not-allowed;
    background: #F5F5F5;
}
table.sheet-full {
    width: 100%;
}
table.sheet-full_fixed {
    width: 100%;
    table-layout: fixed;
}
tr.sheet-head {
    text-align: center;
}
input.sheet-full {
    width: 100%;
}
input.sheet-value_full {
    width: 100%;
    text-align: center;
}
input[type="number"].sheet-full {
    width: 100%;
}
input[type="number"].sheet-value_full {
    width: 100%;
    text-align: center;
}
input[type="number"].sheet-total_full {
    width: 100%;
    text-align: center;
    font-weight: bold;
}
input.sheet-value {
    width: 35px;
    text-align: center;
}
input[type="number"].sheet-value {
    width: 35px;
    text-align: center;
}
input[type="number"].sheet-total {
    width: 35px;
    text-align: center;
    font-weight: bold;
}
input.sheet-damage {
    width: 55px;
    text-align: right;
}
select.sheet-diff {
    width: 45px;
    padding: 0px;
}
select.sheet-db {
    padding: 0px;
    width: 52px;
}
select.sheet-skill_base {
    padding: 0px;
    width: 60px;
    font-size: 75%;
}
select.sheet-full {
    width: 100%;
}

/* Info CSS */
td.sheet-info-label {
    white-space: nowrap;
}
input.sheet-info-number {
    width: 50px;
    text-align: center;
}

/* Tab CSS */
input.sheet-tab {
    position: relative;
    z-index: 9999;
    cursor: pointer;
    opacity: 0;
    width: 16.25%;
    margin-bottom: 2px;
}
span.sheet-tab {
    display: inline-block;
    position: relative;
    width: 16.25%;
    text-align: center;
    background: #B30201;
  color: #F59111;
    font-weight: bold;
  border-radius: 4px;
    cursor: pointer;
    margin-left: -16.25%;
}

input.sheet-vitals-tab:checked + span.sheet-vitals-tab,
input.sheet-combat-tab:checked + span.sheet-combat-tab,
input.sheet-skills-tab:checked + span.sheet-skills-tab,
input.sheet-passions-tab:checked + span.sheet-passions-tab,
input.sheet-equipment-tab:checked + span.sheet-equipment-tab,
input.sheet-notes-tab:checked + span.sheet-notes-tab,
input.sheet-folk_magic-tab:checked + span.sheet-folk_magic-tab,
input.sheet-animism-tab:checked + span.sheet-animism-tab,
input.sheet-mysticism-tab:checked + span.sheet-mysticism-tab,
input.sheet-sorcery-tab:checked + span.sheet-sorcery-tab,
input.sheet-theism-tab:checked + span.sheet-theism-tab,
input.sheet-active_effects-tab:checked + span.sheet-active_effects-tab {
    background: #BEBEBE;
    color: black;
}

/* Page CSS */
div.sheet-page {
    visibility: hidden;
    opacity: 0;
    max-height: 0;
    overflow: hidden;
}
input.sheet-vitals-tab:checked ~ div.sheet-vitals-page,
input.sheet-combat-tab:checked ~ div.sheet-combat-page,
input.sheet-skills-tab:checked ~ div.sheet-skills-page,
input.sheet-passions-tab:checked ~ div.sheet-passions-page,
input.sheet-equipment-tab:checked ~ div.sheet-equipment-page,
input.sheet-notes-tab:checked ~ div.sheet-notes-page,
input.sheet-folk_magic-tab:checked ~ div.sheet-folk_magic-page,
input.sheet-animism-tab:checked ~ div.sheet-animism-page,
input.sheet-mysticism-tab:checked ~ div.sheet-mysticism-page,
input.sheet-sorcery-tab:checked ~ div.sheet-sorcery-page,
input.sheet-theism-tab:checked ~ div.sheet-theism-page,
input.sheet-active_effects-tab:checked ~ div.sheet-active_effects-page {
    visibility: visible;
    opacity: 1;
    max-height: 999999px;
    overflow: auto;
}

/* Characteristics */
div.sheet-characteristic-column {
    text-align: center;
    float: left;
    width: 25%;
}
table.sheet-char {
    margin-left: auto;
    margin-right: auto;
}
td.sheet-char-label {
    text-align: right;
    font-weight: bold;
}

/* Hit Locations */
table.sheet-hit_locations {
    width: 100%;
}
td.sheet-hit_locations_roll {
    width: 50px;
}
input.sheet-hit_locations_long {
    width: 100%;
}
input.sheet-hit_locations_short {
    width: 47px;
    text-align: center;
}

/* Attributes */
td.sheet-attribute-label {
    white-space: nowrap;
}
td.sheet-attribute_value {
    text-align: center;
}
input.sheet-attribute-current {
    text-align: center;
    width: 35px;
    font-weight: bold;
}

/* Fatigue */
table.sheet-fatigue {
    width: 100%;
}
td.sheet-fatigue-label {
    white-space: nowrap;
}
td.sheet-fatigue-select {
    width: 100%;
}
select.sheet-fatigue-select {
    width: 100%;
}
td.sheet-fatigue_skillgrade {
    width: 16.666%;
}
td.sheet-fatigue_movement {
    width: 16.666%;
}
td.sheet-fatigue_strike_rank {
    width: 16.666%;
}
td.sheet-fatigue_action_points {
    width: 16.666%;
}
td.sheet-fatigue_recovery_period {
    width: 16.666%;
}
td.sheet-fatigue_recovery_time {
    white-space: nowrap;
    width: 16.666%;
    text-align: center;
}

/* Combat Styles */
table.sheet-combat_styles {
    width: 100%;
}
td.sheet-cs_style {
    width: 16%;
}
td.sheet-cs_calc {
    white-space: nowrap;
    width: 25%;
    text-align: center;
}
td.sheet-cs_number {
    width: 5%;
    text-align: center;
}
td.sheet-cs_symbol {
    text-align: center;
    width: 2%;
}
td.sheet-cs_roll {
    width: 4%;
}
td.sheet-cs_weapons {
    width: 35%;
}
td.sheet-cs_benifits {
    width: 14%;
}

/* Shields and Weapons */
td.sheet-shield {
    width: 15%;
    text-align: center;
}
td.sheet-shield_damage {
    width: 17%;
    text-align: center;
}
td.sheet-shield_size {
    width: 8%;
    text-align: center;
}
td.sheet-shield_reach {
    width: 10%;
    text-align: center;
}
td.sheet-shield_enc {
    width: 5%;
    text-align: center;
}
td.sheet-shield_ap {
    width: 5%;
    text-align: center;
}
td.sheet-shield_hp {
    width: 10%;
    text-align: center;
}
td.sheet-shield_effects {
    width: 20%;
    text-align: center;
}
td.sheet-shield_blocks {
    width: 11%;
    text-align: center;
}

td.sheet-weapon {
    width: 15%;
    text-align: center;
}
td.sheet-weapon_damage {
    width: 17%;
    text-align: center;
}
td.sheet-weapon_size {
    width: 8%;
    text-align: center;
}
td.sheet-weapon_reach {
    width: 10%;
    text-align: center;
}
td.sheet-weapon_enc {
    width: 5%;
    text-align: center;
}
td.sheet-weapon_ap {
    width: 5%;
    text-align: center;
}
td.sheet-weapon_hp {
    width: 10%;
    text-align: center;
}
td.sheet-weapon_impalesize {
    width: 6%;
    text-align: center;
}
td.sheet-weapon_effects {
    width: 20%;
    text-align: center;
}
td.sheet-weapon_load {
    width: 5%;
    text-align: center;
}

/* SKill CSS */
td.sheet-skill {
    width: 25%;
}
td.sheet-skill_calc_label {
    width: 54%;
    text-align: center;
}
td.sheet-skill_calc {
    width: 54%;
    text-align: right;
}
td.sheet-profskill {
    width: 26%;
}
td.sheet-profskill_calc_label {
    width: 53%;
    text-align: center;
}
td.sheet-profskill_calc {
    width: 53%;
    text-align: right;
}
td.sheet-skill_total {
    width: 10%;
    text-align: center;
}
td.sheet-skill_symbol {
    text-align: center;
    width: 3%;
}
td.sheet-skill_roll {
    width: 8%;
    text-align: center;
}

/* Passions */
td.sheet-passion {
    width: 33%;
}
td.sheet-passion_calc_label {
    width: 46%;
    text-align: center;
}
td.sheet-passion_calc {
    width: 46%;
    text-align: right;
}

/* Cults */
td.sheet-cult {
    width: 35%;
}
td.sheet-cult_rank {
    width: 27%;
}
td.sheet-cult_notes {
    width: 38%;
}

/* Equipment */
td.sheet-item {
    width: 70%;
}
td.sheet-item_qnty {
    width: 15%;
}
td.sheet-item_end {
    width: 15%;
}

/* Wealth */
textarea.sheet-wealth {
    width: 97%;
    height: 75px;
}

/* Load */
td.sheet-load_label {
    width: 25%;
}
td.sheet-load_value {
    width: 25%;
}

/* Notes */
textarea.sheet-notes {
    width: 96%;
    height: 425px;
}

/* Folk Magic */
textarea.sheet-folk_magic_spells {
    width: 98.5%;
    height: 350px;
}

/* Animism */
table.sheet-animism_table {
    margin-left: auto;
    margin-right: auto;
}
td.sheet-animism_cult {
    width: 12%;
}
td.sheet-animism_max_spirits {
    width: 18%;
}
td.sheet-animism_max_spirit_pow {
    width: 20%;
}
td.sheet-animism_ap {
    width: 11%;
}
td.sheet-animism_sr {
    width: 9%;
}
td.sheet-animism_spirit_damage {
    width: 15%;
}
td.sheet-animism_roll {
    width: 4%;
}
td.sheet-animism_tenacity {
    width: 11%;
}
textarea.sheet-animism_fetishes {
    width: 98.5%;
    height: 300px;
}

/* Mysticism */
td.sheet-mysticism_label {
    width: 15%;
}
td.sheet-mysticism_calc_label {
    width: 27%;
    text-align: center;
}
td.sheet-mysticism_calc {
    width: 27%;
    text-align: right;
}
td.sheet-mysticism_total {
    width: 4%;
    text-align: center;
}
td.sheet-mysticism_symbol {
    text-align: center;
    width: 2%;
}
td.sheet-mysticism_roll {
    width: 4%;
    text-align: center;
}
td.sheet-mysticism_intensity {
    width: 7%;
    text-align: center;
}
td.sheet-mysticism_talents {
    width: 41%;
    text-align: center;
}
textarea.sheet-mysticism_practiced_talents {
    width: 98.5%;
    height: 300px;
}

/* Sorcery */
td.sheet-sorcery_label {
    width: 15%;
}
td.sheet-sorcery_calc_label {
    width: 26%;
    text-align: center;
}
td.sheet-sorcery_calc {
    width: 26%;
    text-align: right;
}
td.sheet-sorcery_total {
    width: 4%;
    text-align: center;
}
td.sheet-sorcery_symbol {
    text-align: center;
    width: 2%;
}
td.sheet-sorcery_roll {
    width: 4%;
    text-align: center;
}
td.sheet-sorcery_intensity {
    width: 7%;
    text-align: center;
}
td.sheet-sorcery_spells {
    width: 42%;
    text-align: center;
}
textarea.sheet-sorcery_memorized_spells {
    width: 98.5%;
    height: 300px;
}

/* Theism */
td.sheet-theism_label {
    width: 27%;
}
td.sheet-theism_calc_label {
    width: 26%;
    text-align: center;
}
td.sheet-theism_calc {
    width: 26%;
    text-align: right;
}
td.sheet-theism_total {
    width: 4%;
    text-align: center;
}
td.sheet-theism_symbol {
    text-align: center;
    width: 2%;
}
td.sheet-theism_roll {
    width: 4%;
    text-align: center;
}
td.sheet-theism_intensity {
    width: 8%;
    text-align: center;
}
td.sheet-theism_magnitude {
    width: 8%;
    text-align: center;
}
td.sheet-theism_cult {
    width: 10%;
    text-align: center;
}
td.sheet-theism_pool {
    width: 11%;
    text-align: center;
}
td.sheet-theism_pool_symbol {
    width: 1%;
    text-align: center;
}
td.sheet-theism_pool_value {
    width: 5%;
    text-align: center;
}
textarea.sheet-theism_miracles {
    width: 98.5%;
    height: 300px;
}

/* Active Effects */
td.sheet-effect_label {
    width: 15%;
}
td.sheet-effect_duration {
    width: 8%;
}
td.sheet-effect_magnitude {
    width: 8%;
}
td.sheet-effect_intensity {
    width: 8%;
}
td.sheet-effect_range {
    width: 8%;
}
td.sheet-effect_targets {
    width: 8%;
}
td.sheet-effect_desc {
    width: 37%;
}
td.sheet-effect_mp_cost {
    width: 8%;
}

/* Roll Templates */
.sheet-rolltemplate-runequest table {
    width: 100%;
    border: 1px solid black;
    color: black;
    background: #FFFFFF;
}
.sheet-rolltemplate-runequest caption {
    text-align: center;
    background: url(http://i.imgur.com/VnqY9Kh.png);
    color: #F59111;
    font-weight: bold;
  padding: 2px;
  border: 1px solid black;
  line-height: 1.6em;
}
.sheet-rolltemplate-runequest td {
  padding: 5px;
  border-bottom: 1px solid black;
}
.sheet-rolltemplate-runequest td.sheet-template_label {
    font-weight: bold;
}
.sheet-rolltemplate-runequest td.sheet-template_value {
    text-align: center;
}
.sheet-rolltemplate-runequest .inlinerollresult  {
  display: inline-block;
  min-width: 1.5em;
  text-align: center;
  border: 2px solid black;
    background: #BEBEBE;
}
.sheet-rolltemplate-runequest .inlinerollresult.fullcrit {
  border: 2px solid black;
    background: #BEBEBE;
}
.sheet-rolltemplate-runequest .inlinerollresult.fullfail {
  border: 2px solid black;
    background: #BEBEBE;
}
.sheet-rolltemplate-runequest .inlinerollresult.importantroll {
  border: 2px solid black;
    background: #BEBEBE;
}

.sheet-rolltemplate-runequest-weapon table {
    width: 100%;
    border: 1px solid black;
    color: black;
    background: #FFFFFF;
}
.sheet-rolltemplate-runequest-weapon caption {
    text-align: center;
    background: url(http://i.imgur.com/VnqY9Kh.png);
    color: #F59111;
    font-weight: bold;
    padding: 2px;
  border: 1px solid black;
  line-height: 1.6em;
}
.sheet-rolltemplate-runequest-weapon td {
  padding: 5px;
  border-bottom: 1px solid black;
}
.sheet-rolltemplate-runequest-weapon td.sheet-template_label {
    font-weight: bold;
}
.sheet-rolltemplate-runequest-weapon td.sheet-template_value {
    text-align: center;
}
.sheet-rolltemplate-runequest-weapon .inlinerollresult  {
  display: inline-block;
  min-width: 1.5em;
  text-align: center;
  border: 2px solid black;
    background: #BEBEBE;
}
.sheet-rolltemplate-runequest-weapon .inlinerollresult.fullcrit {
  border: 2px solid black;
    background: #BEBEBE;
}
.sheet-rolltemplate-runequest-weapon .inlinerollresult.fullfail {
  border: 2px solid black;
    background: #BEBEBE;
}
.sheet-rolltemplate-runequest-weapon .inlinerollresult.importantroll {
  border: 2px solid black;
    background: #BEBEBE;
}


text:
using System;
using System.Management.Automation;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Diagnostics;

namespace Microsoft.PowerShell.Commands
{
    /// <summary>
    /// Response object for html content without DOM parsing
    /// </summary>
    public partial class BasicHtmlWebResponseObject : WebResponseObject
    {
        #region Properties

        /// <summary>
        /// gets or protected sets the Content property
        /// </summary>
        public new string Content { get; private set; }

        private WebCmdletElementCollection _inputFields;

        /// <summary>
        /// gets the Fields property
        /// </summary>
        public WebCmdletElementCollection InputFields
        {
            get
            {
                if (_inputFields == null)
                {
                    EnsureHtmlParser();

                    List<PSObject> parsedFields = new List<PSObject>();
                    MatchCollection fieldMatch = s_inputFieldRegex.Matches(Content);
                    foreach (Match field in fieldMatch)
                    {
                        parsedFields.Add(CreateHtmlObject(field.Value, "INPUT"));
                    }

                    _inputFields = new WebCmdletElementCollection(parsedFields);
                }

                return _inputFields;
            }
        }

        private WebCmdletElementCollection _links;

        /// <summary>
        /// gets the Links property
        /// </summary>
        public WebCmdletElementCollection Links
        {
            get
            {
                if (_links == null)
                {
                    EnsureHtmlParser();

                    List<PSObject> parsedLinks = new List<PSObject>();
                    MatchCollection linkMatch = s_linkRegex.Matches(Content);
                    foreach (Match link in linkMatch)
                    {
                        parsedLinks.Add(CreateHtmlObject(link.Value, "A"));
                    }

                    _links = new WebCmdletElementCollection(parsedLinks);
                }

                return _links;
            }
        }

        private WebCmdletElementCollection _images;

        /// <summary>
        /// gets the Images property
        /// </summary>
        public WebCmdletElementCollection Images
        {
            get
            {
                if (_images == null)
                {
                    EnsureHtmlParser();

                    List<PSObject> parsedImages = new List<PSObject>();
                    MatchCollection imageMatch = s_imageRegex.Matches(Content);
                    foreach (Match image in imageMatch)
                    {
                        parsedImages.Add(CreateHtmlObject(image.Value, "IMG"));
                    }

                    _images = new WebCmdletElementCollection(parsedImages);
                }

                return _images;
            }
        }

        #endregion Properties

        #region Private Fields

        private static Regex s_tagRegex;
        private static Regex s_attribsRegex;
        private static Regex s_attribNameValueRegex;
        private static Regex s_inputFieldRegex;
        private static Regex s_linkRegex;
        private static Regex s_imageRegex;

        #endregion Private Fields

        #region Methods

        private void EnsureHtmlParser()
        {
            if (s_tagRegex == null)
            {
                s_tagRegex = new Regex(@"<\w+((\s+[^""'>/=\s\p{Cc}]+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>",
                    RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
            }

            if (s_attribsRegex == null)
            {
                s_attribsRegex = new Regex(@"(?<=\s+)([^""'>/=\s\p{Cc}]+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)",
                    RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
            }

            if (s_attribNameValueRegex == null)
            {
                s_attribNameValueRegex = new Regex(@"([^""'>/=\s\p{Cc}]+)(?:\s*=\s*(?:""(.*?)""|'(.*?)'|([^'"">\s]+)))?",
                    RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
            }

            if (s_inputFieldRegex == null)
            {
                s_inputFieldRegex = new Regex(@"<input\s+[^>]*(/>|>.*?</input>)",
                    RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
            }

            if (s_linkRegex == null)
            {
                s_linkRegex = new Regex(@"<a\s+[^>]*(/>|>.*?</a>)",
                    RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
            }

            if (s_imageRegex == null)
            {
                s_imageRegex = new Regex(@"<img\s+[^>]*>",
                    RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
            }
        }

        private PSObject CreateHtmlObject(string html, string tagName)
        {
            PSObject elementObject = new PSObject();

            elementObject.Properties.Add(new PSNoteProperty("outerHTML", html));
            elementObject.Properties.Add(new PSNoteProperty("tagName", tagName));

            ParseAttributes(html, elementObject);

            return elementObject;
        }

        private void ParseAttributes(string outerHtml, PSObject elementObject)
        {
            // We might get an empty input for a directive from the HTML file
            if (!string.IsNullOrEmpty(outerHtml))
            {
                // Extract just the opening tag of the HTML element (omitting the closing tag and any contents,
                // including contained HTML elements)
                var match = s_tagRegex.Match(outerHtml);

                // Extract all the attribute specifications within the HTML element opening tag
                var attribMatches = s_attribsRegex.Matches(match.Value);

                foreach (Match attribMatch in attribMatches)
                {
                    // Extract the name and value for this attribute (allowing for variations like single/double/no
                    // quotes, and no value at all)
                    var nvMatches = s_attribNameValueRegex.Match(attribMatch.Value);
                    Debug.Assert(nvMatches.Groups.Count == 5);

                    // Name is always captured by group #1
                    string name = nvMatches.Groups[1].Value;

                    // The value (if any) is captured by group #2, #3, or #4, depending on quoting or lack thereof
                    string value = null;
                    if (nvMatches.Groups[2].Success)
                    {
                        value = nvMatches.Groups[2].Value;
                    }
                    else if (nvMatches.Groups[3].Success)
                    {
                        value = nvMatches.Groups[3].Value;
                    }
                    else if (nvMatches.Groups[4].Success)
                    {
                        value = nvMatches.Groups[4].Value;
                    }

                    elementObject.Properties.Add(new PSNoteProperty(name, value));
                }
            }
        }

        /// <summary>
        /// Reads the response content from the web response.
        /// </summary>
        private void InitializeContent()
        {
            string contentType = ContentHelper.GetContentType(BaseResponse);
            if (ContentHelper.IsText(contentType))
            {
                // fill the Content buffer
                string characterSet = WebResponseHelper.GetCharacterSet(BaseResponse);
                this.Content = StreamHelper.DecodeStream(RawContentStream, characterSet);
            }
            else
            {
                this.Content = string.Empty;
            }
        }

        #endregion Methods
    }
}


text:
package org.jetbrains.plugins.groovy.lang.psi.stubs;

import com.intellij.psi.stubs.NamedStub;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition;

/**
 * @author ilyas
 */
public interface GrTypeDefinitionStub extends NamedStub<GrTypeDefinition> {

  String[] getSuperClassNames();

  @NonNls
  @Nullable
  String getQualifiedName();

  String getSourceFileName();

  String[] getAnnotations();

  boolean isAnonymous();
  boolean isAnonymousInQualifiedNew();

  boolean isInterface();
  boolean isEnum();
  boolean isAnnotationType();

  byte getFlags();
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

001package io.ebean.meta;
002
003import java.sql.Connection;
004import java.util.ArrayList;
005import java.util.List;
006import java.util.Set;
007
008/**
009 * Request used to capture query plans.
010 */
011public class QueryPlanRequest {
012
013  private List<MetaQueryPlan> plans = new ArrayList<>();
014
015  private Connection connection;
016
017  private boolean store;
018
019  private long since;
020
021  private Set<Class<?>> includedBeanTypes;
022
023  private Set<String> includedLabels;
024
025  public List<MetaQueryPlan> getPlans() {
026    return plans;
027  }
028
029  /**
030   * Return the connection to use to capture the query plans.
031   */
032  public Connection getConnection() {
033    return connection;
034  }
035
036  /**
037   * Set the connection to use to capture the query plans.
038   */
039  public void setConnection(Connection connection) {
040    this.connection = connection;
041  }
042
043  /**
044   * Return true if the captured query plan is stored.
045   */
046  public boolean isStore() {
047    return store;
048  }
049
050  /**
051   * Set to true to store the captured query plan.
052   */
053  public void setStore(boolean store) {
054    this.store = store;
055  }
056
057  /**
058   * Return the epoch time after which the query plan was capture (to be included).
059   */
060  public long getSince() {
061    return since;
062  }
063
064  /**
065   * Set the epoch time after which the query plan was captured.
066   * <p>
067   * This is used to only capture plans that have changed since a given time (like the time of last capture).
068   * </p>
069   *
070   * @param since The time after which the query plan was captured to be included
071   */
072  public void setSince(long since) {
073    this.since = since;
074  }
075
076  /**
077   * Process consume the query plan.
078   */
079  public void process(MetaQueryPlan plan) {
080    plans.add(plan);
081  }
082
083  /**
084   * Return true if the bean type should be included in the query plan capture.
085   */
086  public boolean includeType(Class<?> beanType) {
087    return includedBeanTypes == null || includedBeanTypes.isEmpty() || includedBeanTypes.contains(beanType);
088  }
089
090  /**
091   * Return true if the label should be included in the query plan capture.
092   */
093  public boolean includeLabel(String label) {
094    return includedLabels == null || includedLabels.isEmpty() || includedLabels.contains(label);
095  }
096
097}


text:
<?xml version="1.0" encoding="UTF-8"?>
<tei xmlns="http://www.tei-c.org/ns/1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:mml="http://www.w3.org/1998/Math/MathML">
	<teiHeader>
		<fileDesc>
			<sourceDesc>
				<biblStruct>
					<analytic>
						<author>

						<affiliation>
							<orgName type="department">Institute for Information Systems</orgName>,
							<orgName type="institution">ETH Zurich</orgName>
							<lb/>
							<address>
								<postCode>CH-8092</postCode>
								<settlement>Zurich</settlement>,
								<country>Switzerland</country>
							</address>
						</affiliation>

						</author>
					</analytic>
				</biblStruct>
			</sourceDesc>
		</fileDesc>
	</teiHeader>
</tei>


text:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<script>
var test_name = '<?php echo $_GET["testname"]; ?>';
var data = {
  'cookie_val': document.cookie,
  'test_name': test_name
};
window.parent.postMessage(data, '*');
</script>
</html>


text:
'use strict';

var express = require('express');
var controller = require('./misc.controller');
var auth = require('../../auth/auth.service');

var router = express.Router();

router.post('/reseed', auth.hasRole('admin'), controller.reseed);

module.exports = router;


text:
package com.desmetRobotics.utils.gamepad;

/**
 *
 * @author John
 */
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.buttons.Button;
import edu.wpi.first.wpilibj.buttons.JoystickButton;

public class Gamepad_XBox360Number2 extends Gamepad{
    private Joystick joystick;

    private final double DPAD_THRESHOLD = 0.5;

    public final Button A_BUTTON;
    public final Button B_BUTTON;
    public final Button X_BUTTON;
    public final Button Y_BUTTON;
    public final Button LEFT_BUMPER;
    public final Button RIGHT_BUMPER;
    public final Button BACK_BUTTON;
    public final Button START_BUTTON;
    public final Button LEFT_JOYSTICK_BUTTON;
    public final Button RIGHT_JOYSTICK_BUTTON;
    public final Button DPAD_UP;
    public final Button DPAD_DOWN;
    public final Button DPAD_RIGHT;
    public final Button DPAD_LEFT;

    public Gamepad_XBox360Number2(int port) {
        joystick = new Joystick(port);
        A_BUTTON = new JoystickButton(joystick, 1);
        B_BUTTON = new JoystickButton(joystick, 2);
        X_BUTTON = new JoystickButton(joystick, 3);
        Y_BUTTON = new JoystickButton(joystick, 4);
        LEFT_BUMPER = new JoystickButton(joystick, 5);
        RIGHT_BUMPER = new JoystickButton(joystick, 6);
        BACK_BUTTON = new JoystickButton(joystick, 7);
        START_BUTTON = new JoystickButton(joystick, 8);
        LEFT_JOYSTICK_BUTTON = new JoystickButton(joystick, 9);
        RIGHT_JOYSTICK_BUTTON = new JoystickButton(joystick, 10);

        DPAD_UP = new DPadButton(this, DPadButton.DPAD_UP);
        DPAD_DOWN = new DPadButton(this, DPadButton.DPAD_DOWN);
        DPAD_LEFT = new DPadButton(this, DPadButton.DPAD_LEFT);
        DPAD_RIGHT = new DPadButton(this, DPadButton.DPAD_RIGHT);
    }

    public double getLeftX() {
        return joystick.getRawAxis(1);
    }

    public double getLeftY() {
        return -joystick.getRawAxis(2);
    }

    public double getTriggerAxis() {
        return joystick.getRawAxis(3);
    }

    public double getRightX() {
        return joystick.getRawAxis(4);
    }

    public double getRightY() {
        return -joystick.getRawAxis(5);
    }

    public byte getDPadX() {
        return dPadToByte(joystick.getRawAxis(6));
    }

    public byte getDPadY() {
        return dPadToByte(joystick.getRawAxis(6));
    }

    public GamepadResult getJoysticks(){
        return new GamepadResult(getLeftX(),getLeftY(),getRightX(),getRightY());
    }

    protected byte dPadToByte(double value) {
        if(value >= DPAD_THRESHOLD){
            return 1;
        }
        else if(value <= -DPAD_THRESHOLD){
            return -1;
        }
        return 0;
    }
}


text:
package leeon.mobile.BBSBrowser.models;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class BlockObject implements Serializable {

	private static final long serialVersionUID = 2L;

	private String id = null;
	private String name = null;

	private List<BoardObject> recommendBoardList = new ArrayList<BoardObject>();
	private List<BoardObject> allBoardList = new ArrayList<BoardObject>();

	public BlockObject(String id, String name) {
		this.id = id;
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public List<BoardObject> getRecommendBoardList() {
		return recommendBoardList;
	}

	public void setRecommendBoardList(List<BoardObject> recommendBoardList) {
		this.recommendBoardList = recommendBoardList;
	}

	public List<BoardObject> getAllBoardList() {
		return allBoardList;
	}

	public void setAllBoardList(List<BoardObject> allBoardList) {
		this.allBoardList = allBoardList;
	}

	@Override
	public String toString() {
		return name + "(" + id + ")";
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		return id.equals(((BlockObject)obj).id);
	}
}


text:
:desc: Find out how open source chatbot framework Rasa Stack allows
       you to stream events to a message broker.

.. _brokers:

Event Brokers
=============

Rasa Core allows you to stream events to a message broker. The event broker
emits events into the event queue. It becomes part of the ``TrackerStore``
which you use when starting an ``Agent`` or launch ``rasa.core.run``.

All events are streamed to the broker as serialised dictionaries every time
the tracker updates it state. An example event emitted from the ``default``
tracker looks like this:

.. code-block:: json

    {
        "sender_id": "default",
        "timestamp": 1528402837.617099,
        "event": "bot",
        "text": "what your bot said",
        "data": "some data"
    }

The ``event`` field takes the event's ``type_name`` (for more on event
types, check out the :doc:`api/events` docs).

Rasa enables two possible brokers producers: Pika Event Broker and Kafka Event Broker.

Pika Event Broker
-----------------

The example implementation we're going to show you here uses `Pika <pika.readthedocs.io>`_,
the Python client library for `RabbitMQ <https://www.rabbitmq.com>`_.

Adding a Pika Event Broker Using the Endpoint Configuration
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

You can use an endpoint configuration file to instruct Rasa Core to stream
all events to your event broker. To do so, add the following section to your
endpoint configuration, e.g. ``endpoints.yml``:

.. literalinclude:: ../../data/test_endpoints/event_brokers/pika_endpoint.yml

Then instruct Rasa Core to use the endpoint configuration and Pika producer by adding
``--event_broker pika_producer`` and ``--endpoints <path to your endpoint configuration`` as following example:

.. code-block:: shell

    python3 -m rasa.core.run -d models/dialogue -u models/nlu/current --event_broker pika_producer --endpoints endpoints.yml

Adding a Pika Event Broker in Python
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Here is how you add it using Python code:

.. code-block:: python

    from rasa.core.event_brokers.pika_producer import PikaProducer
    from rasa_platform.core.tracker_store import InMemoryTrackerStore

    pika_broker = PikaProducer('localhost',
                                'username',
                                'password',
                                queue='rasa_core_events')

    tracker_store = InMemoryTrackerStore(db=db, event_broker=pika_broker)

Implementing a Pika Event Consumer
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

You need to have a RabbitMQ server running, as well as another application
that consumes the events. This consumer to needs to implement Pika's
``start_consuming()`` method with a ``callback`` action. Here's a simple
example:

.. code-block:: python

    import json
    import pika

    def _callback(self, ch, method, properties, body):
            # Do something useful with your incoming message body here, e.g.
            # saving it to a database
            print('Received event {}'.format(json.loads(body)))

    if __name__ == '__main__':

        # RabbitMQ credentials with username and password
        credentials = pika.PlainCredentials('username', 'password')

        # pika connection to the RabbitMQ host - typically 'rabbit' in a
        # docker environment, or 'localhost' in a local environment
        connection = pika.BlockingConnection(
            pika.ConnectionParameters('rabbit', credentials=credentials))

        # start consumption of channel
        channel = connection.channel()
        channel.basic_consume(_callback,
                              queue='rasa_core_events',
                              no_ack=True)
        channel.start_consuming()

Kafka Event Broker
------------------

It is possible to use `Kafka <https://kafka.apache.org/>`_ as main broker to you events. In this example
we are going to use the `python-kafka <https://kafka-python.readthedocs.io/en/master/usage.html>`_
library, a Kafka client written in Python.

Adding a Kafka Event Broker Using the Endpoint Configuration
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

As for the other brokers, you can use an endpoint configuration file to instruct Rasa Core to stream
all events to this event broker. To do it, add the following section to your
endpoint configuration.

Pass the ``endpoints.yml`` file as argument with ``--endpoints <path to your endpoint configuration>``
when running Rasa, and select Kafka producer with ``--kafka_broker kafka_producer``, as following example:

.. code-block:: shell

    python3 -m rasa.core.run -d models/dialogue -u models/nlu/current --event_broker kafka_producer --endpoints endpoints.yml

Using ``SASL_PLAINTEXT`` protocol the endpoints file must have the following entries:

.. literalinclude:: ../../data/test_endpoints/event_brokers/kafka_plaintext_endpoint.yml

In the case of using SSL protocol the endpoints file must looks like:

.. literalinclude:: ../../data/test_endpoints/event_brokers/kafka_ssl_endpoint.yml

Adding a Kafka Broker in Python
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The code below shows an example on how to instantiate a Kafka producer in you script.

.. code-block:: python

    from rasa.core.event_brokers.kafka_producer import KafkaProducer
    from rasa.core.tracker_store import InMemoryTrackerStore

    kafka_broker = KafkaProducer(host='localhost:9092',
                                 topic='rasa_core_events')

    tracker_store = InMemoryTrackerStore(event_broker=kafka_broker)

The host variable can be either a list of brokers adresses or a single one.
If only one broker address is available, the client will connect to it and
request the cluster Metadata.
Therefore, the remain brokers in the cluster can be discovered
automatically through the data served by the first connected broker.

To pass more than one broker address as argument, they must be passed in a
list of strings. e.g.:

.. code-block:: python

    kafka_broker = KafkaProducer(host=['kafka_broker_1:9092',
                                       'kafka_broker_2:2030',
                                       'kafka_broker_3:9092'],
                                 topic='rasa_core_events')

Authentication and authorization
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Rasa Core's Kafka producer accepts two types of security protocols - ``SASL_PLAINTEXT`` and ``SSL``.

For development environment, or if the brokers servers and clients are located
into the same machine, you can use simple authentication with ``SASL_PLAINTEXT``.
By using this protocol, the credentials and messages exchanged between the clients and servers
will be sent in plaintext. Thus, this is not the most secure approach, but since it's simple
to configure, it is useful for simple cluster configurations.
``SASL_PLAINTEXT`` protocol requires the setup of the ``username`` and ``password``
previously configured in the broker server.

.. code-block:: python

    kafka_broker = KafkaProducer(host='kafka_broker:9092',
                                 sasl_plain_username='kafka_username',
                                 sasl_plain_password='kafka_password',
                                 security_protocol='SASL_PLAINTEXT',
                                 topic='rasa_core_events')

If the clients or the brokers in the kafka cluster are located in different
machines, it's important to use ssl protocal to assure encryption of data and client
authentication. After generating valid certificates for the brokers and the
clients, the path to the certificate and key generated for the producer must
be provided as arguments, as well as the CA's root certificate.

.. code-block:: python

    kafka_broker = KafkaProducer(host='kafka_broker:9092',
                                 ssl_cafile='CARoot.pem',
                                 ssl_certfile='certificate.pem',
                                 ssl_keyfile='key.pem',
                                 ssl_check_hostname=True,
                                 security_protocol='SSL',
                                 topic='rasa_core_events')

If the ``ssl_check_hostname`` parameter is enabled, the clients will verify
if the broker's hostname matches the certificate. It's used on client's connections
and inter-broker connections to prevent man-in-the-middle attacks.

Implementing a Kafka Event Consumer
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The parameters used to create a Kafka consumer is the same used on the producer creation,
according to the security protocol being used. The following implementation shows an example:

.. code-block:: python

    from kafka import KafkaConsumer
    from json import loads

    consumer = KafkaConsumer('rasa_core_events',
                              bootstrap_servers=['localhost:29093'],
                              value_deserializer=lambda m: json.loads(m.decode('utf-8')),
                              security_protocol='SSL',
                              ssl_check_hostname=False,
                              ssl_cafile='CARoot.pem',
                              ssl_certfile='certificate.pem',
                              ssl_keyfile='key.pem')

    for message in consumer:
        print(message.value)

.. include:: feedback.inc


text:
#include "config.h"
#include "wine/port.h"

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#include <ctype.h>

#include "wine/debug.h"
#include "wine/exception.h"
#include "wine/library.h"
#include "wine/unicode.h"
#include "winnt.h"
#include "winternl.h"
#include "ntdll_misc.h"

WINE_DECLARE_DEBUG_CHANNEL(tid);
WINE_DECLARE_DEBUG_CHANNEL(timestamp);

static struct __wine_debug_functions default_funcs;

/* ---------------------------------------------------------------------- */

/* get the debug info pointer for the current thread */
static inline struct debug_info *get_info(void)
{
    return ntdll_get_thread_data()->debug_info;
}

/* allocate some tmp space for a string */
static char *get_temp_buffer( size_t n )
{
    struct debug_info *info = get_info();
    char *res = info->str_pos;

    if (res + n >= &info->strings[sizeof(info->strings)]) res = info->strings;
    info->str_pos = res + n;
    return res;
}

/* release extra space that we requested in gimme1() */
static void release_temp_buffer( char *ptr, size_t size )
{
    struct debug_info *info = get_info();
    info->str_pos = ptr + size;
}

/***********************************************************************
 *		NTDLL_dbgstr_an
 */
static const char *NTDLL_dbgstr_an( const char *src, int n )
{
    const char *res;
    struct debug_info *info = get_info();
    /* save current position to restore it on exception */
    char *old_pos = info->str_pos;

    __TRY
    {
        res = default_funcs.dbgstr_an( src, n );
    }
    __EXCEPT_PAGE_FAULT
    {
        release_temp_buffer( old_pos, 0 );
        return "(invalid)";
    }
    __ENDTRY
    return res;
}

/***********************************************************************
 *		NTDLL_dbgstr_wn
 */
static const char *NTDLL_dbgstr_wn( const WCHAR *src, int n )
{
    const char *res;
    struct debug_info *info = get_info();
    /* save current position to restore it on exception */
    char *old_pos = info->str_pos;

    __TRY
    {
        res = default_funcs.dbgstr_wn( src, n );
    }
    __EXCEPT_PAGE_FAULT
    {
        release_temp_buffer( old_pos, 0 );
        return "(invalid)";
    }
    __ENDTRY
     return res;
}

/***********************************************************************
 *		NTDLL_dbg_vprintf
 */
static int NTDLL_dbg_vprintf( const char *format, va_list args )
{
    struct debug_info *info = get_info();
    int end;

    int ret = vsnprintf( info->out_pos, sizeof(info->output) - (info->out_pos - info->output),
                         format, args );

    /* make sure we didn't exceed the buffer length
     * the two checks are due to glibc changes in vsnprintfs return value
     * the buffer size can be exceeded in case of a missing \n in
     * debug output */
    if ((ret == -1) || (ret >= sizeof(info->output) - (info->out_pos - info->output)))
    {
       fprintf( stderr, "wine_dbg_vprintf: debugstr buffer overflow (contents: '%s')\n",
                info->output);
       info->out_pos = info->output;
       abort();
    }

    for (end = ret; end > 0; end--) if (info->out_pos[end - 1] == '\n') break;

    if (!end) info->out_pos += ret;
    else
    {
        char *pos = info->output;
        write( 2, pos, info->out_pos + end - pos );
        /* move beginning of next line to start of buffer */
        memmove( pos, info->out_pos + end, ret - end );
        info->out_pos = pos + ret - end;
    }
    return ret;
}

/***********************************************************************
 *		NTDLL_dbg_vlog
 */
static int NTDLL_dbg_vlog( enum __wine_debug_class cls, struct __wine_debug_channel *channel,
                           const char *function, const char *format, va_list args )
{
    static const char * const classes[] = { "fixme", "err", "warn", "trace" };
    struct debug_info *info = get_info();
    int ret = 0;

    /* only print header if we are at the beginning of the line */
    if (info->out_pos == info->output || info->out_pos[-1] == '\n')
    {
        if (TRACE_ON(timestamp))
        {
            ULONG ticks = NtGetTickCount();
            ret = wine_dbg_printf( "%3u.%03u:", ticks / 1000, ticks % 1000 );
        }
        if (TRACE_ON(tid))
            ret += wine_dbg_printf( "%04x:", GetCurrentThreadId() );
        if (cls < sizeof(classes)/sizeof(classes[0]))
            ret += wine_dbg_printf( "%s:%s:%s ", classes[cls], channel->name, function );
    }
    if (format)
        ret += NTDLL_dbg_vprintf( format, args );
    return ret;
}

static const struct __wine_debug_functions funcs =
{
    get_temp_buffer,
    release_temp_buffer,
    NTDLL_dbgstr_an,
    NTDLL_dbgstr_wn,
    NTDLL_dbg_vprintf,
    NTDLL_dbg_vlog
};

/***********************************************************************
 *		debug_init
 */
void debug_init(void)
{
    __wine_dbg_set_functions( &funcs, &default_funcs, sizeof(funcs) );
}


text:
import collections
import json

with open("troika_backgrounds.txt") as f:
    backgrounds_txt = collections.deque(f.readlines())

def nextline():
    return backgrounds_txt and backgrounds_txt.popleft().strip()

backgrounds = []
while backgrounds_txt:
    name = nextline()
    description = nextline()

    assert(nextline() == "")
    assert(nextline() == "Possessions")

    possessions = []
    while True:
        possession = nextline()
        if not possession:
            break
        possessions.append(possession)

    assert(nextline() == "Skills")

    skills = []
    while True:
        skill = nextline()
        if not skill:
            break
        skills.append(skill)

    specials = []
    if backgrounds_txt and backgrounds_txt[0].strip() == "Special":
        backgrounds_txt.popleft()
        while True:
            special = backgrounds_txt and nextline()
            if not special:
                break
            specials.append(special)

    backgrounds.append({
        "name": name,
        "description": description,
        "possessions": possessions,
        "skills": skills,
        "special": " ".join(specials)
    })

print(json.dumps(backgrounds, indent=4))