<commit_before>#include<malloc.h>
#include<stdio.h>
#define OK 1
#define ERROR 0
#define STACK_INIT_SIZE 100 // 存储空间初始分配量
#define STACKINCREMENT 10 // 存储空间分配增量

typedef int SElemType; // 定义栈元素类型
typedef int Status; // Status是函数的类型,其值是函数结果状态代码，如OK等

struct SqStack
{
     SElemType *base; // 在栈构造之前和销毁之后，base的值为NULL
     SElemType *top; // 栈顶指针
     int stacksize;  // 当前已分配的存储空间，以元素为单位

     Status InitStack()
	{
	// 构造一个空栈S，该栈预定义大小为STACK_INIT_SIZE
	// 请补全代码
		base=malloc(STACK_INIT_SIZE*(sizeof(SElemType)));
		if(base=NULL)return ERROR;
		top=base+1;
		stacksize=STACK_INIT_SIZE;

		return OK;
	}

	Status Push(SElemType e)
	{
		// 在栈S中插入元素e为新的栈顶元素
		// 请补全代码
		if(top-base>=stacksize){

			base=remalloc(base,(stacksize+STACKINCREMENT)*sizeof(Element));

			if(base==NULL){

				return ERROR;
			}
		}else{

			*top=e;
			top++;
		}

		return OK;

	}

	Status Pop(SElemType &e)
	{
		// 若栈不空，则删除S的栈顶元素，用e返回其值，并返回OK；否则返回ERROR
		// 请补全代码
		if( top-base<=1){
			return ERROR;
		}

		e=*(--top);

		return OK;
	}

	Status GetTop(SElemType &e)
	{
	// 若栈不空，则用e返回S的栈顶元素，并返回OK；否则返回ERROR
	// 请补全代码
		if( top-base<=1){
			return ERROR;
		}

		e=*(top-1);

		return OK;

	}

	int StackLength()
	{
	// 返回栈S的元素个数
	// 请补全代码

		return top-base-1;

	}

	Status StackTraverse(SqStack S)
	{
	// 从栈顶到栈底依次输出栈中的每个元素
		SElemType *p = (SElemType *)malloc(sizeof(SElemType));
		p = *top;        //请填空
		if(StackLength() ==0 )printf("The Stack is Empty!"); //请填空
		else
		{
			printf("The Stack is: ");
			p--;
			while(p-base>1)            //请填空
			{
				printf("%d ", *p);
				p--;               //请填空
			}
		}
		printf("\n");
		return OK;
	}
}; // 顺序栈

int main()
{
     int a;
     SqStack S;
	SElemType x, e;
     if(S.InitStack())    // 判断顺序表是否创建成功，请填空
{
	printf("A Stack Has Created.\n");
}
while(1)
	{
    printf("1:Push \n2:Pop \n3:Get the Top \n4:Return the Length of the Stack\n5:Load the Stack\n0:Exit\nPlease choose:\n");
	scanf("%d",&a);
		switch(a)
		{
			case 1: scanf("%d", &x);
		      if(S.Push(x)) printf("Push Error!\n"); // 判断Push是否合法，请填空
		      else printf("The Element %d is Successfully Pushed!\n", x);
		      break;
		case 2: if(S.Pop(e)) printf("Pop Error!\n"); // 判断Pop是否合法，请填空
			  else printf("The Element %d is Successfully Poped!\n", e);
		  	  break;
		case 3: if(S.top(e))printf("Get Top Error!\n"); // 判断Get Top是否合法，请填空
			  else printf("The Top Element is %d!\n", e);
		   	  break;
			case 4: printf("The Length of the Stack is %d!\n",S.StackLength()); //请填空
				  break;
			case 5: S.StackTraverse()  //请填空
				  break;
			case 0: return 1;
		}
	}
}<commit_msg>update uoj8583<commit_after>#include<malloc.h>
#include<stdio.h>
#define OK 1
#define ERROR 0
#define STACK_INIT_SIZE 100 // 存储空间初始分配量
#define STACKINCREMENT 10 // 存储空间分配增量

typedef int SElemType; // 定义栈元素类型
typedef int Status; // Status是函数的类型,其值是函数结果状态代码，如OK等

struct SqStack
{
     SElemType *base; // 在栈构造之前和销毁之后，base的值为NULL
     SElemType *top; // 栈顶指针
     int stacksize;  // 当前已分配的存储空间，以元素为单位

     Status InitStack()
	{
	// 构造一个空栈S，该栈预定义大小为STACK_INIT_SIZE
	// 请补全代码
		base=(SElemType*) malloc(STACK_INIT_SIZE*(sizeof(SElemType)));
		if(base=NULL)return ERROR;
		top=base+1;
		stacksize=STACK_INIT_SIZE;

		return OK;
	}

	Status Push(SElemType e)
	{
		// 在栈S中插入元素e为新的栈顶元素
		// 请补全代码
		if(top-base>=stacksize){

			base=realloc(base,(stacksize+STACKINCREMENT)*sizeof(SElement));

			if(base==NULL){

				return ERROR;
			}
		}else{

			*top=e;
			top++;
		}

		return OK;

	}

	Status Pop(SElemType &e)
	{
		// 若栈不空，则删除S的栈顶元素，用e返回其值，并返回OK；否则返回ERROR
		// 请补全代码
		if( top-base<=1){
			return ERROR;
		}

		e=*(--top);

		return OK;
	}

	Status GetTop(SElemType &e)
	{
	// 若栈不空，则用e返回S的栈顶元素，并返回OK；否则返回ERROR
	// 请补全代码
		if( top-base<=1){
			return ERROR;
		}

		e=*(top-1);

		return OK;

	}

	int StackLength()
	{
	// 返回栈S的元素个数
	// 请补全代码

		return top-base-1;

	}

	Status StackTraverse(SqStack S)
	{
	// 从栈顶到栈底依次输出栈中的每个元素
		SElemType *p = (SElemType *)malloc(sizeof(SElemType));
		p = *top;        //请填空
		if(StackLength() ==0 )printf("The Stack is Empty!"); //请填空
		else
		{
			printf("The Stack is: ");
			p--;
			while(p-base>1)            //请填空
			{
				printf("%d ", *p);
				p--;               //请填空
			}
		}
		printf("\n");
		return OK;
	}
}; // 顺序栈

int main()
{
     int a;
     SqStack S;
	SElemType x, e;
     if(S.InitStack())    // 判断顺序表是否创建成功，请填空
{
	printf("A Stack Has Created.\n");
}
while(1)
	{
    printf("1:Push \n2:Pop \n3:Get the Top \n4:Return the Length of the Stack\n5:Load the Stack\n0:Exit\nPlease choose:\n");
	scanf("%d",&a);
		switch(a)
		{
			case 1: scanf("%d", &x);
		      if(S.Push(x)) printf("Push Error!\n"); // 判断Push是否合法，请填空
		      else printf("The Element %d is Successfully Pushed!\n", x);
		      break;
		case 2: if(S.Pop(e)) printf("Pop Error!\n"); // 判断Pop是否合法，请填空
			  else printf("The Element %d is Successfully Poped!\n", e);
		  	  break;
		case 3: if(S.top(e))printf("Get Top Error!\n"); // 判断Get Top是否合法，请填空
			  else printf("The Top Element is %d!\n", e);
		   	  break;
			case 4: printf("The Length of the Stack is %d!\n",S.StackLength()); //请填空
				  break;
			case 5: S.StackTraverse()  //请填空
				  break;
			case 0: return 1;
		}
	}
}<|endoftext|>


<commit_before>// Copyright 2021 The Cross-Media Measurement Authors
//
// 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.

#include "wfa/panelmatch/client/privatemembership/decrypt_query_results.h"

#include <memory>
#include <string>
#include <utility>

#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "common_cpp/macros/macros.h"
#include "google/protobuf/repeated_field.h"
#include "private_membership/rlwe/batch/cpp/client/client.h"
#include "private_membership/rlwe/batch/proto/client.pb.h"
#include "private_membership/rlwe/batch/proto/shared.pb.h"
#include "wfa/panelmatch/client/exchangetasks/join_key.pb.h"
#include "wfa/panelmatch/client/privatemembership/event_data_decryptor.h"
#include "wfa/panelmatch/client/privatemembership/query.pb.h"
#include "wfa/panelmatch/common/compression/compressor.h"
#include "wfa/panelmatch/common/compression/make_compressor.h"

namespace wfa::panelmatch::client::privatemembership {

namespace {
using ClientEncryptedQueryResult =
    ::private_membership::batch::EncryptedQueryResult;
using ClientDecryptedQueryResult =
    ::private_membership::batch::DecryptedQueryResult;
using ClientDecryptQueriesRequest =
    ::private_membership::batch::DecryptQueriesRequest;
using ClientDecryptQueriesResponse =
    ::private_membership::batch::DecryptQueriesResponse;
using ::private_membership::batch::DecryptQueries;

absl::StatusOr<ClientDecryptQueriesResponse> RemoveRlwe(
    const DecryptQueryResultsRequest& request) {
  ClientDecryptQueriesRequest client_decrypt_queries_request;
  client_decrypt_queries_request.mutable_parameters()->ParseFromString(
      request.serialized_parameters());
  client_decrypt_queries_request.mutable_private_key()->ParseFromString(
      request.serialized_private_key());
  client_decrypt_queries_request.mutable_public_key()->ParseFromString(
      request.serialized_public_key());
  for (const EncryptedQueryResult& encrypted_query_result :
       request.encrypted_query_results()) {
    client_decrypt_queries_request.add_encrypted_queries()->ParseFromString(
        encrypted_query_result.serialized_encrypted_query_result());
  }
  return DecryptQueries(client_decrypt_queries_request);
}

absl::StatusOr<DecryptedEventDataSet> RemoveAesFromDecryptedQueryResult(
    const ClientDecryptedQueryResult& client_decrypted_query_result,
    const std::string& lookup_key, const std::string& hkdf_pepper) {
  DecryptEventDataRequest decrypt_event_data_request;
  decrypt_event_data_request.set_hkdf_pepper(hkdf_pepper);
  decrypt_event_data_request.mutable_lookup_key()->set_key(lookup_key);
  EncryptedEventData encrypted_event_data;
  encrypted_event_data.ParseFromString(client_decrypted_query_result.result());
  decrypt_event_data_request.mutable_encrypted_event_data_set()
      ->mutable_query_id()
      ->set_id(client_decrypted_query_result.query_metadata().query_id());
  *decrypt_event_data_request.mutable_encrypted_event_data_set()
       ->mutable_encrypted_event_data()
       ->mutable_ciphertexts() =
      *std::move(encrypted_event_data.mutable_ciphertexts());
  return DecryptEventData(decrypt_event_data_request);
}

absl::StatusOr<DecryptQueryResultsResponse> RemoveAes(
    const DecryptQueryResultsRequest& request,
    const ClientDecryptQueriesResponse& client_decrypt_queries_response) {
  DecryptQueryResultsResponse result;
  for (const ClientDecryptedQueryResult& client_decrypted_query_result :
       client_decrypt_queries_response.result()) {
    ASSIGN_OR_RETURN(
        *result.add_event_data_sets(),
        RemoveAesFromDecryptedQueryResult(client_decrypted_query_result,
                                          request.decrypted_join_key().key(),
                                          request.hkdf_pepper()));
  }
  return result;
}

absl::Status Decompress(const CompressionParameters& compression_parameters,
                        DecryptQueryResultsResponse& response) {
  ASSIGN_OR_RETURN(std::unique_ptr<Compressor> compressor,
                   MakeCompressor(compression_parameters));
  for (auto& data_set : *response.mutable_event_data_sets()) {
    for (Plaintext& plaintext : *data_set.mutable_decrypted_event_data()) {
      ASSIGN_OR_RETURN(*plaintext.mutable_payload(),
                       compressor->Decompress(plaintext.payload()));
    }
  }
  return absl::OkStatus();
}
}  // namespace

absl::StatusOr<DecryptQueryResultsResponse> DecryptQueryResults(
    const DecryptQueryResultsRequest& request) {
  // Step 1: Decrypt the encrypted query response
  ASSIGN_OR_RETURN(ClientDecryptQueriesResponse client_decrypt_queries_response,
                   RemoveRlwe(request));

  // If this is for a padding query, don't attempt to remove AES or decompress.
  // TODO(efoxepstein@): padding queries should be signalled explicitly.
  // Rather than detecting them based on the JKI, we should just have a boolean
  // flag in `request`.
  absl::string_view join_key_identifier = request.decrypted_join_key().key();
  if (join_key_identifier.empty() ||
      join_key_identifier.substr(0, 14) == "padding-query:") {
    DecryptQueryResultsResponse result;
    for (const ClientDecryptedQueryResult& client_decrypted_query_result :
         client_decrypt_queries_response.result()) {
      DecryptedEventDataSet* decrypted_data_set = result.add_event_data_sets();
      decrypted_data_set->mutable_query_id()->set_id(
          client_decrypted_query_result.query_metadata().query_id());
      decrypted_data_set->add_decrypted_event_data()->set_payload(
          client_decrypted_query_result.result());
    }
    return result;
  }

  // Step 2: Decrypt the encrypted event data
  ASSIGN_OR_RETURN(DecryptQueryResultsResponse result,
                   RemoveAes(request, client_decrypt_queries_response));

  // Step 3: Decompress the decrypted event data
  RETURN_IF_ERROR(Decompress(request.compression_parameters(), result));

  return result;
}
}  // namespace wfa::panelmatch::client::privatemembership
<commit_msg>Remove unnecessary check in private membership decryption (#333)<commit_after>// Copyright 2021 The Cross-Media Measurement Authors
//
// 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.

#include "wfa/panelmatch/client/privatemembership/decrypt_query_results.h"

#include <memory>
#include <string>
#include <utility>

#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "common_cpp/macros/macros.h"
#include "google/protobuf/repeated_field.h"
#include "private_membership/rlwe/batch/cpp/client/client.h"
#include "private_membership/rlwe/batch/proto/client.pb.h"
#include "private_membership/rlwe/batch/proto/shared.pb.h"
#include "wfa/panelmatch/client/exchangetasks/join_key.pb.h"
#include "wfa/panelmatch/client/privatemembership/event_data_decryptor.h"
#include "wfa/panelmatch/client/privatemembership/query.pb.h"
#include "wfa/panelmatch/common/compression/compressor.h"
#include "wfa/panelmatch/common/compression/make_compressor.h"

namespace wfa::panelmatch::client::privatemembership {

namespace {
using ClientEncryptedQueryResult =
    ::private_membership::batch::EncryptedQueryResult;
using ClientDecryptedQueryResult =
    ::private_membership::batch::DecryptedQueryResult;
using ClientDecryptQueriesRequest =
    ::private_membership::batch::DecryptQueriesRequest;
using ClientDecryptQueriesResponse =
    ::private_membership::batch::DecryptQueriesResponse;
using ::private_membership::batch::DecryptQueries;

absl::StatusOr<ClientDecryptQueriesResponse> RemoveRlwe(
    const DecryptQueryResultsRequest& request) {
  ClientDecryptQueriesRequest client_decrypt_queries_request;
  client_decrypt_queries_request.mutable_parameters()->ParseFromString(
      request.serialized_parameters());
  client_decrypt_queries_request.mutable_private_key()->ParseFromString(
      request.serialized_private_key());
  client_decrypt_queries_request.mutable_public_key()->ParseFromString(
      request.serialized_public_key());
  for (const EncryptedQueryResult& encrypted_query_result :
       request.encrypted_query_results()) {
    client_decrypt_queries_request.add_encrypted_queries()->ParseFromString(
        encrypted_query_result.serialized_encrypted_query_result());
  }
  return DecryptQueries(client_decrypt_queries_request);
}

absl::StatusOr<DecryptedEventDataSet> RemoveAesFromDecryptedQueryResult(
    const ClientDecryptedQueryResult& client_decrypted_query_result,
    const std::string& lookup_key, const std::string& hkdf_pepper) {
  DecryptEventDataRequest decrypt_event_data_request;
  decrypt_event_data_request.set_hkdf_pepper(hkdf_pepper);
  decrypt_event_data_request.mutable_lookup_key()->set_key(lookup_key);
  EncryptedEventData encrypted_event_data;
  encrypted_event_data.ParseFromString(client_decrypted_query_result.result());
  decrypt_event_data_request.mutable_encrypted_event_data_set()
      ->mutable_query_id()
      ->set_id(client_decrypted_query_result.query_metadata().query_id());
  *decrypt_event_data_request.mutable_encrypted_event_data_set()
       ->mutable_encrypted_event_data()
       ->mutable_ciphertexts() =
      *std::move(encrypted_event_data.mutable_ciphertexts());
  return DecryptEventData(decrypt_event_data_request);
}

absl::StatusOr<DecryptQueryResultsResponse> RemoveAes(
    const DecryptQueryResultsRequest& request,
    const ClientDecryptQueriesResponse& client_decrypt_queries_response) {
  DecryptQueryResultsResponse result;
  for (const ClientDecryptedQueryResult& client_decrypted_query_result :
       client_decrypt_queries_response.result()) {
    ASSIGN_OR_RETURN(
        *result.add_event_data_sets(),
        RemoveAesFromDecryptedQueryResult(client_decrypted_query_result,
                                          request.decrypted_join_key().key(),
                                          request.hkdf_pepper()));
  }
  return result;
}

absl::Status Decompress(const CompressionParameters& compression_parameters,
                        DecryptQueryResultsResponse& response) {
  ASSIGN_OR_RETURN(std::unique_ptr<Compressor> compressor,
                   MakeCompressor(compression_parameters));
  for (auto& data_set : *response.mutable_event_data_sets()) {
    for (Plaintext& plaintext : *data_set.mutable_decrypted_event_data()) {
      ASSIGN_OR_RETURN(*plaintext.mutable_payload(),
                       compressor->Decompress(plaintext.payload()));
    }
  }
  return absl::OkStatus();
}
}  // namespace

absl::StatusOr<DecryptQueryResultsResponse> DecryptQueryResults(
    const DecryptQueryResultsRequest& request) {
  // Step 1: Decrypt the encrypted query response
  ASSIGN_OR_RETURN(ClientDecryptQueriesResponse client_decrypt_queries_response,
                   RemoveRlwe(request));

  // If this is for a padding query, don't attempt to remove AES or decompress.
  absl::string_view join_key = request.decrypted_join_key().key();
  if (join_key.empty()) {
    DecryptQueryResultsResponse result;
    for (const ClientDecryptedQueryResult& client_decrypted_query_result :
         client_decrypt_queries_response.result()) {
      DecryptedEventDataSet* decrypted_data_set = result.add_event_data_sets();
      decrypted_data_set->mutable_query_id()->set_id(
          client_decrypted_query_result.query_metadata().query_id());
      decrypted_data_set->add_decrypted_event_data()->set_payload(
          client_decrypted_query_result.result());
    }
    return result;
  }

  // Step 2: Decrypt the encrypted event data
  ASSIGN_OR_RETURN(DecryptQueryResultsResponse result,
                   RemoveAes(request, client_decrypt_queries_response));

  // Step 3: Decompress the decrypted event data
  RETURN_IF_ERROR(Decompress(request.compression_parameters(), result));

  return result;
}
}  // namespace wfa::panelmatch::client::privatemembership
<|endoftext|>


<commit_before>
#include <cassert>
#include <iostream>

#include <scm/gl_core/buffer_objects.h>
#include <scm/gl_core/render_device.h>

namespace scm {
namespace gl {

template <class host_block_type>
uniform_block<host_block_type>::uniform_block()
{
}

template <class host_block_type>
uniform_block<host_block_type>::uniform_block(const render_device_ptr& in_device)
  : _host_block(new host_block_type())
{
    _device_block = in_device->create_buffer(BIND_UNIFORM_BUFFER, USAGE_STREAM_DRAW, sizeof(host_block_type));
}

template <class host_block_type>
uniform_block<host_block_type>::uniform_block(const render_device_ptr& in_device, const host_block_type& in_block)
  : _host_block(new host_block_type(in_block)),
{
    _device_block = in_device->create_buffer(BIND_UNIFORM_BUFFER, USAGE_STREAM_DRAW, sizeof(host_block_type));
    commit_block(in_device->main_context());
}

template <class host_block_type>
uniform_block<host_block_type>::~uniform_block()
{
    reset();
}

template <class host_block_type>
void
uniform_block<host_block_type>::reset()
{
    _device_block.reset();
    _host_block.reset();
}

template <class host_block_type>
void
uniform_block<host_block_type>::begin_manipulation(const render_context_ptr& in_context)
{
    assert(_device_block);
    assert(_host_block);

    _current_context = in_context;
}

template <class host_block_type>
void
uniform_block<host_block_type>::end_manipulation()
{
    assert(_device_block);
    assert(_host_block);

    commit_block(_current_context);
    _current_context.reset();
}

template <class host_block_type>
typename uniform_block<host_block_type>::block_type&
uniform_block<host_block_type>::operator*() const
{
    return (*_host_block);
}

template <class host_block_type>
typename uniform_block<host_block_type>::block_type*
uniform_block<host_block_type>::operator->() const
{
    return (_host_block.get());
}

template <class host_block_type>
typename uniform_block<host_block_type>::block_type*
uniform_block<host_block_type>::get_block() const
{
    return (_host_block.get());
}

template <class host_block_type>
const buffer_ptr&
uniform_block<host_block_type>::block_buffer() const
{
    return (_device_block);
}

template <class host_block_type>
void
uniform_block<host_block_type>::commit_block(const render_context_ptr& in_context)
{
    using namespace scm::gl;

    assert(_device_block);
    assert(_host_block);

    block_type* gpu_block = reinterpret_cast<block_type*>(in_context->map_buffer(_device_block, ACCESS_WRITE_INVALIDATE_BUFFER));

    if (memcpy(gpu_block, _host_block.get(), sizeof(block_type)) != gpu_block) {
        std::cerr << "uniform_block<>::commit_block(): error copying host block to gpu memory." << std::endl;
    }

    in_context->unmap_buffer(_device_block);
}

template <class host_block_type>
uniform_block<host_block_type>
make_uniform_block(const render_device_ptr& in_device)
{
    return (uniform_block<host_block_type>(in_device));
}

template <class host_block_type>
uniform_block<host_block_type>
make_uniform_block(const render_device_ptr& in_device, const host_block_type& in_block)
{
    return (uniform_block<host_block_type>(in_device, in_block));
}

} // namespace gl
} // namespace scm
<commit_msg>linux fix uniform_buffer_adaptor<commit_after>
#include <cassert>
#include <iostream>

#include <scm/gl_core/buffer_objects.h>
#include <scm/gl_core/render_device.h>

namespace scm {
namespace gl {

template <class host_block_type>
uniform_block<host_block_type>::uniform_block()
{
}

template <class host_block_type>
uniform_block<host_block_type>::uniform_block(const render_device_ptr& in_device)
  : _host_block(new host_block_type())
{
    _device_block = in_device->create_buffer(BIND_UNIFORM_BUFFER, USAGE_STREAM_DRAW, sizeof(host_block_type));
}

template <class host_block_type>
uniform_block<host_block_type>::uniform_block(const render_device_ptr& in_device, const host_block_type& in_block)
  : _host_block(new host_block_type(in_block))
{
    _device_block = in_device->create_buffer(BIND_UNIFORM_BUFFER, USAGE_STREAM_DRAW, sizeof(host_block_type));
    commit_block(in_device->main_context());
}

template <class host_block_type>
uniform_block<host_block_type>::~uniform_block()
{
    reset();
}

template <class host_block_type>
void
uniform_block<host_block_type>::reset()
{
    _device_block.reset();
    _host_block.reset();
}

template <class host_block_type>
void
uniform_block<host_block_type>::begin_manipulation(const render_context_ptr& in_context)
{
    assert(_device_block);
    assert(_host_block);

    _current_context = in_context;
}

template <class host_block_type>
void
uniform_block<host_block_type>::end_manipulation()
{
    assert(_device_block);
    assert(_host_block);

    commit_block(_current_context);
    _current_context.reset();
}

template <class host_block_type>
typename uniform_block<host_block_type>::block_type&
uniform_block<host_block_type>::operator*() const
{
    return (*_host_block);
}

template <class host_block_type>
typename uniform_block<host_block_type>::block_type*
uniform_block<host_block_type>::operator->() const
{
    return (_host_block.get());
}

template <class host_block_type>
typename uniform_block<host_block_type>::block_type*
uniform_block<host_block_type>::get_block() const
{
    return (_host_block.get());
}

template <class host_block_type>
const buffer_ptr&
uniform_block<host_block_type>::block_buffer() const
{
    return (_device_block);
}

template <class host_block_type>
void
uniform_block<host_block_type>::commit_block(const render_context_ptr& in_context)
{
    using namespace scm::gl;

    assert(_device_block);
    assert(_host_block);

    block_type* gpu_block = reinterpret_cast<block_type*>(in_context->map_buffer(_device_block, ACCESS_WRITE_INVALIDATE_BUFFER));

    if (memcpy(gpu_block, _host_block.get(), sizeof(block_type)) != gpu_block) {
        std::cerr << "uniform_block<>::commit_block(): error copying host block to gpu memory." << std::endl;
    }

    in_context->unmap_buffer(_device_block);
}

template <class host_block_type>
uniform_block<host_block_type>
make_uniform_block(const render_device_ptr& in_device)
{
    return (uniform_block<host_block_type>(in_device));
}

template <class host_block_type>
uniform_block<host_block_type>
make_uniform_block(const render_device_ptr& in_device, const host_block_type& in_block)
{
    return (uniform_block<host_block_type>(in_device, in_block));
}

} // namespace gl
} // namespace scm
<|endoftext|>


<commit_before>#include <QSound>

#include "MoNv.h"
enum CAUSE{
    CANG_YAN_FA_DIAN=3001,
    TIAN_HUO_DUAN_KONG=3002,
    MO_NV_ZHI_NU=3003,
    MO_NV_ZHI_NU_ATTACK=30031,
    TI_SHEN_WAN_OU=3004,
    YONG_SHENG_YIN_SHI_JI=3005,
    TONG_KU_LIAN_JIE=3006,
    TONG_KU_LIAN_JIE_CARD=30061,
    MO_NENG_FAN_ZHUAN=3007
};

MoNv::MoNv()
{
    makeConnection();
    setMyRole(this);
    Button *cangYanFaDian, *tianHuoDuanKong, *tongKuLianJie;
    cangYanFaDian = new Button(3,QStringLiteral("苍炎法典"));
    buttonArea->addButton(cangYanFaDian);
    connect(cangYanFaDian,SIGNAL(buttonSelected(int)),this,SLOT(CangYanFaDian()));

    tianHuoDuanKong = new Button(4,QStringLiteral("天火断空"));
    buttonArea->addButton(tianHuoDuanKong);
    connect(tianHuoDuanKong,SIGNAL(buttonSelected(int)),this,SLOT(TianHuoDuanKong()));

    tongKuLianJie = new Button(5,QStringLiteral("痛苦链接"));
    buttonArea->addButton(tongKuLianJie);
    connect(tongKuLianJie,SIGNAL(buttonSelected(int)),this,SLOT(TongKuLianJie()));
}

int MoNv::checkFire()
{
    Player* myself=dataInterface->getMyself();
    SafeList<Card*> handcards = dataInterface->getHandCards();
    int fire = 0;
    for(int i=0; i<handcards.size();i++)
    {
        if(handcards[i]->getElement() == QStringLiteral("fire"))
            fire ++;
        if(myself->getTap() && handcards[i]->getType() == "attack" &&
                (handcards[i]->getElement() == "thunder" || handcards[i]->getElement() == "earth" || handcards[i]->getElement() == "wind"))
            fire ++;
    }
    return fire;
}

void MoNv::enbleFire()
{
    Player* myself=dataInterface->getMyself();
    if(myself->getTap())
    {
        handArea->enableTypeAndElement(QStringLiteral("attack"), QStringLiteral("thunder"));
        handArea->enableTypeAndElement(QStringLiteral("attack"), QStringLiteral("wind"));
        handArea->enableTypeAndElement(QStringLiteral("attack"), QStringLiteral("earth"));
    }
    handArea->enableElement(QStringLiteral("fire"));
}

void MoNv::enbleFireAttack(QString element)
{
    Player* myself=dataInterface->getMyself();
    if(myself->getTap())
    {
        if(element == "water")
            handArea->enableElement(element);
        if(element == "fire")
        {
            handArea->enableElement("fire");
            handArea->enableElement("thunder");
            handArea->enableElement("earth");
            handArea->enableElement("wind");
        }
    }
    else
    {
        handArea->enableElement(element);
    }
}

void MoNv::attacked(QString element,int hitRate)
{
    state=2;
    playerArea->setQuota(1);
    handArea->setQuota(1);

    decisionArea->enable(1);
    if(hitRate==0)
    {
        this->enbleFireAttack(element);
        handArea->enableElement("darkness");
    }
    handArea->disableMagic();
    handArea->enableElement("light");
    gui->alert();
    QSound::play("sound/Warning.wav");
}

void MoNv::normal()
{
    Role::normal();
    Player* myself=dataInterface->getMyself();
    int fire = checkFire();
    if(fire > 0)
        buttonArea->enable(3);
    if(fire > 1 && (myself->getToken(0)>0 || myself->getTap()))
        buttonArea->enable(4);
    if(myself->getEnergy()>0)
        buttonArea->enable(5);
    unactionalCheck();
}

void MoNv::CangYanFaDian()
{
    state = CANG_YAN_FA_DIAN;
    handArea->reset();
    playerArea->reset();
    tipArea->reset();

    this->enbleFire();

    handArea->setQuota(1);
    playerArea->setQuota(1);

    decisionArea->enable(1);
    decisionArea->disable(0);
}

void MoNv::TianHuoDuanKong()
{
    state = TIAN_HUO_DUAN_KONG;
    handArea->reset();
    playerArea->reset();
    tipArea->reset();

    this->enbleFire();

    handArea->setQuota(2);
    playerArea->setQuota(1);

    playerArea->setQuota(1);

    decisionArea->enable(1);
    decisionArea->disable(0);
}

void MoNv::TongKuLianJie()
{
    state = TONG_KU_LIAN_JIE;
    handArea->reset();
    playerArea->reset();
    tipArea->reset();

    playerArea->enableAll();

    playerArea->setQuota(1);

    decisionArea->enable(1);
    decisionArea->disable(0);
}

void MoNv::cardAnalyse()
{
    Role::cardAnalyse();

    switch (state)
    {
    case CANG_YAN_FA_DIAN:
    case TIAN_HUO_DUAN_KONG:
        playerArea->enableAll();
        break;
    case TI_SHEN_WAN_OU:
        playerArea->enableMate();
        break;
    case MO_NENG_FAN_ZHUAN:
        playerArea->enableEnemy();
        break;
    }
}

void MoNv::MoNvZhiNu()
{
    state = MO_NV_ZHI_NU;
    gui->reset();
    tipArea->setMsg(QStringLiteral("发动【魔女之怒】，并选择要摸取的手牌数量"));
    for(int i =0; i < 3 ; i ++)
        tipArea->addBoxItem(QString::number(i));
    tipArea->showBox();
    decisionArea->enable(0);
    decisionArea->enable(1);
}

void MoNv::TiShenWanOu()
{
    state=TI_SHEN_WAN_OU;
    gui->reset();
    tipArea->setMsg(QStringLiteral("是否发动替身玩偶"));
    handArea->setQuota(1);
    handArea->enableMagic();
    decisionArea->enable(1);
}

void MoNv::MoNengFanZhuan()
{
    state=MO_NENG_FAN_ZHUAN;
    gui->reset();
    tipArea->setMsg(QStringLiteral("是否发动魔能反转"));
    handArea->setQuota(2,9);
    handArea->enableMagic();
    decisionArea->enable(1);
}

void MoNv::askForSkill(network::Command* cmd)
{
    switch (cmd->respond_id()) {
    case MO_NV_ZHI_NU:
        MoNvZhiNu();
        break;
    case TI_SHEN_WAN_OU:
        TiShenWanOu();
        break;
    case MO_NENG_FAN_ZHUAN:
        MoNengFanZhuan();
        break;
    default:
        Role::askForSkill(cmd);
        break;
    }
}

void MoNv::onOkClicked()
{
    Player* myself=dataInterface->getMyself();
    SafeList<Card*> selectedCards;
    SafeList<Player*>selectedPlayers;

    selectedCards=handArea->getSelectedCards();
    selectedPlayers=playerArea->getSelectedPlayers();

    network::Action* action;
    network::Respond* respond;

    try{
    switch(state)
    {
    case 1:
        if(selectedCards[0]->getType()=="attack" && myself->getTap() &&
                (selectedCards[0]->getElement() == "thunder" || selectedCards[0]->getElement() == "earth" || selectedCards[0]->getElement() == "wind")){
            state = MO_NV_ZHI_NU_ATTACK;
            action = newAction(ACTION_ATTACK_SKILL, MO_NV_ZHI_NU_ATTACK);
            action->add_dst_ids(selectedPlayers[0]->getID());
            action->add_card_ids(selectedCards[0]->getID());
            usedAttack=true;
            usedMagic=usedSpecial=false;
            gui->reset();
            emit sendCommand(network::MSG_ACTION, action);
        }
        break;
    case TI_SHEN_WAN_OU:
        respond = new network::Respond();
        respond->set_src_id(myID);
        respond->set_respond_id(TI_SHEN_WAN_OU);
        respond->add_card_ids(selectedCards[0]->getID());
        respond->add_dst_ids(selectedPlayers[0]->getID());
        respond->add_args(1);// 1表示选择发动
        emit sendCommand(network::MSG_RESPOND, respond);
        gui->reset();
        break;
    case MO_NENG_FAN_ZHUAN:
        respond = new network::Respond();
        respond->set_src_id(myID);
        respond->set_respond_id(MO_NENG_FAN_ZHUAN);
        respond->add_dst_ids(selectedPlayers[0]->getID());
        for(int i =0; i < selectedCards.size();i++)
            respond->add_card_ids(selectedCards[i]->getID());
        respond->add_args(1);// 1表示选择发动
        emit sendCommand(network::MSG_RESPOND, respond);
        gui->reset();
        break;
    case MO_NV_ZHI_NU:
        respond = new network::Respond();
        respond->set_src_id(myID);
        respond->set_respond_id(MO_NV_ZHI_NU);
        respond->add_args(1);// 1表示选择发动
        respond->add_args(tipArea->getBoxCurrentText().toInt());
        emit sendCommand(network::MSG_RESPOND, respond);
        start =true;
		gui->reset();
        break;
    case CANG_YAN_FA_DIAN:
        action = newAction(ACTION_MAGIC_SKILL, CANG_YAN_FA_DIAN);
        action->set_src_id(myID);

        action->add_card_ids(selectedCards[0]->getID());
        action->add_dst_ids(selectedPlayers[0]->getID());

        emit sendCommand(network::MSG_ACTION, action);
        gui->reset();
        break;
    case TIAN_HUO_DUAN_KONG:
        action = newAction(ACTION_MAGIC_SKILL, TIAN_HUO_DUAN_KONG);
        action->set_src_id(myID);

        action->add_card_ids(selectedCards[0]->getID());
        action->add_card_ids(selectedCards[1]->getID());
        action->add_dst_ids(selectedPlayers[0]->getID());

        emit sendCommand(network::MSG_ACTION, action);
        gui->reset();
        break;
    case TONG_KU_LIAN_JIE:
        action = newAction(ACTION_MAGIC_SKILL, TONG_KU_LIAN_JIE);
        action->set_src_id(myID);
        action->add_dst_ids(selectedPlayers[0]->getID());

        action->add_args(1);

        emit sendCommand(network::MSG_ACTION, action);
        gui->reset();
        break;
    }
    }catch(int error){
        logic->onError(error);
    }
    Role::onOkClicked();
}

void MoNv::onCancelClicked()
{
    Role::onCancelClicked();

    network::Respond* respond;

    switch(state)
    {
    case MO_NV_ZHI_NU:
    case TI_SHEN_WAN_OU:
    case MO_NENG_FAN_ZHUAN:
        respond = new network::Respond();
        respond->set_src_id(myID);
        respond->set_respond_id(state);
        respond->add_args(0);
        emit sendCommand(network::MSG_RESPOND, respond);
        gui->reset();
        break;
    case CANG_YAN_FA_DIAN:
    case TIAN_HUO_DUAN_KONG:
    case TONG_KU_LIAN_JIE:
        normal();
        break;
    }
}
<commit_msg>魔女 痛苦链接<commit_after>#include <QSound>

#include "MoNv.h"
enum CAUSE{
    CANG_YAN_FA_DIAN=3001,
    TIAN_HUO_DUAN_KONG=3002,
    MO_NV_ZHI_NU=3003,
    MO_NV_ZHI_NU_ATTACK=30031,
    TI_SHEN_WAN_OU=3004,
    YONG_SHENG_YIN_SHI_JI=3005,
    TONG_KU_LIAN_JIE=3006,
    TONG_KU_LIAN_JIE_CARD=30061,
    MO_NENG_FAN_ZHUAN=3007
};

MoNv::MoNv()
{
    makeConnection();
    setMyRole(this);
    Button *cangYanFaDian, *tianHuoDuanKong, *tongKuLianJie;
    cangYanFaDian = new Button(3,QStringLiteral("苍炎法典"));
    buttonArea->addButton(cangYanFaDian);
    connect(cangYanFaDian,SIGNAL(buttonSelected(int)),this,SLOT(CangYanFaDian()));

    tianHuoDuanKong = new Button(4,QStringLiteral("天火断空"));
    buttonArea->addButton(tianHuoDuanKong);
    connect(tianHuoDuanKong,SIGNAL(buttonSelected(int)),this,SLOT(TianHuoDuanKong()));

    tongKuLianJie = new Button(5,QStringLiteral("痛苦链接"));
    buttonArea->addButton(tongKuLianJie);
    connect(tongKuLianJie,SIGNAL(buttonSelected(int)),this,SLOT(TongKuLianJie()));
}

int MoNv::checkFire()
{
    Player* myself=dataInterface->getMyself();
    SafeList<Card*> handcards = dataInterface->getHandCards();
    int fire = 0;
    for(int i=0; i<handcards.size();i++)
    {
        if(handcards[i]->getElement() == QStringLiteral("fire"))
            fire ++;
        if(myself->getTap() && handcards[i]->getType() == "attack" &&
                (handcards[i]->getElement() == "thunder" || handcards[i]->getElement() == "earth" || handcards[i]->getElement() == "wind"))
            fire ++;
    }
    return fire;
}

void MoNv::enbleFire()
{
    Player* myself=dataInterface->getMyself();
    if(myself->getTap())
    {
        handArea->enableTypeAndElement(QStringLiteral("attack"), QStringLiteral("thunder"));
        handArea->enableTypeAndElement(QStringLiteral("attack"), QStringLiteral("wind"));
        handArea->enableTypeAndElement(QStringLiteral("attack"), QStringLiteral("earth"));
    }
    handArea->enableElement(QStringLiteral("fire"));
}

void MoNv::enbleFireAttack(QString element)
{
    Player* myself=dataInterface->getMyself();
    if(myself->getTap())
    {
        if(element == "water")
            handArea->enableElement(element);
        if(element == "fire")
        {
            handArea->enableElement("fire");
            handArea->enableElement("thunder");
            handArea->enableElement("earth");
            handArea->enableElement("wind");
        }
    }
    else
    {
        handArea->enableElement(element);
    }
}

void MoNv::attacked(QString element,int hitRate)
{
    state=2;
    playerArea->setQuota(1);
    handArea->setQuota(1);

    decisionArea->enable(1);
    if(hitRate==0)
    {
        this->enbleFireAttack(element);
        handArea->enableElement("darkness");
    }
    handArea->disableMagic();
    handArea->enableElement("light");
    gui->alert();
    QSound::play("sound/Warning.wav");
}

void MoNv::normal()
{
    Role::normal();
    Player* myself=dataInterface->getMyself();
    int fire = checkFire();
    if(fire > 0)
        buttonArea->enable(3);
    if(fire > 1 && (myself->getToken(0)>0 || myself->getTap()))
        buttonArea->enable(4);
    if(myself->getEnergy()>0)
        buttonArea->enable(5);
    unactionalCheck();
}

void MoNv::CangYanFaDian()
{
    state = CANG_YAN_FA_DIAN;
    handArea->reset();
    playerArea->reset();
    tipArea->reset();

    this->enbleFire();

    handArea->setQuota(1);
    playerArea->setQuota(1);

    decisionArea->enable(1);
    decisionArea->disable(0);
}

void MoNv::TianHuoDuanKong()
{
    state = TIAN_HUO_DUAN_KONG;
    handArea->reset();
    playerArea->reset();
    tipArea->reset();

    this->enbleFire();

    handArea->setQuota(2);
    playerArea->setQuota(1);

    playerArea->setQuota(1);

    decisionArea->enable(1);
    decisionArea->disable(0);
}

void MoNv::TongKuLianJie()
{
    state = TONG_KU_LIAN_JIE;
    handArea->reset();
    playerArea->reset();
    tipArea->reset();

    playerArea->enableEnemy();

    playerArea->setQuota(1);

    decisionArea->enable(1);
    decisionArea->disable(0);
}

void MoNv::cardAnalyse()
{
    Role::cardAnalyse();

    switch (state)
    {
    case CANG_YAN_FA_DIAN:
    case TIAN_HUO_DUAN_KONG:
        playerArea->enableAll();
        break;
    case TI_SHEN_WAN_OU:
        playerArea->enableMate();
        break;
    case MO_NENG_FAN_ZHUAN:
        playerArea->enableEnemy();
        break;
    }
}

void MoNv::MoNvZhiNu()
{
    state = MO_NV_ZHI_NU;
    gui->reset();
    tipArea->setMsg(QStringLiteral("发动【魔女之怒】，并选择要摸取的手牌数量"));
    for(int i =0; i < 3 ; i ++)
        tipArea->addBoxItem(QString::number(i));
    tipArea->showBox();
    decisionArea->enable(0);
    decisionArea->enable(1);
}

void MoNv::TiShenWanOu()
{
    state=TI_SHEN_WAN_OU;
    gui->reset();
    tipArea->setMsg(QStringLiteral("是否发动替身玩偶"));
    handArea->setQuota(1);
    handArea->enableMagic();
    decisionArea->enable(1);
}

void MoNv::MoNengFanZhuan()
{
    state=MO_NENG_FAN_ZHUAN;
    gui->reset();
    tipArea->setMsg(QStringLiteral("是否发动魔能反转"));
    handArea->setQuota(2,9);
    handArea->enableMagic();
    decisionArea->enable(1);
}

void MoNv::askForSkill(network::Command* cmd)
{
    switch (cmd->respond_id()) {
    case MO_NV_ZHI_NU:
        MoNvZhiNu();
        break;
    case TI_SHEN_WAN_OU:
        TiShenWanOu();
        break;
    case MO_NENG_FAN_ZHUAN:
        MoNengFanZhuan();
        break;
    default:
        Role::askForSkill(cmd);
        break;
    }
}

void MoNv::onOkClicked()
{
    Player* myself=dataInterface->getMyself();
    SafeList<Card*> selectedCards;
    SafeList<Player*>selectedPlayers;

    selectedCards=handArea->getSelectedCards();
    selectedPlayers=playerArea->getSelectedPlayers();

    network::Action* action;
    network::Respond* respond;

    try{
    switch(state)
    {
    case 1:
        if(selectedCards[0]->getType()=="attack" && myself->getTap() &&
                (selectedCards[0]->getElement() == "thunder" || selectedCards[0]->getElement() == "earth" || selectedCards[0]->getElement() == "wind")){
            state = MO_NV_ZHI_NU_ATTACK;
            action = newAction(ACTION_ATTACK_SKILL, MO_NV_ZHI_NU_ATTACK);
            action->add_dst_ids(selectedPlayers[0]->getID());
            action->add_card_ids(selectedCards[0]->getID());
            usedAttack=true;
            usedMagic=usedSpecial=false;
            gui->reset();
            emit sendCommand(network::MSG_ACTION, action);
        }
        break;
    case TI_SHEN_WAN_OU:
        respond = new network::Respond();
        respond->set_src_id(myID);
        respond->set_respond_id(TI_SHEN_WAN_OU);
        respond->add_card_ids(selectedCards[0]->getID());
        respond->add_dst_ids(selectedPlayers[0]->getID());
        respond->add_args(1);// 1表示选择发动
        emit sendCommand(network::MSG_RESPOND, respond);
        gui->reset();
        break;
    case MO_NENG_FAN_ZHUAN:
        respond = new network::Respond();
        respond->set_src_id(myID);
        respond->set_respond_id(MO_NENG_FAN_ZHUAN);
        respond->add_dst_ids(selectedPlayers[0]->getID());
        for(int i =0; i < selectedCards.size();i++)
            respond->add_card_ids(selectedCards[i]->getID());
        respond->add_args(1);// 1表示选择发动
        emit sendCommand(network::MSG_RESPOND, respond);
        gui->reset();
        break;
    case MO_NV_ZHI_NU:
        respond = new network::Respond();
        respond->set_src_id(myID);
        respond->set_respond_id(MO_NV_ZHI_NU);
        respond->add_args(1);// 1表示选择发动
        respond->add_args(tipArea->getBoxCurrentText().toInt());
        emit sendCommand(network::MSG_RESPOND, respond);
        start =true;
		gui->reset();
        break;
    case CANG_YAN_FA_DIAN:
        action = newAction(ACTION_MAGIC_SKILL, CANG_YAN_FA_DIAN);
        action->set_src_id(myID);

        action->add_card_ids(selectedCards[0]->getID());
        action->add_dst_ids(selectedPlayers[0]->getID());

        emit sendCommand(network::MSG_ACTION, action);
        gui->reset();
        break;
    case TIAN_HUO_DUAN_KONG:
        action = newAction(ACTION_MAGIC_SKILL, TIAN_HUO_DUAN_KONG);
        action->set_src_id(myID);

        action->add_card_ids(selectedCards[0]->getID());
        action->add_card_ids(selectedCards[1]->getID());
        action->add_dst_ids(selectedPlayers[0]->getID());

        emit sendCommand(network::MSG_ACTION, action);
        gui->reset();
        break;
    case TONG_KU_LIAN_JIE:
        action = newAction(ACTION_MAGIC_SKILL, TONG_KU_LIAN_JIE);
        action->set_src_id(myID);
        action->add_dst_ids(selectedPlayers[0]->getID());

        action->add_args(1);

        emit sendCommand(network::MSG_ACTION, action);
        gui->reset();
        break;
    }
    }catch(int error){
        logic->onError(error);
    }
    Role::onOkClicked();
}

void MoNv::onCancelClicked()
{
    Role::onCancelClicked();

    network::Respond* respond;

    switch(state)
    {
    case MO_NV_ZHI_NU:
    case TI_SHEN_WAN_OU:
    case MO_NENG_FAN_ZHUAN:
        respond = new network::Respond();
        respond->set_src_id(myID);
        respond->set_respond_id(state);
        respond->add_args(0);
        emit sendCommand(network::MSG_RESPOND, respond);
        gui->reset();
        break;
    case CANG_YAN_FA_DIAN:
    case TIAN_HUO_DUAN_KONG:
    case TONG_KU_LIAN_JIE:
        normal();
        break;
    }
}
<|endoftext|>


<commit_before>#include "ModernGL-Constants.hpp"

#include "ModernGL-Types.hpp"

#define STR_VERSION(ver) # ver

void RegisterConstants(PyObject * module) {
	PyModule_AddObject(module, "ENABLE_NOTHING", CreateEnableFlagType(ENABLE_NOTHING));
	PyModule_AddObject(module, "ENABLE_BLEND", CreateEnableFlagType(ENABLE_BLEND));
	PyModule_AddObject(module, "ENABLE_CULL_FACE", CreateEnableFlagType(ENABLE_CULL_FACE));
	PyModule_AddObject(module, "ENABLE_DEPTH_TEST", CreateEnableFlagType(ENABLE_DEPTH_TEST));
	PyModule_AddObject(module, "ENABLE_MULTISAMPLE", CreateEnableFlagType(ENABLE_MULTISAMPLE));
	PyModule_AddObject(module, "ENABLE_ALL", CreateEnableFlagType(ENABLE_ALL));

	PyModule_AddStringConstant(module, "VERSION", STR_VERSION(MODERN_GL_VERSION));

	PyModule_AddStringConstant(module, "__AUTHOR_NAME__", "Szabolcs Dombi");
	PyModule_AddStringConstant(module, "__AUTHOR_EMAIL__", "cprogrammer1994@gmail.com");

	PyModule_AddObject(module, "screen", CreateFramebufferType(0, 0, 0));
}

#undef STR_VERSION
<commit_msg>better uppercase screen<commit_after>#include "ModernGL-Constants.hpp"

#include "ModernGL-Types.hpp"

#define STR_VERSION(ver) # ver

void RegisterConstants(PyObject * module) {
	PyModule_AddObject(module, "ENABLE_NOTHING", CreateEnableFlagType(ENABLE_NOTHING));
	PyModule_AddObject(module, "ENABLE_BLEND", CreateEnableFlagType(ENABLE_BLEND));
	PyModule_AddObject(module, "ENABLE_CULL_FACE", CreateEnableFlagType(ENABLE_CULL_FACE));
	PyModule_AddObject(module, "ENABLE_DEPTH_TEST", CreateEnableFlagType(ENABLE_DEPTH_TEST));
	PyModule_AddObject(module, "ENABLE_MULTISAMPLE", CreateEnableFlagType(ENABLE_MULTISAMPLE));
	PyModule_AddObject(module, "ENABLE_ALL", CreateEnableFlagType(ENABLE_ALL));

	PyModule_AddObject(module, "SCREEN", CreateFramebufferType(0, 0, 0));

	PyModule_AddStringConstant(module, "VERSION", STR_VERSION(MODERN_GL_VERSION));

	PyModule_AddStringConstant(module, "__AUTHOR_NAME__", "Szabolcs Dombi");
	PyModule_AddStringConstant(module, "__AUTHOR_EMAIL__", "cprogrammer1994@gmail.com");

}

#undef STR_VERSION
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <organization> nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"
#include "EventDispatcher.h"

class ObserverMock : public EventObserver
{
public:
    virtual void notify(const Event& event, int timeOutInSeconds)
    {
        mock().actualCall("notify").onObject(this).withParameterOfType("Event", "event", (void*) &event).withParameter("timeOutInSeconds", timeOutInSeconds);
    }
    virtual void notifyRegistration(EventObserver* newObserver)
    {
        mock().actualCall("notifyRegistration").onObject(this).withParameter("newObserver", newObserver);
    }
};

class EventComparator : public MockNamedValueComparator
{
public:
    virtual bool isEqual(const void* object1, const void* object2)
    {
        return ((Event*)object1)->type == ((Event*)object2)->type;
    }
    virtual SimpleString valueToString(const void* object)
    {
        return StringFrom(((Event*)object)->type);
    }
};

TEST_GROUP(EventDispatcher)
{
    Event event;
    EventDispatcher* dispatcher;
    ObserverMock observer;
    ObserverMock observer2;
    EventComparator eventComparator;

    void setup()
    {
        dispatcher = new EventDispatcher;
        mock().installComparator("Event", eventComparator);
    }
    void teardown()
    {
        delete dispatcher;
        mock().removeAllComparatorsAndCopiers();
    }
};

TEST(EventDispatcher, EventWithoutRegistrationsResultsIntoNoCalls)
{
    dispatcher->dispatchEvent(event, 10);
}

TEST(EventDispatcher, EventWithRegistrationForEventResultsIntoCallback)
{
    mock().expectOneCall("notify").onObject(&observer).withParameterOfType("Event", "event", &event).withParameter("timeOutInSeconds", 10);
    event.type = IMPORTANT_EVENT;

    dispatcher->registerObserver(IMPORTANT_EVENT, &observer);
    dispatcher->dispatchEvent(event, 10);
}

TEST(EventDispatcher, DifferentEventWithRegistrationDoesNotResultIntoCallback)
{
    event.type = LESS_IMPORTANT_EVENT;
    dispatcher->registerObserver(IMPORTANT_EVENT, &observer);
    dispatcher->dispatchEvent(event, 10);
}

TEST(EventDispatcher, RegisterTwoObserversResultIntoTwoCallsAndARegistrationNotification)
{
    mock().expectOneCall("notify").onObject(&observer).withParameterOfType("Event", "event", &event).withParameter("timeOutInSeconds", 10);
    mock().expectOneCall("notify").onObject(&observer2).withParameterOfType("Event", "event", &event).withParameter("timeOutInSeconds", 10);
    mock().expectOneCall("notifyRegistration").onObject(&observer).withParameter("newObserver", &observer2);

    event.type = IMPORTANT_EVENT;
    dispatcher->registerObserver(IMPORTANT_EVENT, &observer);
    dispatcher->registerObserver(IMPORTANT_EVENT, &observer2);
    dispatcher->dispatchEvent(event, 10);
}
<commit_msg>remove warning, cast from 'const void *' to 'Event *' drops const qualifier.<commit_after>/*
 * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <organization> nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"
#include "EventDispatcher.h"

class ObserverMock : public EventObserver
{
public:
    virtual void notify(const Event& event, int timeOutInSeconds)
    {
        mock().actualCall("notify").onObject(this).withParameterOfType("Event", "event", (void*) &event).withParameter("timeOutInSeconds", timeOutInSeconds);
    }
    virtual void notifyRegistration(EventObserver* newObserver)
    {
        mock().actualCall("notifyRegistration").onObject(this).withParameter("newObserver", newObserver);
    }
};

class EventComparator : public MockNamedValueComparator
{
public:
    virtual bool isEqual(const void* object1, const void* object2)
    {
        return ((const Event*)object1)->type == ((const Event*)object2)->type;
    }
    virtual SimpleString valueToString(const void* object)
    {
        return StringFrom(((const Event*)object)->type);
    }
};

TEST_GROUP(EventDispatcher)
{
    Event event;
    EventDispatcher* dispatcher;
    ObserverMock observer;
    ObserverMock observer2;
    EventComparator eventComparator;

    void setup()
    {
        dispatcher = new EventDispatcher;
        mock().installComparator("Event", eventComparator);
    }
    void teardown()
    {
        delete dispatcher;
        mock().removeAllComparatorsAndCopiers();
    }
};

TEST(EventDispatcher, EventWithoutRegistrationsResultsIntoNoCalls)
{
    dispatcher->dispatchEvent(event, 10);
}

TEST(EventDispatcher, EventWithRegistrationForEventResultsIntoCallback)
{
    mock().expectOneCall("notify").onObject(&observer).withParameterOfType("Event", "event", &event).withParameter("timeOutInSeconds", 10);
    event.type = IMPORTANT_EVENT;

    dispatcher->registerObserver(IMPORTANT_EVENT, &observer);
    dispatcher->dispatchEvent(event, 10);
}

TEST(EventDispatcher, DifferentEventWithRegistrationDoesNotResultIntoCallback)
{
    event.type = LESS_IMPORTANT_EVENT;
    dispatcher->registerObserver(IMPORTANT_EVENT, &observer);
    dispatcher->dispatchEvent(event, 10);
}

TEST(EventDispatcher, RegisterTwoObserversResultIntoTwoCallsAndARegistrationNotification)
{
    mock().expectOneCall("notify").onObject(&observer).withParameterOfType("Event", "event", &event).withParameter("timeOutInSeconds", 10);
    mock().expectOneCall("notify").onObject(&observer2).withParameterOfType("Event", "event", &event).withParameter("timeOutInSeconds", 10);
    mock().expectOneCall("notifyRegistration").onObject(&observer).withParameter("newObserver", &observer2);

    event.type = IMPORTANT_EVENT;
    dispatcher->registerObserver(IMPORTANT_EVENT, &observer);
    dispatcher->registerObserver(IMPORTANT_EVENT, &observer2);
    dispatcher->dispatchEvent(event, 10);
}
<|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (c) 2015 Mark Charlebois. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/**
 * @file simulator.cpp
 * A device simulator
 */

#include <px4_log.h>
#include <px4_tasks.h>
#include <px4_time.h>
#include <pthread.h>
#include <poll.h>
#include <systemlib/err.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <drivers/drv_led.h>

#include "simulator.h"

using namespace simulator;

static px4_task_t g_sim_task = -1;

Simulator *Simulator::_instance = NULL;

Simulator *Simulator::getInstance()
{
	return _instance;
}

bool Simulator::getMPUReport(uint8_t *buf, int len)
{
	return _mpu.copyData(buf, len);
}

bool Simulator::getRawAccelReport(uint8_t *buf, int len)
{
	return _accel.copyData(buf, len);
}

bool Simulator::getMagReport(uint8_t *buf, int len)
{
	return _mag.copyData(buf, len);
}

bool Simulator::getBaroSample(uint8_t *buf, int len)
{
	return _baro.copyData(buf, len);
}

bool Simulator::getGPSSample(uint8_t *buf, int len)
{
	return _gps.copyData(buf, len);
}

bool Simulator::getAirspeedSample(uint8_t *buf, int len)
{
	return _airspeed.copyData(buf, len);
}

void Simulator::write_MPU_data(void *buf)
{
	_mpu.writeData(buf);
}

void Simulator::write_accel_data(void *buf)
{
	_accel.writeData(buf);
}

void Simulator::write_mag_data(void *buf)
{
	_mag.writeData(buf);
}

void Simulator::write_baro_data(void *buf)
{
	_baro.writeData(buf);
}

void Simulator::write_gps_data(void *buf)
{
	_gps.writeData(buf);
}

void Simulator::write_airspeed_data(void *buf)
{
	_airspeed.writeData(buf);
}

int Simulator::start(int argc, char *argv[])
{
	int ret = 0;
	_instance = new Simulator();

	if (_instance) {
		drv_led_start();

		if (argv[2][1] == 's') {
			_instance->initializeSensorData();
#ifndef __PX4_QURT
			// Update sensor data
			_instance->pollForMAVLinkMessages(false);
#endif

		} else if (argv[2][1] == 'p') {
			// Update sensor data
			_instance->pollForMAVLinkMessages(true);

		} else {
			_instance->initializeSensorData();
			_instance->_initialized = true;
		}

	} else {
		PX4_WARN("Simulator creation failed");
		ret = 1;
	}

	return ret;
}

static void usage()
{
	PX4_WARN("Usage: simulator {start -[spt] |stop}");
	PX4_WARN("Simulate raw sensors:     simulator start -s");
	PX4_WARN("Publish sensors combined: simulator start -p");
	PX4_WARN("Dummy unit test data:     simulator start -t");
}

__BEGIN_DECLS
extern int simulator_main(int argc, char *argv[]);
__END_DECLS

extern "C" {

	int simulator_main(int argc, char *argv[])
	{
		int ret = 0;

		if (argc == 3 && strcmp(argv[1], "start") == 0) {
			if (strcmp(argv[2], "-s") == 0 ||
			    strcmp(argv[2], "-p") == 0 ||
			    strcmp(argv[2], "-t") == 0) {
				if (g_sim_task >= 0) {
					warnx("Simulator already started");
					return 0;
				}

				g_sim_task = px4_task_spawn_cmd("Simulator",
								SCHED_DEFAULT,
								SCHED_PRIORITY_MAX - 5,
								1500,
								Simulator::start,
								argv);

				// now wait for the command to complete
				while (true) {
					if (Simulator::getInstance() && Simulator::getInstance()->isInitialized()) {
						break;

					} else {
						usleep(100000);
					}
				}

			} else {
				usage();
				ret = -EINVAL;
			}

		} else if (argc == 2 && strcmp(argv[1], "stop") == 0) {
			if (g_sim_task < 0) {
				PX4_WARN("Simulator not running");

			} else {
				px4_task_delete(g_sim_task);
				g_sim_task = -1;
			}

		} else {
			usage();
			ret = -EINVAL;
		}

		return ret;
	}

}
<commit_msg>Simulator: All app names are lowercase!<commit_after>/****************************************************************************
 *
 *   Copyright (c) 2015 Mark Charlebois. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/**
 * @file simulator.cpp
 * A device simulator
 */

#include <px4_log.h>
#include <px4_tasks.h>
#include <px4_time.h>
#include <pthread.h>
#include <poll.h>
#include <systemlib/err.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <drivers/drv_led.h>

#include "simulator.h"

using namespace simulator;

static px4_task_t g_sim_task = -1;

Simulator *Simulator::_instance = NULL;

Simulator *Simulator::getInstance()
{
	return _instance;
}

bool Simulator::getMPUReport(uint8_t *buf, int len)
{
	return _mpu.copyData(buf, len);
}

bool Simulator::getRawAccelReport(uint8_t *buf, int len)
{
	return _accel.copyData(buf, len);
}

bool Simulator::getMagReport(uint8_t *buf, int len)
{
	return _mag.copyData(buf, len);
}

bool Simulator::getBaroSample(uint8_t *buf, int len)
{
	return _baro.copyData(buf, len);
}

bool Simulator::getGPSSample(uint8_t *buf, int len)
{
	return _gps.copyData(buf, len);
}

bool Simulator::getAirspeedSample(uint8_t *buf, int len)
{
	return _airspeed.copyData(buf, len);
}

void Simulator::write_MPU_data(void *buf)
{
	_mpu.writeData(buf);
}

void Simulator::write_accel_data(void *buf)
{
	_accel.writeData(buf);
}

void Simulator::write_mag_data(void *buf)
{
	_mag.writeData(buf);
}

void Simulator::write_baro_data(void *buf)
{
	_baro.writeData(buf);
}

void Simulator::write_gps_data(void *buf)
{
	_gps.writeData(buf);
}

void Simulator::write_airspeed_data(void *buf)
{
	_airspeed.writeData(buf);
}

int Simulator::start(int argc, char *argv[])
{
	int ret = 0;
	_instance = new Simulator();

	if (_instance) {
		drv_led_start();

		if (argv[2][1] == 's') {
			_instance->initializeSensorData();
#ifndef __PX4_QURT
			// Update sensor data
			_instance->pollForMAVLinkMessages(false);
#endif

		} else if (argv[2][1] == 'p') {
			// Update sensor data
			_instance->pollForMAVLinkMessages(true);

		} else {
			_instance->initializeSensorData();
			_instance->_initialized = true;
		}

	} else {
		PX4_WARN("Simulator creation failed");
		ret = 1;
	}

	return ret;
}

static void usage()
{
	PX4_WARN("Usage: simulator {start -[spt] |stop}");
	PX4_WARN("Simulate raw sensors:     simulator start -s");
	PX4_WARN("Publish sensors combined: simulator start -p");
	PX4_WARN("Dummy unit test data:     simulator start -t");
}

__BEGIN_DECLS
extern int simulator_main(int argc, char *argv[]);
__END_DECLS

extern "C" {

	int simulator_main(int argc, char *argv[])
	{
		int ret = 0;

		if (argc == 3 && strcmp(argv[1], "start") == 0) {
			if (strcmp(argv[2], "-s") == 0 ||
			    strcmp(argv[2], "-p") == 0 ||
			    strcmp(argv[2], "-t") == 0) {
				if (g_sim_task >= 0) {
					warnx("Simulator already started");
					return 0;
				}

				g_sim_task = px4_task_spawn_cmd("simulator",
								SCHED_DEFAULT,
								SCHED_PRIORITY_MAX - 5,
								1500,
								Simulator::start,
								argv);

				// now wait for the command to complete
				while (true) {
					if (Simulator::getInstance() && Simulator::getInstance()->isInitialized()) {
						break;

					} else {
						usleep(100000);
					}
				}

			} else {
				usage();
				ret = -EINVAL;
			}

		} else if (argc == 2 && strcmp(argv[1], "stop") == 0) {
			if (g_sim_task < 0) {
				PX4_WARN("Simulator not running");

			} else {
				px4_task_delete(g_sim_task);
				g_sim_task = -1;
			}

		} else {
			usage();
			ret = -EINVAL;
		}

		return ret;
	}

}
<|endoftext|>


<commit_before>/*
 * Copyright 2021 The CFU-Playground Authors
 * Copyright 2019 The TensorFlow Authors
 *
 * 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.
 */

#include "tensorflow/lite/kernels/internal/reference/integer_ops/conv_accel_gen_2.h"

#include <cstdio>

#include "gateware_constants.h"
#include "hps_cfu.h"
#include "tensorflow/lite/kernels/internal/common.h"

#if GATEWARE_GEN == 2

namespace tflite {
namespace reference_integer_ops {

namespace {

// Loads four post process parameters into the CFU
void LoadFourPostProcessParameters(int channel_start, const int32_t* bias_data,
                                   const int32_t* output_shift,
                                   const int32_t* output_multiplier) {
  for (int i = channel_start; i < channel_start + 4; i++) {
    cfu_set(REG_POST_PROCESS_BIAS, bias_data[i]);
    // Note : shift is stored as a negative number in tflite model
    cfu_set(REG_POST_PROCESS_SHIFT, -output_shift[i]);
    cfu_set(REG_POST_PROCESS_MULTIPLIER, output_multiplier[i]);
  }
}

// Loads filter parameters, correctly split between the two
// stores
void LoadFourFilterData(int channel_start, const RuntimeShape& filter_shape,
                        const uint32_t* data_base) {
  const int num_filter_words_per_output =
      filter_shape.Dims(1) * filter_shape.Dims(2) * filter_shape.Dims(3) / 4;
  const uint32_t* filter_data =
      data_base + channel_start * num_filter_words_per_output;

  size_t addr_base = 0;
  for (int i = channel_start; i < channel_start + 4; i += 2) {
    for (int store = 0; store < 2; store++) {
      uint32_t addr = addr_base;
      for (int j = 0; j < num_filter_words_per_output; j++) {
        uint32_t data = *filter_data++;
        cfu_setx(REG_FILTER_WRITE, (store << 16 | addr), data);
        addr++;
      }
    }
    addr_base += num_filter_words_per_output;
  }
}

// Collects a single ouput value and optionally places it into memory
inline void CollectValue(uint32_t*& p, int advance, bool write) {
  uint32_t val = cfu_get(REG_OUTPUT_WORD);
  if (write) {
    *p = val;
    p += advance;
  }
}

// Collects output from the accelerator into the output area
// Collects one word per output pixel
void CollectOutput(int channel, uint32_t* output, const int height,
                   const int width, const int depth) {
  const int num_pixels = height * width;
  const int num_words_per_pixel = depth / 4;

  uint32_t* p = output + channel / 4;

  for (int pixel = 0; pixel < num_pixels; pixel += 4) {
    CollectValue(p, num_words_per_pixel, true);
    CollectValue(p, num_words_per_pixel, pixel + 1 < num_pixels);
    CollectValue(p, num_words_per_pixel, pixel + 2 < num_pixels);
    CollectValue(p, num_words_per_pixel, pixel + 3 < num_pixels);
  }
}
};  // namespace

bool CanAccelerateConv4x4(const ConvParams& params,
                          const RuntimeShape& input_shape,
                          const RuntimeShape& filter_shape,
                          const RuntimeShape& output_shape,
                          const int32_t* bias_data) {
  // No padding allowed
  if (params.padding_type != PaddingType::kValid) return false;

  // Must have bias_data and single batch
  if (!bias_data) return false;
  const int batches = MatchingDim(input_shape, 0, output_shape, 0);
  if (batches != 1) return false;

  // Input and output depths must be a multiple of 16
  // NB: We could probably relax output depth to be a multiple of 4
  const int input_depth = input_shape.Dims(3);
  const int output_depth = output_shape.Dims(3);
  // if (input_depth % 16 != 0) return false;
  // if (output_depth % 16 != 0) return false;
  // Currently, only works where input and output depths are exactly 16
  if (input_depth != 16) return false;
  if (output_depth != 16) return false;

  // Must be 4x4
  const int filter_height = filter_shape.Dims(1);
  const int filter_width = filter_shape.Dims(2);
  if (filter_height != 4 || filter_width != 4) return false;

  // Must fit in filter word storag   e
  const int num_filter_words = input_depth * output_depth * 4 * 4 / 4;
  if (num_filter_words > NUM_FILTER_STORES * FILTER_WORDS_PER_STORE)
    return false;

  // Dilation must be 1
  if (params.dilation_height_factor != 1 || params.dilation_width_factor != 1)
    return false;

  // Stride must be 1
  const int stride_width = params.stride_width;
  const int stride_height = params.stride_height;
  if (stride_height != 1 || stride_width != 1) return false;

  return true;
}

// Accelerated Conv2D
void ConvPerChannel4x4(const ConvParams& params,
                       const int32_t* output_multiplier,
                       const int32_t* output_shift,
                       const RuntimeShape& input_shape,
                       const int8_t* input_data,
                       const RuntimeShape& filter_shape,
                       const int8_t* filter_data,
                       const RuntimeShape& bias_shape, const int32_t* bias_data,
                       const RuntimeShape& output_shape, int8_t* output_data) {
  // Calculates in trances of four channels (one output word)
  const int channels_per_tranche = 4;

  // Get parameters.
  const int32_t input_offset = params.input_offset;  // r = s(q - Z)
  // TODO: handle stride
  // const int stride_width = params.stride_width;
  // const int stride_height = params.stride_height;
  // TODO: handle padding
  // const int pad_width = params.padding_values.width;
  // const int pad_height = params.padding_values.height;
  const int32_t output_offset = params.output_offset;

  // Set min and max value of the output.
  const int32_t output_activation_min = params.quantized_activation_min;
  const int32_t output_activation_max = params.quantized_activation_max;

  // Consistency checks
  TFLITE_DCHECK_LE(output_activation_min, output_activation_max);
  TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4);
  TFLITE_DCHECK_EQ(filter_shape.DimensionsCount(), 4);
  TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4);
  const int input_depth = MatchingDim(input_shape, 3, filter_shape, 3);
  const int output_depth = MatchingDim(filter_shape, 0, output_shape, 3);
  TFLITE_DCHECK_EQ(bias_shape.FlatSize(), output_depth);

  // Get dimensions of the tensors.
  const int input_width = input_shape.Dims(2);
  const int output_height = output_shape.Dims(1);
  const int output_width = output_shape.Dims(2);

  const int num_output_values_per_tranche =
      output_width * output_height * channels_per_tranche;

  // Filter words required to calculate each tranche
  const int filter_words_per_channel =
      filter_shape.Dims(1) * filter_shape.Dims(2) * filter_shape.Dims(3) / 4;
  const int filter_words_per_tranche =
      filter_words_per_channel * channels_per_tranche;

  // Base address is bank address (4 words per bank) within 256K arena
  uint32_t input_base_addr =
      (reinterpret_cast<uint32_t>(input_data) & 0x3ffff) / 16;

  for (int channel = 0; channel < output_depth;
       channel += channels_per_tranche) {
    // Reset to ensure important state is initialized
    cfu_set(REG_ACCELERATOR_RESET, 0);

    // Configure simple values
    cfu_set(REG_INPUT_OFFSET, input_offset);
    cfu_set(REG_NUM_FILTER_WORDS, filter_words_per_tranche / 2);
    cfu_set(REG_OUTPUT_OFFSET, output_offset);
    cfu_set(REG_OUTPUT_ACTIVATION_MIN, output_activation_min);
    cfu_set(REG_OUTPUT_ACTIVATION_MAX, output_activation_max);
    cfu_set(REG_INPUT_BASE_ADDR, input_base_addr);
    cfu_set(REG_NUM_PIXELS_X, output_width);
    cfu_set(REG_PIXEL_ADVANCE_X, input_depth / 16);
    cfu_set(REG_PIXEL_ADVANCE_Y, (input_depth / 16) * input_width);
    cfu_set(REG_INPUT_CHANNEL_DEPTH, input_depth);
    cfu_set(REG_OUTPUT_CHANNEL_DEPTH, channels_per_tranche);
    cfu_set(REG_NUM_OUTPUT_VALUES, num_output_values_per_tranche);

    LoadFourPostProcessParameters(channel, bias_data, output_shift,
                                  output_multiplier);
    LoadFourFilterData(channel, filter_shape,
                       reinterpret_cast<const uint32_t*>(filter_data));

    // Start Accelerator
    cfu_set(REG_ACCELERATOR_START, 0);

    // Collect data
    CollectOutput(channel, reinterpret_cast<uint32_t*>(output_data),
                  output_height, output_width, output_depth);
  }
}

}  // namespace reference_integer_ops
}  // namespace tflite
#endif  // GATEWARE_GEN
<commit_msg>gen2/conv_accel_gen_2: Allow larger Conv2D ops<commit_after>/*
 * Copyright 2021 The CFU-Playground Authors
 * Copyright 2019 The TensorFlow Authors
 *
 * 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.
 */

#include "tensorflow/lite/kernels/internal/reference/integer_ops/conv_accel_gen_2.h"

#include <cstdio>

#include "gateware_constants.h"
#include "hps_cfu.h"
#include "tensorflow/lite/kernels/internal/common.h"

#if GATEWARE_GEN == 2

namespace tflite {
namespace reference_integer_ops {

namespace {

// Loads four post process parameters into the CFU
void LoadFourPostProcessParameters(int channel_start, const int32_t* bias_data,
                                   const int32_t* output_shift,
                                   const int32_t* output_multiplier) {
  for (int i = channel_start; i < channel_start + 4; i++) {
    cfu_set(REG_POST_PROCESS_BIAS, bias_data[i]);
    // Note : shift is stored as a negative number in tflite model
    cfu_set(REG_POST_PROCESS_SHIFT, -output_shift[i]);
    cfu_set(REG_POST_PROCESS_MULTIPLIER, output_multiplier[i]);
  }
}

// Loads filter parameters, correctly split between the two
// stores
void LoadFourFilterData(int channel_start, const RuntimeShape& filter_shape,
                        const uint32_t* data_base) {
  const int num_filter_words_per_output =
      filter_shape.Dims(1) * filter_shape.Dims(2) * filter_shape.Dims(3) / 4;
  const uint32_t* filter_data =
      data_base + channel_start * num_filter_words_per_output;

  size_t addr_base = 0;
  for (int i = channel_start; i < channel_start + 4; i += 2) {
    for (int store = 0; store < 2; store++) {
      uint32_t addr = addr_base;
      for (int j = 0; j < num_filter_words_per_output; j++) {
        uint32_t data = *filter_data++;
        cfu_setx(REG_FILTER_WRITE, (store << 16 | addr), data);
        addr++;
      }
    }
    addr_base += num_filter_words_per_output;
  }
}

// Collects a single ouput value and optionally places it into memory
inline void CollectValue(uint32_t*& p, int advance, bool write) {
  uint32_t val = cfu_get(REG_OUTPUT_WORD);
  if (write) {
    *p = val;
    p += advance;
  }
}

// Collects output from the accelerator into the output area
// Collects one word per output pixel
void CollectOutput(int channel, uint32_t* output, const int height,
                   const int width, const int depth) {
  const int num_pixels = height * width;
  const int num_words_per_pixel = depth / 4;

  uint32_t* p = output + channel / 4;

  for (int pixel = 0; pixel < num_pixels; pixel += 4) {
    CollectValue(p, num_words_per_pixel, true);
    CollectValue(p, num_words_per_pixel, pixel + 1 < num_pixels);
    CollectValue(p, num_words_per_pixel, pixel + 2 < num_pixels);
    CollectValue(p, num_words_per_pixel, pixel + 3 < num_pixels);
  }
}
};  // namespace

bool CanAccelerateConv4x4(const ConvParams& params,
                          const RuntimeShape& input_shape,
                          const RuntimeShape& filter_shape,
                          const RuntimeShape& output_shape,
                          const int32_t* bias_data) {
  // No padding allowed
  if (params.padding_type != PaddingType::kValid) return false;

  // Must have bias_data and single batch
  if (!bias_data) return false;
  const int batches = MatchingDim(input_shape, 0, output_shape, 0);
  if (batches != 1) return false;

  // Input and output depths must be a multiples of 16 and 4
  const int input_depth = input_shape.Dims(3);
  const int output_depth = output_shape.Dims(3);
  if (input_depth % 16 != 0) return false;
  if (output_depth % 4 != 0) return false;

  // Must be 4x4
  const int filter_height = filter_shape.Dims(1);
  const int filter_width = filter_shape.Dims(2);
  if (filter_height != 4 || filter_width != 4) return false;

  // Must fit in filter word storage
  const int filter_values_per_output =
      input_depth * filter_height * filter_width;
  // Calculate 4 output values per tranche
  const int filter_values = 4 * filter_values_per_output;
  // 4 values per word
  const int filter_words = filter_values / 4;
  if (filter_words > NUM_FILTER_STORES * FILTER_WORDS_PER_STORE) return false;

  // Dilation must be 1
  if (params.dilation_height_factor != 1 || params.dilation_width_factor != 1)
    return false;

  // Stride must be 1
  const int stride_width = params.stride_width;
  const int stride_height = params.stride_height;
  if (stride_height != 1 || stride_width != 1) return false;

  return true;
}

// Accelerated Conv2D
void ConvPerChannel4x4(const ConvParams& params,
                       const int32_t* output_multiplier,
                       const int32_t* output_shift,
                       const RuntimeShape& input_shape,
                       const int8_t* input_data,
                       const RuntimeShape& filter_shape,
                       const int8_t* filter_data,
                       const RuntimeShape& bias_shape, const int32_t* bias_data,
                       const RuntimeShape& output_shape, int8_t* output_data) {
  // Calculates in tranches of four channels (one output word)
  const int channels_per_tranche = 4;

  // Get parameters.
  const int32_t input_offset = params.input_offset;  // r = s(q - Z)
  // TODO: handle stride
  // const int stride_width = params.stride_width;
  // const int stride_height = params.stride_height;
  // TODO: handle padding
  // const int pad_width = params.padding_values.width;
  // const int pad_height = params.padding_values.height;
  const int32_t output_offset = params.output_offset;

  // Set min and max value of the output.
  const int32_t output_activation_min = params.quantized_activation_min;
  const int32_t output_activation_max = params.quantized_activation_max;

  // Consistency checks
  TFLITE_DCHECK_LE(output_activation_min, output_activation_max);
  TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4);
  TFLITE_DCHECK_EQ(filter_shape.DimensionsCount(), 4);
  TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4);
  const int input_depth = MatchingDim(input_shape, 3, filter_shape, 3);
  const int output_depth = MatchingDim(filter_shape, 0, output_shape, 3);
  TFLITE_DCHECK_EQ(bias_shape.FlatSize(), output_depth);

  // Get dimensions of the tensors.
  const int input_width = input_shape.Dims(2);
  const int output_height = output_shape.Dims(1);
  const int output_width = output_shape.Dims(2);

  // Round up output values to next multiple of 16
  const int num_output_values_per_tranche =
      (output_width * output_height * channels_per_tranche + 15) / 16 * 16;

  // Filter words required to calculate each tranche
  const int filter_words_per_channel =
      filter_shape.Dims(1) * filter_shape.Dims(2) * filter_shape.Dims(3) / 4;
  const int filter_words_per_tranche =
      filter_words_per_channel * channels_per_tranche;

  // Base address is bank address (4 words per bank) within 256K arena
  uint32_t input_base_addr =
      (reinterpret_cast<uint32_t>(input_data) & 0x3ffff) / 16;

  for (int channel = 0; channel < output_depth;
       channel += channels_per_tranche) {
    // Reset to ensure important state is initialized
    cfu_set(REG_ACCELERATOR_RESET, 0);

    // Configure simple values
    cfu_set(REG_INPUT_OFFSET, input_offset);
    cfu_set(REG_NUM_FILTER_WORDS, filter_words_per_tranche / 2);
    cfu_set(REG_OUTPUT_OFFSET, output_offset);
    cfu_set(REG_OUTPUT_ACTIVATION_MIN, output_activation_min);
    cfu_set(REG_OUTPUT_ACTIVATION_MAX, output_activation_max);
    cfu_set(REG_INPUT_BASE_ADDR, input_base_addr);
    cfu_set(REG_NUM_PIXELS_X, output_width);
    cfu_set(REG_PIXEL_ADVANCE_X, input_depth / 16);
    cfu_set(REG_PIXEL_ADVANCE_Y, (input_depth / 16) * input_width);
    cfu_set(REG_INPUT_CHANNEL_DEPTH, input_depth);
    cfu_set(REG_OUTPUT_CHANNEL_DEPTH, channels_per_tranche);
    cfu_set(REG_NUM_OUTPUT_VALUES, num_output_values_per_tranche);

    LoadFourPostProcessParameters(channel, bias_data, output_shift,
                                  output_multiplier);
    LoadFourFilterData(channel, filter_shape,
                       reinterpret_cast<const uint32_t*>(filter_data));

    // Start Accelerator
    cfu_set(REG_ACCELERATOR_START, 0);

    // Collect data
    CollectOutput(channel, reinterpret_cast<uint32_t*>(output_data),
                  output_height, output_width, output_depth);
  }
}

}  // namespace reference_integer_ops
}  // namespace tflite
#endif  // GATEWARE_GEN
<|endoftext|>


<commit_before>
#include "rootdir.h"

RootDir::RootDir():m_dirs(0){
  m_dirs = new Dir[32];
}

RootDir::~RootDir(){
  delete []m_dirs;
}

<commit_msg>again getting rid of that hardcoded number<commit_after>
#include "rootdir.h"

#define DIR_ENTRIES 32

RootDir::RootDir():m_dirs(0){
  m_dirs = new Dir[DIR_ENTRIES];
}

RootDir::~RootDir(){
  delete []m_dirs;
}

<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011-2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <vector>

#include "iterators.hpp"
#include "logging.hpp"
#include "GlobalContext.hpp"

#include "mtac/remove_empty_functions.hpp"
#include "mtac/Utils.hpp"
#include "mtac/Quadruple.hpp"

using namespace eddic;

bool mtac::remove_empty_functions::operator()(mtac::Program& program){
    std::vector<std::string> removed_functions;

    bool changes = false;

    auto it = iterate(program.functions);

    while(it.has_next()){
        auto& function = *it;

        if(function.is_main()){
            ++it;
            continue;
        }

        unsigned int statements = function.size_no_nop();

        if(statements == 0){
            program.context->stats().inc_counter("empty_function_removed");
            LOG<Debug>("Optimizer") << "Remove empty function " << function.get_name() << log::endl;
            changes = true;

            removed_functions.push_back(function.get_name());
            it.erase();
        } else {
            ++it;
        }
    }

    if(!removed_functions.empty()){
        for(auto& function : program.functions){
            for(auto& block : function){
                auto fit = block->statements.begin();

                while(fit != block->statements.end()){
                    auto& quadruple = *fit;

                    if(quadruple.op == mtac::Operator::CALL){
                        auto function_name = quadruple.function().mangled_name();

                        if(std::find(removed_functions.begin(), removed_functions.end(), function_name) != removed_functions.end()){
                            //Update the call graph
                            --program.call_graph.edge(function.definition(), quadruple.function())->count;

                            int parameters = quadruple.function().parameters().size();

                            if(parameters > 0){
                                //The parameters are in the previous block
                                if(fit == block->statements.begin()){
                                    auto previous = block->prev;

                                    auto fend = previous->statements.end();
                                    --fend;

                                    while(parameters > 0){
                                        fend = previous->statements.erase(fend);
                                        --fend;

                                        --parameters;
                                    }

                                    fit = block->statements.erase(fit);
                                }
                                //The parameters are in the same block
                                else {
                                    while(parameters >= 0){
                                        fit = block->statements.erase(fit);
                                        --fit;

                                        --parameters;
                                    }
                                }

                            } else {
                                fit = block->statements.erase(fit);
                            }

                            continue;
                        }
                    }

                    ++fit;
                }
            }
        }
    }

    return changes;
}
<commit_msg>STL Refactor<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011-2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <vector>

#include "iterators.hpp"
#include "logging.hpp"
#include "GlobalContext.hpp"

#include "mtac/remove_empty_functions.hpp"
#include "mtac/Utils.hpp"
#include "mtac/Quadruple.hpp"

using namespace eddic;

bool mtac::remove_empty_functions::operator()(mtac::Program& program){
    std::vector<std::string> removed_functions;

    program.functions.erase(std::remove_if(program.functions.begin(), program.functions.end(),
        [&program,&removed_functions](auto& function){
            if(!function.is_main() && function.size_no_nop() == 0){
                program.context->stats().inc_counter("empty_function_removed");
                LOG<Debug>("Optimizer") << "Remove empty function " << function.get_name() << log::endl;

                removed_functions.push_back(function.get_name());

                return true;
            }

            return false;
        }), program.functions.end());

    if(!removed_functions.empty()){
        for(auto& function : program.functions){
            for(auto& block : function){
                auto fit = block->statements.begin();

                while(fit != block->statements.end()){
                    auto& quadruple = *fit;

                    if(quadruple.op == mtac::Operator::CALL){
                        auto function_name = quadruple.function().mangled_name();

                        if(std::find(removed_functions.begin(), removed_functions.end(), function_name) != removed_functions.end()){
                            //Update the call graph
                            --program.call_graph.edge(function.definition(), quadruple.function())->count;

                            int parameters = quadruple.function().parameters().size();

                            if(parameters > 0){
                                //The parameters are in the previous block
                                if(fit == block->statements.begin()){
                                    auto previous = block->prev;

                                    auto fend = previous->statements.end();
                                    --fend;

                                    while(parameters > 0){
                                        fend = previous->statements.erase(fend);
                                        --fend;

                                        --parameters;
                                    }

                                    fit = block->statements.erase(fit);
                                }
                                //The parameters are in the same block
                                else {
                                    while(parameters >= 0){
                                        fit = block->statements.erase(fit);
                                        --fit;

                                        --parameters;
                                    }
                                }

                            } else {
                                fit = block->statements.erase(fit);
                            }

                            continue;
                        }
                    }

                    ++fit;
                }
            }
        }
    }

    return !removed_functions.empty();
}
<|endoftext|>